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
013970cd616bd63313ef2edb37f436d1fcd1753d
105
import UIKit class Cast: NSObject { var alt: String? var id: String? var name: String? }
10.5
22
0.609524
67178697737a6aa1b8bda90fad99ff1b53f2e5ed
256
import XCTest class Notes97UITests: XCTestCase { override func setUp() { super.setUp() XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testExample() { } }
19.692308
36
0.535156
141b8fefbbb0cd7e4f5047b7e61c41d093329031
3,553
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class RootViewController: UIViewController { /// NavigationBar buttons. private var menuButton: IconButton! private var starButton: IconButton! private var searchButton: IconButton! /// Trigger to go to the next view controller. private var nextButton: FlatButton! open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Color.grey.lighten5 prepareMenuButton() prepareStarButton() prepareSearchButton() prepareNavigationItem() prepareNextButton() } internal func handleNextButton() { navigationController?.pushViewController(NextViewController(), animated: true) } private func prepareMenuButton() { menuButton = IconButton(image: Icon.cm.menu, tintColor: Color.white) menuButton.pulseColor = Color.white } private func prepareStarButton() { starButton = IconButton(image: Icon.cm.star, tintColor: Color.white) starButton.pulseColor = Color.white } private func prepareSearchButton() { searchButton = IconButton(image: Icon.cm.search, tintColor: Color.white) searchButton.pulseColor = Color.white } private func prepareNavigationItem() { navigationItem.title = "Material" navigationItem.titleLabel.textColor = Color.white navigationItem.detail = "Build Beautiful Software" navigationItem.detailLabel.textColor = Color.lightBlue.lighten5 navigationItem.leftViews = [menuButton] navigationItem.rightViews = [starButton, searchButton] } private func prepareNextButton() { nextButton = FlatButton() nextButton.pulseAnimation = .none nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside) view.layout(nextButton).edges() } }
38.619565
92
0.713763
3939c9581dc0ebec47ca43f63b193d5454260437
4,529
/* LoginPage.swift Created by Eric Engelking on 10/16/15. Copyright (c) 2016-present, salesforce.com, inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of salesforce.com, inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import XCTest class HostPage: PageObject, PageThatWaits { fileprivate var ChooseConnectionButton: XCUIElement { get { return app.navigationBars["Log In"].buttons["Choose Connection"] } } fileprivate var AddConnectionButton: XCUIElement { get { return app.navigationBars["Choose Connection"].buttons["Add"] } } fileprivate var CancelConnectionButton: XCUIElement { get { return app.navigationBars["Choose Connection"].buttons["Cancel"] } } fileprivate var BackConnectionButton: XCUIElement { get { return app.navigationBars["Add Connection"].buttons["Back"] } } fileprivate var DoneAdd: XCUIElement { get { return app.navigationBars["Add Connection"].buttons["Done"] } } fileprivate var HostField: XCUIElement { get { return app.tables.textFields["Host (Example: login.salesforce.com)"] } } fileprivate var LabelField: XCUIElement { get { return app.tables.textFields["Label (Optional)"] } } func waitForPageInvalid() { waitForElementDoesNotExist(AddConnectionButton) } func waitForPageLoaded() { waitForElementExists(AddConnectionButton) } // MARK: Act on screen @discardableResult func chooseConnection(_ host: String) -> LoginPage { app.tables.staticTexts[host].tap() return LoginPage() } func setLabel(_ label: String) { LabelField.tap() LabelField.typeText(label) } func setHost(_ host: String) { HostField.tap() HostField.typeText(host) } @discardableResult func addAndChooseConnection(_ label: String, host: String!) -> LoginPage { AddConnectionButton.tap() setLabel(label) setHost(host) DoneAdd.tap() let loginPage = LoginPage() loginPage.waitForPageLoaded() return loginPage } func addAndCancel(_ toLogin: Bool) { waitForElementEnabled(app.navigationBars["Choose Connection"].buttons["Add"]) AddConnectionButton.tap() setHost("dummy") BackConnectionButton.tap() if (toLogin) { CancelConnectionButton.tap() } } @discardableResult func selectHost(_ host: String) -> LoginPage { if (!app.tables.staticTexts[host].exists) { addAndChooseConnection("", host: host) } else { app.tables.staticTexts[host].tap() } let loginPage = LoginPage() loginPage.waitForPageLoaded() return loginPage } func deleteHost(_ label: String!) { app.tables.staticTexts[label].swipeLeft() app.tables.buttons["Delete"].tap() } }
31.894366
98
0.667476
d6cf5e0d007fc2b83e6d3b2a569548a9d5b0cefd
8,640
// // Poly1305.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 30/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // // http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4 // /// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the /// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message. final public class Poly1305: Authenticator { public enum Error: Swift.Error { case authenticateError } let blockSize = 16 private var ctx:Context? private final class Context { var r = Array<UInt8>(repeating: 0, count: 17) var h = Array<UInt8>(repeating: 0, count: 17) var pad = Array<UInt8>(repeating: 0, count: 17) var buffer = Array<UInt8>(repeating: 0, count: 16) var final:UInt8 = 0 var leftover:Int = 0 init(_ key: Array<UInt8>) { precondition(key.count == 32, "Invalid key length") for i in 0..<17 { h[i] = 0 } r[0] = key[0] & 0xff; r[1] = key[1] & 0xff; r[2] = key[2] & 0xff; r[3] = key[3] & 0x0f; r[4] = key[4] & 0xfc; r[5] = key[5] & 0xff; r[6] = key[6] & 0xff; r[7] = key[7] & 0x0f; r[8] = key[8] & 0xfc; r[9] = key[9] & 0xff; r[10] = key[10] & 0xff; r[11] = key[11] & 0x0f; r[12] = key[12] & 0xfc; r[13] = key[13] & 0xff; r[14] = key[14] & 0xff; r[15] = key[15] & 0x0f; r[16] = 0 for i in 0..<16 { pad[i] = key[i + 16] } pad[16] = 0 leftover = 0 final = 0 } deinit { for i in 0..<buffer.count { buffer[i] = 0 } for i in 0..<r.count { r[i] = 0 h[i] = 0 pad[i] = 0 final = 0 leftover = 0 } } } /// - parameter key: 32-byte key public init (key: Array<UInt8>) { ctx = Context(key) } // MARK: - Private /** Add message to be processed - parameter context: Context - parameter message: message - parameter bytes: length of the message fragment to be processed */ private func update(_ context:Context, message:Array<UInt8>, bytes:Int? = nil) { var bytes = bytes ?? message.count var mPos = 0 /* handle leftover */ if (context.leftover > 0) { var want = blockSize - context.leftover if (want > bytes) { want = bytes } for i in 0..<want { context.buffer[context.leftover + i] = message[mPos + i] } bytes -= want mPos += want context.leftover += want if (context.leftover < blockSize) { return } blocks(context, m: context.buffer) context.leftover = 0 } /* process full blocks */ if (bytes >= blockSize) { let want = bytes & ~(blockSize - 1) blocks(context, m: message, startPos: mPos) mPos += want bytes -= want; } /* store leftover */ if (bytes > 0) { for i in 0..<bytes { context.buffer[context.leftover + i] = message[mPos + i] } context.leftover += bytes } } private func finish(_ context:Context) -> Array<UInt8>? { var mac = Array<UInt8>(repeating: 0, count: 16); /* process the remaining block */ if (context.leftover > 0) { context.buffer[context.leftover] = 1 for i in (context.leftover + 1)..<blockSize { context.buffer[i] = 0 } context.final = 1 blocks(context, m: context.buffer) } /* fully reduce h */ freeze(context) /* h = (h + pad) % (1 << 128) */ add(context, c: context.pad) for i in 0..<mac.count { mac[i] = context.h[i] } return mac } // MARK: - Utils private func add(_ context:Context, c:Array<UInt8>) { if (context.h.count != 17 && c.count != 17) { assertionFailure() return } var u:UInt16 = 0 for i in 0..<17 { u += UInt16(context.h[i]) + UInt16(c[i]) context.h[i] = UInt8.with(value: u) u = u >> 8 } return } private func squeeze(_ context:Context, hr:Array<UInt32>) { if (context.h.count != 17 && hr.count != 17) { assertionFailure() return } var u:UInt32 = 0 for i in 0..<16 { u += hr[i]; context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff u >>= 8; } u += hr[16] context.h[16] = UInt8.with(value: u) & 0x03 u >>= 2 u += (u << 2); /* u *= 5; */ for i in 0..<16 { u += UInt32(context.h[i]) context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff u >>= 8 } context.h[16] += UInt8.with(value: u); } private func freeze(_ context:Context) { assert(context.h.count == 17,"Invalid length") if (context.h.count != 17) { return } let minusp:Array<UInt8> = [0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc] var horig:Array<UInt8> = Array<UInt8>(repeating: 0, count: 17) /* compute h + -p */ for i in 0..<17 { horig[i] = context.h[i] } add(context, c: minusp) /* select h if h < p, or h + -p if h >= p */ let bits:[Bit] = (context.h[16] >> 7).bits() let invertedBits = bits.map({ (bit) -> Bit in return bit.inverted() }) let negative = UInt8(bits: invertedBits) for i in 0..<17 { context.h[i] ^= negative & (horig[i] ^ context.h[i]); } } private func blocks(_ context:Context, m:Array<UInt8>, startPos:Int = 0) { var bytes = m.count let hibit = context.final ^ 1 // 1 <<128 var mPos = startPos while (bytes >= Int(blockSize)) { var hr:Array<UInt32> = Array<UInt32>(repeating: 0, count: 17) var u:UInt32 = 0 var c:Array<UInt8> = Array<UInt8>(repeating: 0, count: 17) /* h += m */ for i in 0..<16 { c[i] = m[mPos + i] } c[16] = hibit add(context, c: c) /* h *= r */ for i in 0..<17 { u = 0 for j in 0...i { u = u + UInt32(UInt16(context.h[j])) * UInt32(context.r[i - j]) // u += (unsigned short)st->h[j] * st->r[i - j]; } for j in (i+1)..<17 { var v:UInt32 = UInt32(UInt16(context.h[j])) * UInt32(context.r[i + 17 - j]) // unsigned long v = (unsigned short)st->h[j] * st->r[i + 17 - j]; v = ((v << 8) &+ (v << 6)) u = u &+ v } hr[i] = u } squeeze(context, hr: hr) mPos += blockSize bytes -= blockSize } } //MARK: - Authenticator /** Calculate Message Authentication Code (MAC) for message. Calculation context is discarder on instance deallocation. - parameter bytes: Message - returns: 16-byte tag that authenticates the message */ public func authenticate(_ bytes:Array<UInt8>) throws -> Array<UInt8> { guard let ctx = self.ctx else { throw Error.authenticateError } update(ctx, message: bytes) guard let result = finish(ctx) else { throw Error.authenticateError } return result } }
28.8
163
0.441782
e2018fdf45fa594ec840a537c750c4436250183d
1,412
// // Completion.swift // CodeEditor // // Copyright © 2021 SCADE Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // public protocol CompletionItem { var label: String { get } var detail: String? { get } var documentation: Documentation? { get } var filterText: String? { get } var insertText: String? { get } var textEdit: TextEdit? { get } var kind: CompletionItemKind { get } } public enum CompletionItemKind: Int { case unknown = 0, // LSP 1+ text, method, function, constructor, field, variable, `class`, interface, module, property, unit, value, reference, `enum`, keyword, snippet, color, file, // LSP 3+ folder, enumMember, constant, `struct`, event, `operator`, typeParameter }
23.533333
76
0.63102
e4210fd850d985e5afe97f6bda94a0c778c14148
2,153
/// `URLEncodedSerialization` parses `Data` and `String` as urlencoded, /// and returns dictionary that represents the data or the string. public final class URLEncodedSerialization { /// Returns urlencoded `String` from the dictionary. public static func string(from dictionary: [String: Any]) -> String { let pairs = dictionary.map { key, value -> String in if value is NSNull { return "\(escape(key))" } let valueAsString = (value as? String) ?? "\(value)" return "\(escape(key))=\(escape(valueAsString))" } return pairs.joined(separator: "&") } private static func escape(_ string: String) -> String { // Reserved characters defined by RFC 3986 // Reference: https://www.ietf.org/rfc/rfc3986.txt let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" let reservedCharacters = generalDelimiters + subDelimiters var allowedCharacterSet = CharacterSet() allowedCharacterSet.formUnion(.urlQueryAllowed) allowedCharacterSet.remove(charactersIn: reservedCharacters) // Crashes due to internal bug in iOS 7 ~ iOS 8.2. // References: // - https://github.com/Alamofire/Alamofire/issues/206 // - https://github.com/AFNetworking/AFNetworking/issues/3028 // return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string let batchSize = 50 var index = string.startIndex var escaped = "" while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = String(string[range]) escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring index = endIndex } return escaped } }
38.446429
114
0.597771
5665de1bf5a30076629dbd5d52a3da3fe02ad1cc
582
// // AppDelegate.swift // LanguageManager-iOS // // Created by Abedalkareem on 08/09/2018. // Copyright (c) 2018 Abedalkareem. All rights reserved. // import UIKit import LanguageManager_iOS @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Set the default language for the app LanguageManager.shared.defaultLanguage = .en return true } }
20.068966
145
0.725086
61aa8309687b29671523c4c72b93875ee22a9b68
402
// // ViewController.swift // BurstXBundle // // Created by Andrew Scott on 2/2/18. // import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
16.08
58
0.61194
7a17f2498f859fb5661d129437cf9e1eccf3ad66
2,961
// // Webservice.swift // Weather // // Created by Tales Pinheiro De Andrade on 20/10/18. // Copyright © 2018 Tales Pinheiro De Andrade. All rights reserved. // import Foundation enum Result<T, E: Error> { case success(T) case failure(E) init(_ value: T) { self = Result.success(value) } init(_ value: E) { self = Result.failure(value) } } enum NetworkError: Error { case invalidData case emptyData case clientError(String) case redirection case serverError case networkError(String) case unknowm } final class Webservice: NSObject { let urlSession: URLSession init(urlSession: URLSession = URLSession(configuration: URLSessionConfiguration.default)) { self.urlSession = urlSession } func load<T>(_ resource: Resource<T>, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, NetworkError>) -> Void) -> URLSessionDataTask { let request = URLRequest(resource: resource) let task = urlSession.dataTask(with: request) { [unowned self] data, urlResponse, error in let result: Result<T, NetworkError> if let response = urlResponse as? HTTPURLResponse, let status = response.status, let data = data { switch status.responseType { case .success: result = self.parse(data, for: resource, error: error) case .redirection: result = Result(.redirection) case .clientError: let message = "[\(response.statusCode)]: \(HTTPURLResponse.localizedString(forStatusCode: response.statusCode))" result = Result(NetworkError.clientError(message)) case .serverError: result = Result(.serverError) default: result = Result(.unknowm) } } else if let error = error { result = Result(.networkError(error.localizedDescription)) } else { result = Result(.unknowm) } completion(result) } task.resume() return task } private func parse<T>(_ data: Data?, for resource: Resource<T>, error: Error?) -> Result<T, NetworkError> where T: Decodable { let result: Result<T, NetworkError> if let data = data { do { result = try Result(resource.parse(data)) } catch { result = Result(NetworkError.invalidData) } } else if let error = error { print(error.localizedDescription) fatalError("FIXME") } else { result = Result(NetworkError.emptyData) } return result } }
29.029412
132
0.544411
0894cc585fba8f912d8eed68843ecbfbcdd0712e
2,399
// // Created by Swen van Zanten on 2019-02-12. // Copyright (c) 2019 Verge Currency. All rights reserved. // import Foundation import BitcoinKit import CryptoSwift public class Credentials { enum CredentialsError: Error { case invalidDeriver(value: String) } var seed: Data = Data() var network: Network = .mainnetXVG init(mnemonic: [String], passphrase: String, network: Network = .mainnetXVG) { self.seed = Mnemonic.seed(mnemonic: mnemonic, passphrase: passphrase) self.network = network } public func reset(mnemonic: [String], passphrase: String, network: Network = .mainnetXVG) { self.seed = Mnemonic.seed(mnemonic: mnemonic, passphrase: passphrase) self.network = network } public var privateKey: HDPrivateKey { return HDPrivateKey(seed: seed, network: network) } public var walletPrivateKey: HDPrivateKey { return try! privateKey.derived(at: 0, hardened: true) } public var requestPrivateKey: HDPrivateKey { return try! privateKey.derived(at: 1, hardened: true).derived(at: 0) } public var bip44PrivateKey: HDPrivateKey { return try! privateKey .derived(at: 44, hardened: true) .derived(at: 0, hardened: true) .derived(at: 0, hardened: true) } public var publicKey: HDPublicKey { return bip44PrivateKey.extendedPublicKey() } public var personalEncryptingKey: String { let data = Crypto.sha256(requestPrivateKey.privateKey().data) let key = "personalKey".data(using: .utf8)! let b2 = try! HMAC(key: key.bytes, variant: .sha256).authenticate(data.bytes) return Data(b2[0..<16]).base64EncodedString() } public var sharedEncryptingKey: String { let sha256Data = walletPrivateKey.privateKey().data.sha256() return sha256Data[0..<16].base64EncodedString() } public func privateKeyBy(path: String, privateKey: HDPrivateKey) throws -> PrivateKey { var key = privateKey for deriver in path.replacingOccurrences(of: "m/", with: "").split(separator: "/") { guard let deriverInt32 = UInt32(deriver) else { throw CredentialsError.invalidDeriver(value: String(deriver)) } key = try key.derived(at: deriverInt32) } return key.privateKey() } }
29.617284
95
0.648187
e5a29a777f68271def37afaa35ad8eb2db6388e4
814
// // RenderNode.swift // lottie-swift // // Created by Brandon Withrow on 1/17/19. // import Foundation import CoreGraphics import QuartzCore /// A protocol that defines a node that holds render instructions protocol RenderNode { var renderer: Renderable & NodeOutput { get } } /// A protocol that defines anything with render instructions protocol Renderable { /// The last frame in which this node was updated. var hasUpdate: Bool { get } func hasRenderUpdates(_ forFrame: CGFloat) -> Bool /// Opportunity for renderers to inject sublayers func setupSublayers(layer: CAShapeLayer) /// Passes in the CAShapeLayer to update func updateShapeLayer(layer: CAShapeLayer) } extension RenderNode where Self: AnimatorNode { var outputNode: NodeOutput { return renderer } }
20.871795
65
0.72973
0a996745fd6220e8bd9b6b015f45758cef84fe6a
302
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S<T { class b { { { } { } } let start = A protocol A func a { class A { class A { { { { } { } } } class A { func f func f(T.c
10.413793
87
0.655629
0e25583aeb33ba575a1ee4ef255e8e4bf2155d38
4,521
import Foundation import UIKit import DPLibrary // MARK: - Output public protocol DateFieldAdapterOutput: AnyObject { func didErrors(adapter: DateFieldAdapter, errors: FieldValidations) func didControlEvent(adapter: DateFieldAdapter, event: UIControl.Event) func didDateChanged(adapter: DateFieldAdapter, date: Date?) func didTapClearButton(adapter: DateFieldAdapter) } public extension DateFieldAdapterOutput { func didErrors(adapter: DateFieldAdapter, errors: FieldValidations) {} func didControlEvent(adapter: DateFieldAdapter, event: UIControl.Event) {} func didDateChanged(adapter: DateFieldAdapter, date: Date?) {} func didTapClearButton(adapter: DateFieldAdapter) {} } // MARK: - Adapter open class DateFieldAdapter: Field<Date>, UITextFieldDelegate { // MARK: - Props public weak var textField: UITextField? { didSet { self.textField?.delegate = self self.setDatePicker() self.textField?.text = self.value?.toLocalString(withFormatType: self.dateFormatType) } } public let datePicker = UIDatePicker() public var minDate: Date? { didSet { self.setDatePicker() } } public var maxDate: Date? { didSet { self.setDatePicker() } } public var dateFormatType: DateFormatType = .default public weak var output: DateFieldAdapterOutput? public override var value: Date? { didSet { self.textField?.text = self.value?.toLocalString(withFormatType: self.dateFormatType) self.output?.didDateChanged(adapter: self, date: self.value) } } public override var errors: FieldValidations { didSet { self.output?.didErrors(adapter: self, errors: self.errors) } } // MARK: - Init public init(minDate: Date?, maxDate: Date?, validations: FieldValidations, value: Date?) { self.minDate = minDate self.maxDate = maxDate super.init(validations: validations, value: value) self.datePicker.date = value ?? maxDate ?? .init() } // MARK: - Public methods open func provideControlEvent(_ event: UIControl.Event) { switch event { case .editingDidBegin: self.errors = [] case .valueChanged, .editingChanged: self.generateErrors(with: .realTime) case .editingDidEnd: self.generateErrors(with: .any) default: break } self.output?.didControlEvent(adapter: self, event: event) } open func setDatePicker() { self.datePicker.frame = .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 216) self.datePicker.datePickerMode = .date self.datePicker.addTarget(self, action: #selector(self.datePickerValueChanged), for: .valueChanged) if let minDate = self.minDate { self.datePicker.minimumDate = minDate } if let maxDate = self.maxDate { self.datePicker.maximumDate = maxDate } if #available(iOS 14, *) { self.datePicker.preferredDatePickerStyle = .wheels self.datePicker.sizeToFit() } self.textField?.inputView = self.datePicker } // MARK: - Private methods @objc private func datePickerValueChanged() { self.value = self.datePicker.date } // MARK: - UITextFieldDelegate public func textFieldDidBeginEditing(_ textField: UITextField) { self.provideControlEvent(.editingDidBegin) } public func textFieldDidEndEditing(_ textField: UITextField) { self.provideControlEvent(.editingDidEnd) } public func textFieldShouldClear(_ textField: UITextField) -> Bool { self.output?.didTapClearButton(adapter: self) self.value = nil return true } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text, let textRange = Range(range, in: text) else { return true } let updatedText = text.replacingCharacters(in: textRange, with: string) let errors = self.validations.map({ $0.validate(for: updatedText, with: .realTime) }).filter({ $0 != nil }) self.errors = errors as? FieldValidations ?? [] return errors.isEmpty } }
32.06383
136
0.634152
2f5bdd9313257038dea4a1d10f8fa429e38da901
2,480
// // SurveyForm.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class SurveyForm: Codable { /** The globally unique identifier for the object. */ public var _id: String? /** The survey form name */ public var name: String? /** Last modified date. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z */ public var modifiedDate: Date? /** Is this form published */ public var published: Bool? /** Is this form disabled */ public var disabled: Bool? /** Unique Id for all versions of this form */ public var contextId: String? /** Language for survey viewer localization. Currently localized languages: da, de, en-US, es, fi, fr, it, ja, ko, nl, no, pl, pt-BR, sv, th, tr, zh-CH, zh-TW */ public var language: String? /** Markdown text for the top of the form. */ public var header: String? /** Markdown text for the bottom of the form. */ public var footer: String? /** A list of question groups */ public var questionGroups: [SurveyQuestionGroup]? /** List of published version of this form */ public var publishedVersions: DomainEntityListingSurveyForm? /** The URI for this object */ public var selfUri: String? public init(_id: String?, name: String?, modifiedDate: Date?, published: Bool?, disabled: Bool?, contextId: String?, language: String?, header: String?, footer: String?, questionGroups: [SurveyQuestionGroup]?, publishedVersions: DomainEntityListingSurveyForm?, selfUri: String?) { self._id = _id self.name = name self.modifiedDate = modifiedDate self.published = published self.disabled = disabled self.contextId = contextId self.language = language self.header = header self.footer = footer self.questionGroups = questionGroups self.publishedVersions = publishedVersions self.selfUri = selfUri } public enum CodingKeys: String, CodingKey { case _id = "id" case name case modifiedDate case published case disabled case contextId case language case header case footer case questionGroups case publishedVersions case selfUri } }
29.176471
284
0.621371
b934bd7cd761ed7b1d0bdc27775f8bebc977c9cf
1,076
import UIKit class ViewController: UIViewController { @IBOutlet weak var customJKView: JKCircleView! override func viewDidLoad() { customJKView.animationDuration = 3 customJKView.lineWidth = 10 customJKView.isToRemoveLayerAfterCompletion = true } @IBAction func tapsDrawCircle(_ sender: UIButton) { addFullCircleView() } ///angle = 1 is 360 degree, angle = 0.5 is 180 degree --set as your use case 0 < angle <1 func addFullCircleView() { customJKView.animateCircle(angle: 1) } @IBAction func tapsOnNext(_ sender: Any) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController navigationController?.pushViewController(vc, animated: true) } } //or //Create a new CircleView programetically -> //let circleView = JKCircleView(frame: CGRect(x: 50, y: 250, width: 200, height: 200)) //let test = CircleView(frame: CGRect(x: diceRoll, y: 0, width: circleWidth, height: circleHeight)) //view.addSubview(circleView)
37.103448
124
0.699814
0ad74e063230e42001e13cf72fead5ee64a0bc20
9,547
// // Transition.swift // Movin // // Created by xxxAIRINxxx on 2018/08/02. // Copyright © 2018 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit public enum TransitionType { case push case pop case present case dismiss public var reversedType: TransitionType { switch self { case .push: return .pop case .pop: return .push case .present: return .dismiss case .dismiss: return .present } } public var isPresenting: Bool { return self == .push || self == .present } public var isDismissing: Bool { return self == .pop || self == .dismiss } } open class Transition: NSObject { public fileprivate(set) weak var movin: Movin! public let fromVC: UIViewController public let toVC: UIViewController public let gestureTransitioning: GestureTransitioning? public var customContainerViewSetupHandler: ((TransitionType, UIView) -> Void)? public var customContainerViewCompletionHandler: ((TransitionType, Bool, UIView) -> Void)? public fileprivate(set) var isInteractiveTransition: Bool = false public fileprivate(set) var animatedTransitioning: AnimatedTransitioning? public fileprivate(set) var interactiveTransitioning: InteractiveTransitioning? public fileprivate(set) var completion: ((TransitionType, Bool) -> Void)? deinit { Movin.dp("Transition - deinit") } public init(_ movin: Movin, _ fromVC: UIViewController, _ toVC: UIViewController, _ gestureTransitioning: GestureTransitioning?) { Movin.dp("Transition - init") self.movin = movin self.fromVC = fromVC self.toVC = toVC self.gestureTransitioning = gestureTransitioning super.init() self.handleInteractiveGestureIfNeeded() } @discardableResult public func configureCompletion(_ completion: ((TransitionType, Bool) -> Void)?) -> Transition { Movin.dp("Transition - configureCompletion") self.completion = completion return self } open func prepareTransition(_ type: TransitionType, _ transitionContext: UIViewControllerContextTransitioning) { Movin.dp("Transition - prepareTransition type: \(type)") let containerView = transitionContext.containerView if let handler = self.customContainerViewSetupHandler { handler(type, containerView) } else { if !self.toVC.isOverContext { containerView.addSubview(self.fromVC.view) } containerView.addSubview(self.toVC.view) } self.movin.beforeAnimation() self.movin.configureAnimations(AnimationDirection(self.movin.duration, type.isPresenting)) if type.isDismissing { self.movin.animator.startAnimation() self.movin.animator.pauseAnimation() self.movin.animator.fractionComplete = 1.0 self.movin.animator.isReversed = true } } open func currentTransitionType() -> TransitionType? { Movin.dp("Transition - currentTransitionType") if let type = self.gestureTransitioning?.currentType() { return type } if let type = self.animatedTransitioning?.type { return type } return nil } open func configureInteractiveTransitioningIfNeeded() -> InteractiveTransitioning? { Movin.dp("Transition - configureInteractiveTransitioningIfNeeded") if !self.isInteractiveTransition { return nil } self.setInteractiveTransitioningIfNeeded() self.handleInteractiveGestureIfNeeded() return self.interactiveTransitioning } open func setInteractiveTransitioningIfNeeded() { Movin.dp("Transition - setInteractiveTransitioningIfNeeded") self.interactiveTransitioning = nil guard let type = self.gestureTransitioning?.currentType(), self.gestureTransitioning?.hasGesture(type) == true else { return } self.interactiveTransitioning = InteractiveTransitioning(self, type) } open func handleInteractiveGestureIfNeeded() { Movin.dp("Transition - handleInteractiveGestureIfNeeded") guard let type = self.currentTransitionType(), let gesture = self.gestureTransitioning?.gesture(type) else { return } gesture.updateGestureHandler = { [weak self] completed in if #available(iOS 11.0, *) { self?.movin.interactiveAnimate(completed) self?.interactiveTransitioning?.update(completed) } else { if self?.currentTransitionType()?.isPresenting == true { self?.movin.interactiveAnimate(completed) self?.interactiveTransitioning?.update(completed) } else { let c = 1.0 - completed self?.movin.interactiveAnimate(c) self?.interactiveTransitioning?.update(c) } } } gesture.updateGestureStateHandler = { [weak self] state in switch state { case .began: self?.startInteractiveTransition() case .changed: break case .ended: if self?.gestureTransitioning?.gesture(type)?.isCompleted == true { self?.interactiveTransitioning?.finish() } else { self?.interactiveTransitioning?.cancel() } case .cancelled, .failed: self?.interactiveTransitioning?.cancel() default: break } } } open func startInteractiveTransition() { Movin.dp("Transition - startInteractiveTransition") guard let type = self.currentTransitionType() else { return } self.isInteractiveTransition = true switch type { case .push: self.fromVC.navigationController?.pushViewController(self.toVC, animated: true) case .present: self.fromVC.present(self.toVC, animated: true, completion: nil) case .pop: _ = self.fromVC.navigationController?.popViewController(animated: true) case .dismiss: self.fromVC.dismiss(animated: true, completion: nil) } } func finishTransition(_ type: TransitionType, _ didComplete: Bool, _ containerView: UIView) { Movin.dp("Transition - startInteractiveTransition type: \(type)") self.gestureTransitioning?.finishTransition(type, didComplete) self.animatedTransitioning = nil self.isInteractiveTransition = false if let c = self.customContainerViewCompletionHandler { c(type, didComplete, containerView) } else { self.completion?(type, didComplete) } self.handleInteractiveGestureIfNeeded() } } extension Transition : UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { Movin.dp("Transition - animationController forPresented") self.animatedTransitioning = AnimatedTransitioning(self, .present) return self.animatedTransitioning } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { Movin.dp("Transition - animationController forDismissed") self.animatedTransitioning = AnimatedTransitioning(self, .dismiss) return self.animatedTransitioning } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { Movin.dp("Transition - interactionControllerForPresentation") return self.configureInteractiveTransitioningIfNeeded() } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { Movin.dp("Transition - interactionControllerForDismissal") return self.configureInteractiveTransitioningIfNeeded() } } extension Transition: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { Movin.dp("Transition - navigationController animationControllerFor") switch operation { case .push: self.animatedTransitioning = AnimatedTransitioning(self, .push) case .pop: self.animatedTransitioning = AnimatedTransitioning(self, .pop) case .none: self.animatedTransitioning = nil default: self.animatedTransitioning = nil } return self.animatedTransitioning } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { Movin.dp("Transition - navigationController interactionControllerFor") return self.configureInteractiveTransitioningIfNeeded() } }
39.779167
254
0.664502
201d51e50f065763984378f5edcf31d4110c3213
5,978
// // SetPasswordVC.swift // visafe // // Created by Cuong Nguyen on 6/25/21. // import UIKit class SetPasswordVC: BaseViewController { @IBOutlet weak var passwordTextfield: BaseTextField! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var passwordInfoLabel: UILabel! @IBOutlet weak var rePasswordTextfield: BaseTextField! @IBOutlet weak var rePasswordInfoLabel: UILabel! @IBOutlet weak var doneButton: UIButton! var model: PasswordModel override func viewDidLoad() { super.viewDidLoad() let mutableAttributedString = NSMutableAttributedString.init(string: "Hãy nhập mật khẩu mới cho tài khoản \n\n") let attribute2 = NSAttributedString(string: model.phone_number ?? model.email ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black]) mutableAttributedString.append(attribute2) descriptionLabel.attributedText = mutableAttributedString } init(model: PasswordModel) { self.model = model super.init(nibName: SetPasswordVC.className, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func backAction(_ sender: Any) { navigationController?.popViewController() } @IBAction func acceptAction(_ sender: Any) { if validateInfo() { let param = ResetPassParam() param.username = model.email ?? model.phone_number param.password = passwordTextfield.text param.otp = model.otp param.repeat_password = rePasswordTextfield.text showLoading() AuthenWorker.resetPassword(param: param) { [weak self] (result, error, responseCode) in guard let weakSelf = self else { return } weakSelf.hideLoading() weakSelf.handleResponse(result: result, error: error) } } } func validateInfo() -> Bool { var success = true let password = passwordTextfield.text ?? "" if password.isEmpty { success = false passwordInfoLabel.text = "Mật khẩu không được để trống" } else { passwordInfoLabel.text = nil } let repassword = rePasswordTextfield.text ?? "" if repassword.isEmpty { success = false passwordInfoLabel.text = "Mật khẩu không được để trống" } else { passwordInfoLabel.text = nil } if !password.isEmpty && !repassword.isEmpty && password != repassword { passwordInfoLabel.text = "Mật khẩu không trùng nhau" passwordInfoLabel.text = "Mật khẩu không trùng nhau" } return success } func handleResponse(result: ResetPasswordResult?, error: Error?) { if result == nil && error == nil { authen() } else if let res = result { showError(title: "Đặt mật khẩu lỗi", content: res.status_code?.getDescription()) } } func authen() { let loginParam = LoginParam() loginParam.username = model.email ?? model.phone_number loginParam.password = passwordTextfield.text AuthenWorker.login(param: loginParam) { [weak self] (result, error, responseCode) in guard let weakSelf = self else { return } weakSelf.hideLoading() weakSelf.handleLogin(result: result, error: error) } } func handleLogin(result: LoginResult?, error: Error?) { if let res = result { if res.token != nil { // login thanh cong CacheManager.shared.setPassword(value: passwordTextfield.text!) CacheManager.shared.setLoginResult(value: res) actionAfterLogin() } else { let type = res.status_code ?? .error showError(title: "Đăng nhập không thành công", content: type.getDescription()) } } else { let type = LoginStatusEnum.error showError(title: "Đăng nhập không thành công", content: type.getDescription()) } } func actionAfterLogin() { showLoading() WorkspaceWorker.getList { [weak self] (list, error, responseCode) in guard let weakSelf = self else { return } weakSelf.hideLoading() CacheManager.shared.setIsLogined(value: true) CacheManager.shared.setWorkspacesResult(value: list) weakSelf.setCurrentWorkspace(list: list ?? []) AppDelegate.appDelegate()?.setRootVCToTabVC() } } func setCurrentWorkspace(list: [WorkspaceModel]) { if let workspace = list.first(where: { (m) -> Bool in return m.id == CacheManager.shared.getCurrentUser()?.defaultWorkspace }) { CacheManager.shared.setCurrentWorkspace(value: workspace) } else { CacheManager.shared.setCurrentWorkspace(value: list.first) } } } extension SetPasswordVC: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { guard let field = textField as? BaseTextField else { return } if field.type != .error { field.setState(type: .active) } } func textFieldDidEndEditing(_ textField: UITextField) { guard let field = textField as? BaseTextField else { return } if field.type != .error { field.setState(type: .normal) } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let maxLength = 50 let currentString: NSString = (textField.text ?? "") as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString return newString.length <= maxLength } }
36.45122
161
0.614085
09f0aadf6236ed8aa5fdb96b2296dfedfc00b526
1,073
import Foundation import GRPC public struct CallResult: CustomStringConvertible { public let success: Bool public let code: GRPCStatus.Code public let message: String? public static func error(code: GRPCStatus.Code = .unknown, message: String? = nil) -> CallResult { return CallResult( success: false, code: code, message: message) } public static func success() -> CallResult { return CallResult( success: true, code: .ok, message: "OK") } public init(success: Bool, code: GRPCStatus.Code, message: String?) { self.success = success self.code = code self.message = message } public var description: String { var result = "\(success ? "successful" : "unsuccessful"), code \(code)" if let message = self.message { result += ": " + message } return result } public var isFailed: Bool { return (!self.success || self.code != .ok) } }
26.170732
102
0.56384
62719f1034c3dd5f74a8569c5c71ab67da8fbfd6
3,332
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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. **/ #if os(iOS) || os(tvOS) || os(watchOS) import Foundation import UIKit import IBMSwiftSDKCore // This extension adds convenience methods for using `UIImage`. The comments and interface were copied from // `VisualRecognition.swift`, then modified to use `UIImage` instead of `URL`. Some parameters were also // removed or modified because they are not necessary in this context (e.g. `imagesFileContentType`). extension VisualRecognition { /** Analyze images. Analyze images by URL, by file, or both against your own collection. Make sure that **training_status.objects.ready** is `true` for the feature before you use a collection to analyze images. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. - parameter images: an array of UIImages to be classified - parameter collectionIDs: The IDs of the collections to analyze. Separate multiple values with commas. - parameter features: The features to analyze. Separate multiple values with commas. - parameter threshold: The minimum score a feature must have to be returned. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func analyze( images: [UIImage], collectionIDs: [String], features: [String], threshold: Double? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse<AnalyzeResponse>?, WatsonError?) -> Void) { var imageFiles = [FileWithMetadata]() // convert all UIImages to Data, and then to FileWithMetadata for image in images { guard let imageData = getImageData(image: image) else { let error = WatsonError.serialization(values: "image to data") completionHandler(nil, error) return } let imageFile = FileWithMetadata( data: imageData, filename: "image.png", contentType: "image/png" ) imageFiles.append(imageFile) } self.analyze( collectionIDs: collectionIDs, features: features, imagesFile: imageFiles, imageURL: nil, threshold: threshold, headers: headers, completionHandler: completionHandler ) } /** Convert UIImage to Data */ private func getImageData(image: UIImage) -> Data? { return image.pngData() } } #endif
37.438202
116
0.665066
e299151a62f529ae3cd3de29eb15edede158d49d
2,074
// // DateFormatterService.swift // TheDevConf2019 // // Created by Marlon Burnett on 24/11/19. // Copyright © 2019 Marlon Burnett. All rights reserved. // import Foundation public enum DateFormattingError: Error { case invalidIsoDateString } public protocol DateFormatterServiceContract { func parse(isoDateString: String) throws -> Date func stringRepresentingTime(for date: Date) -> String } public class DateFormatterService: DateFormatterServiceContract { public static let shared = DateFormatterService() private let isoDateFormatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withFullDate] return formatter }() private let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "d 'de' MMMM 'de' YYYY" formatter.locale = Locale.init(identifier: "pt-BR") return formatter }() private init() {} public func parse(isoDateString: String) throws -> Date { guard let date = isoDateFormatter.date(from: isoDateString) else { throw DateFormattingError.invalidIsoDateString } return date } public func stringRepresentingTime(for date: Date) -> String { let dateNow = Date() let differenceInDays = Calendar.current.dateComponents([.day], from: date, to: dateNow).day ?? 0 guard differenceInDays < 1 else { return dateFormatter.string(from: date) } let differenceInHours = Calendar.current.dateComponents([.hour], from: date, to: dateNow).hour ?? 0 guard differenceInHours < 1 else { return "há \(differenceInHours) hora\(differenceInHours > 1 ? "s" : "")" } let differenceInMinutes = max(Calendar.current.dateComponents([.minute], from: date, to: dateNow).minute ?? 1, 1) return "há \(differenceInMinutes) minuto\(differenceInMinutes > 1 ? "s" : "")" } }
30.057971
121
0.640309
64a1c2ea049c598753939410153d60a1c5c18ea3
34,956
// // LoopMathTests.swift // LoopKit // // Created by Nathan Racklyeft on 3/2/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import XCTest import HealthKit @testable import LoopKit typealias RecentGlucoseValue = PredictedGlucoseValue class LoopMathTests: XCTestCase { func loadGlucoseEffectFixture(_ resourceName: String, formatter: ISO8601DateFormatter) -> [GlucoseEffect] { let fixture: [JSONDictionary] = loadFixture(resourceName) return fixture.map { return GlucoseEffect(startDate: formatter.date(from: $0["date"] as! String)!, quantity: HKQuantity(unit: HKUnit(from: $0["unit"] as! String), doubleValue:$0["amount"] as! Double)) } } func loadGlucoseEffectFixture(_ resourceName: String, formatter: DateFormatter) -> [GlucoseEffect] { let fixture: [JSONDictionary] = loadFixture(resourceName) return fixture.map { return GlucoseEffect(startDate: formatter.date(from: $0["date"] as! String)!, quantity: HKQuantity(unit: HKUnit(from: $0["unit"] as! String), doubleValue: $0["value"] as! Double)) } } private func printFixture(_ glucoseEffect: [GlucoseEffect]) { let unit = HKUnit.milligramsPerDeciliter print("\n\n") print(String(data: try! JSONSerialization.data( withJSONObject: glucoseEffect.map({ (value) -> [String: Any] in return [ "date": String(describing: value.startDate), "value": value.quantity.doubleValue(for: unit), "unit": unit.unitString ] }), options: .prettyPrinted), encoding: .utf8)!) print("\n\n") } func loadSampleValueFixture(_ resourceName: String) -> [(startDate: Date, quantity: HKQuantity)] { let fixture: [JSONDictionary] = loadFixture(resourceName) let dateFormatter = ISO8601DateFormatter() return fixture.map { (dateFormatter.date(from: $0["startDate"] as! String)!, HKQuantity(unit: HKUnit(from: $0["unit"] as! String), doubleValue: $0["value"] as! Double)) } } func loadGlucoseHistoryFixture(_ resourceName: String) -> RecentGlucoseValue { let fixture: [JSONDictionary] = loadFixture(resourceName) let dateFormatter = ISO8601DateFormatter.localTimeDate() return fixture.map { return RecentGlucoseValue(startDate: dateFormatter.date(from: $0["display_time"] as! String)!, quantity: HKQuantity(unit: HKUnit.milligramsPerDeciliter, doubleValue:$0["glucose"] as! Double)) }.first! } func loadGlucoseValueFixture(_ resourceName: String) -> [PredictedGlucoseValue] { let fixture: [JSONDictionary] = loadFixture(resourceName) let dateFormatter = ISO8601DateFormatter.localTimeDate() return fixture.map { return PredictedGlucoseValue(startDate: dateFormatter.date(from: $0["date"] as! String)!, quantity: HKQuantity(unit: HKUnit(from: $0["unit"] as! String), doubleValue:$0["amount"] as! Double)) } } lazy var carbEffect: [GlucoseEffect] = { return self.loadGlucoseEffectFixture("glucose_from_effects_carb_effect_input", formatter: ISO8601DateFormatter.localTimeDate()) }() lazy var insulinEffect: [GlucoseEffect] = { return self.loadGlucoseEffectFixture("glucose_from_effects_insulin_effect_input", formatter: ISO8601DateFormatter.localTimeDate()) }() func testPredictGlucoseNoMomentum() { let glucose = loadGlucoseHistoryFixture("glucose_from_effects_glucose_input") let expected = loadGlucoseValueFixture("glucose_from_effects_no_momentum_output") let calculated = LoopMath.predictGlucose(startingAt: glucose, effects: carbEffect, insulinEffect) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testPredictGlucoseFlatMomentum() { let glucose = loadGlucoseHistoryFixture("glucose_from_effects_momentum_flat_glucose_input") let momentum = loadGlucoseEffectFixture("glucose_from_effects_momentum_flat_input", formatter: ISO8601DateFormatter.localTimeDate()) let expected = loadGlucoseValueFixture("glucose_from_effects_momentum_flat_output") let calculated = LoopMath.predictGlucose(startingAt: glucose, momentum: momentum, effects: carbEffect, insulinEffect) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testPredictGlucoseUpMomentum() { let glucose = loadGlucoseHistoryFixture("glucose_from_effects_glucose_input") let momentum = loadGlucoseEffectFixture("glucose_from_effects_momentum_up_input", formatter: ISO8601DateFormatter.localTimeDate()) let expected = loadGlucoseValueFixture("glucose_from_effects_momentum_up_output") let calculated = LoopMath.predictGlucose(startingAt: glucose, momentum: momentum, effects: carbEffect, insulinEffect) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testPredictGlucoseDownMomentum() { let glucose = loadGlucoseHistoryFixture("glucose_from_effects_glucose_input") let momentum = loadGlucoseEffectFixture("glucose_from_effects_momentum_down_input", formatter: ISO8601DateFormatter.localTimeDate()) let expected = loadGlucoseValueFixture("glucose_from_effects_momentum_down_output") let calculated = LoopMath.predictGlucose(startingAt: glucose, momentum: momentum, effects: carbEffect, insulinEffect) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testPredictGlucoseBlendMomentum() { let glucose = loadGlucoseHistoryFixture("glucose_from_effects_momentum_blend_glucose_input") let momentum = loadGlucoseEffectFixture("glucose_from_effects_momentum_blend_momentum_input", formatter: ISO8601DateFormatter.localTimeDate()) let insulinEffect = loadGlucoseEffectFixture("glucose_from_effects_momentum_blend_insulin_effect_input", formatter: ISO8601DateFormatter.localTimeDate()) let expected = loadGlucoseValueFixture("glucose_from_effects_momentum_blend_output") let calculated = LoopMath.predictGlucose(startingAt: glucose, momentum: momentum, effects: insulinEffect) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testPredictGlucoseStartingEffectsNonZero() { let glucose = loadSampleValueFixture("glucose_from_effects_non_zero_glucose_input").first! let insulinEffect = loadSampleValueFixture("glucose_from_effects_non_zero_insulin_input").map { GlucoseEffect(startDate: $0.startDate, quantity: $0.quantity) } let carbEffect = loadSampleValueFixture("glucose_from_effects_non_zero_carb_input").map { GlucoseEffect(startDate: $0.startDate, quantity: $0.quantity) } let expected = loadSampleValueFixture("glucose_from_effects_non_zero_output").map { GlucoseEffect(startDate: $0.startDate, quantity: $0.quantity) } let calculated = LoopMath.predictGlucose(startingAt: RecentGlucoseValue(startDate: glucose.startDate, quantity: glucose.quantity), effects: insulinEffect, carbEffect ) XCTAssertEqual(expected.count, calculated.count) for (expected, calculated) in zip(expected, calculated) { XCTAssertEqual(expected.startDate, calculated.startDate) XCTAssertEqual(expected.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), calculated.quantity.doubleValue(for: HKUnit.milligramsPerDeciliter), accuracy: Double(Float.ulpOfOne)) } } func testDecayEffect() { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let glucoseDate = calendar.date(from: DateComponents(year: 2016, month: 2, day: 1, hour: 10, minute: 13, second: 20))! let type = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)! let unit = HKUnit.milligramsPerDeciliter let glucose = HKQuantitySample(type: type, quantity: HKQuantity(unit: unit, doubleValue: 100), start: glucoseDate, end: glucoseDate) var startingEffect = HKQuantity(unit: unit.unitDivided(by: HKUnit.minute()), doubleValue: 2) var effects = glucose.decayEffect(atRate: startingEffect, for: .minutes(30)) XCTAssertEqual([100, 110, 118, 124, 128, 130, 130], effects.map { $0.quantity.doubleValue(for: unit) }) let startDate = effects.first!.startDate XCTAssertEqual([0, 5, 10, 15, 20, 25, 30], effects.map { $0.startDate.timeIntervalSince(startDate).minutes }) startingEffect = HKQuantity(unit: unit.unitDivided(by: HKUnit.minute()), doubleValue: -0.5) effects = glucose.decayEffect(atRate: startingEffect, for: .minutes(30)) XCTAssertEqual([100, 97.5, 95.5, 94, 93, 92.5, 92.5], effects.map { $0.quantity.doubleValue(for: unit) }) } func testDecayEffectWithEvenGlucose() { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let glucoseDate = calendar.date(from: DateComponents(year: 2016, month: 2, day: 1, hour: 10, minute: 15, second: 0))! let type = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)! let unit = HKUnit.milligramsPerDeciliter let glucose = HKQuantitySample(type: type, quantity: HKQuantity(unit: unit, doubleValue: 100), start: glucoseDate, end: glucoseDate) var startingEffect = HKQuantity(unit: unit.unitDivided(by: HKUnit.minute()), doubleValue: 2) var effects = glucose.decayEffect(atRate: startingEffect, for: .minutes(30)) XCTAssertEqual([100, 110, 118, 124, 128, 130], effects.map { $0.quantity.doubleValue(for: unit) }) let startDate = effects.first!.startDate XCTAssertEqual([0, 5, 10, 15, 20, 25], effects.map { $0.startDate.timeIntervalSince(startDate).minutes }) startingEffect = HKQuantity(unit: unit.unitDivided(by: HKUnit.minute()), doubleValue: -0.5) effects = glucose.decayEffect(atRate: startingEffect, for: .minutes(30)) XCTAssertEqual([100, 97.5, 95.5, 94, 93, 92.5], effects.map { $0.quantity.doubleValue(for: unit) }) } func testSubtractingCarbEffectFromICEWithGaps() { let perMinute = HKUnit.milligramsPerDeciliter.unitDivided(by: .minute()) let mgdl = HKUnit.milligramsPerDeciliter let formatter = DateFormatter.descriptionFormatter let f = { (input) in return formatter.date(from: input)! } let insulinCounteractionEffects = [ GlucoseEffectVelocity(startDate: f("2018-08-16 01:03:43 +0000"), endDate: f("2018-08-16 01:08:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.0063630385383878375)), GlucoseEffectVelocity(startDate: f("2018-08-16 01:08:43 +0000"), endDate: f("2018-08-16 01:13:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.3798225216554212)), GlucoseEffectVelocity(startDate: f("2018-08-16 01:13:44 +0000"), endDate: f("2018-08-16 01:18:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.5726970790754702)), GlucoseEffectVelocity(startDate: f("2018-08-16 01:18:44 +0000"), endDate: f("2018-08-16 01:23:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.7936837738660198)), GlucoseEffectVelocity(startDate: f("2018-08-16 01:23:44 +0000"), endDate: f("2018-08-16 01:28:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 1.2143200509835315)), GlucoseEffectVelocity(startDate: f("2018-08-16 01:28:43 +0000"), endDate: f("2018-08-16 02:03:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 1.214239367352738)), GlucoseEffectVelocity(startDate: f("2018-08-16 02:03:43 +0000"), endDate: f("2018-08-16 03:13:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.64964443000756)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:18:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.40933503856266396)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:18:44 +0000"), endDate: f("2018-08-16 03:23:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.5994115966821696)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:23:43 +0000"), endDate: f("2018-08-16 03:28:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.640336708627245)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:28:44 +0000"), endDate: f("2018-08-16 03:33:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 1.5109774027636143)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:33:43 +0000"), endDate: f("2018-08-16 03:38:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -1.6358198764701966)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:38:43 +0000"), endDate: f("2018-08-16 03:43:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.4187533857556986)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:43:44 +0000"), endDate: f("2018-08-16 03:48:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -1.136005257968153)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:48:43 +0000"), endDate: f("2018-08-16 03:53:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.29635521996668046)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:53:44 +0000"), endDate: f("2018-08-16 03:58:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -1.070285990192832)), GlucoseEffectVelocity(startDate: f("2018-08-16 03:58:43 +0000"), endDate: f("2018-08-16 04:03:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.25025410282677996)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:03:43 +0000"), endDate: f("2018-08-16 04:08:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.5598990284715561)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:08:43 +0000"), endDate: f("2018-08-16 04:13:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 1.9616378142801167)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:13:44 +0000"), endDate: f("2018-08-16 04:18:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 1.7593854114682483)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:18:43 +0000"), endDate: f("2018-08-16 04:23:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.5467358931981837)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:23:44 +0000"), endDate: f("2018-08-16 04:28:44 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.9335047268082058)), GlucoseEffectVelocity(startDate: f("2018-08-16 04:28:44 +0000"), endDate: f("2018-08-16 04:33:43 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.2823274349191665)), ] let carbEffects = [ GlucoseEffect(startDate: f("2018-08-16 01:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 69.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 01:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 69.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 01:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 72.18741125500856)), GlucoseEffect(startDate: f("2018-08-16 01:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 82.00120184863087)), GlucoseEffect(startDate: f("2018-08-16 01:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 90.79285286260895)), GlucoseEffect(startDate: f("2018-08-16 01:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 93.5316456300059)), GlucoseEffect(startDate: f("2018-08-16 01:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 98.19664696604428)), GlucoseEffect(startDate: f("2018-08-16 01:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 98.5800323225078)), GlucoseEffect(startDate: f("2018-08-16 01:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 100.09237800152016)), GlucoseEffect(startDate: f("2018-08-16 01:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 101.60472368053252)), GlucoseEffect(startDate: f("2018-08-16 01:50:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 103.11706935954487)), GlucoseEffect(startDate: f("2018-08-16 01:55:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 104.6294150385572)), GlucoseEffect(startDate: f("2018-08-16 02:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 129.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 02:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 129.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 02:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 132.18741125500856)), GlucoseEffect(startDate: f("2018-08-16 02:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 142.00120184863087)), GlucoseEffect(startDate: f("2018-08-16 02:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 150.79285286260895)), GlucoseEffect(startDate: f("2018-08-16 02:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 153.5316456300059)), GlucoseEffect(startDate: f("2018-08-16 02:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 158.19664696604428)), GlucoseEffect(startDate: f("2018-08-16 02:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 158.5800323225078)), GlucoseEffect(startDate: f("2018-08-16 02:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 160.09237800152016)), GlucoseEffect(startDate: f("2018-08-16 02:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 161.60472368053252)), GlucoseEffect(startDate: f("2018-08-16 02:50:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 163.11706935954487)), GlucoseEffect(startDate: f("2018-08-16 02:55:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 164.6294150385572)), GlucoseEffect(startDate: f("2018-08-16 03:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 166.14176071756955)), GlucoseEffect(startDate: f("2018-08-16 03:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 167.65410639658188)), GlucoseEffect(startDate: f("2018-08-16 03:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 169.16645207559424)), GlucoseEffect(startDate: f("2018-08-16 03:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 170.6787977546066)), GlucoseEffect(startDate: f("2018-08-16 03:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 172.19114343361895)), GlucoseEffect(startDate: f("2018-08-16 03:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 173.70348911263127)), GlucoseEffect(startDate: f("2018-08-16 03:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 175.21583479164363)), GlucoseEffect(startDate: f("2018-08-16 03:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 176.72818047065596)), GlucoseEffect(startDate: f("2018-08-16 03:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 178.2405261496683)), GlucoseEffect(startDate: f("2018-08-16 03:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 179.75287182868067)), GlucoseEffect(startDate: f("2018-08-16 03:50:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 181.26521750769302)), GlucoseEffect(startDate: f("2018-08-16 03:55:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 182.77756318670535)), GlucoseEffect(startDate: f("2018-08-16 04:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 189.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 04:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 189.38642455065255)), GlucoseEffect(startDate: f("2018-08-16 04:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 192.18741125500856)), GlucoseEffect(startDate: f("2018-08-16 04:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 202.00120184863087)), GlucoseEffect(startDate: f("2018-08-16 04:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 210.79285286260895)), GlucoseEffect(startDate: f("2018-08-16 04:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 213.5316456300059)), GlucoseEffect(startDate: f("2018-08-16 04:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 218.19664696604428)), GlucoseEffect(startDate: f("2018-08-16 04:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 218.5800323225078)), GlucoseEffect(startDate: f("2018-08-16 04:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 220.09237800152016)), GlucoseEffect(startDate: f("2018-08-16 04:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 221.60472368053252)), GlucoseEffect(startDate: f("2018-08-16 04:50:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 223.11706935954487)), GlucoseEffect(startDate: f("2018-08-16 04:55:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 224.6294150385572)), GlucoseEffect(startDate: f("2018-08-16 05:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 226.14176071756955)), GlucoseEffect(startDate: f("2018-08-16 05:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 227.65410639658188)), GlucoseEffect(startDate: f("2018-08-16 05:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 229.16645207559424)), GlucoseEffect(startDate: f("2018-08-16 05:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 230.6787977546066)), GlucoseEffect(startDate: f("2018-08-16 05:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 232.19114343361895)), GlucoseEffect(startDate: f("2018-08-16 05:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 233.70348911263127)), GlucoseEffect(startDate: f("2018-08-16 05:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 235.21583479164363)), GlucoseEffect(startDate: f("2018-08-16 05:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 236.72818047065596)), GlucoseEffect(startDate: f("2018-08-16 05:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 238.2405261496683)), GlucoseEffect(startDate: f("2018-08-16 05:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 239.75287182868067)), GlucoseEffect(startDate: f("2018-08-16 05:50:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 241.26521750769302)), GlucoseEffect(startDate: f("2018-08-16 05:55:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 242.77756318670535)), GlucoseEffect(startDate: f("2018-08-16 06:00:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 244.28990886571768)), GlucoseEffect(startDate: f("2018-08-16 06:05:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 245.80225454473003)), GlucoseEffect(startDate: f("2018-08-16 06:10:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 247.3146002237424)), GlucoseEffect(startDate: f("2018-08-16 06:15:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 248.82694590275474)), GlucoseEffect(startDate: f("2018-08-16 06:20:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 250.33929158176707)), GlucoseEffect(startDate: f("2018-08-16 06:25:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 251.85163726077943)), GlucoseEffect(startDate: f("2018-08-16 06:30:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 253.16666666666669)), GlucoseEffect(startDate: f("2018-08-16 06:35:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 253.16666666666669)), GlucoseEffect(startDate: f("2018-08-16 06:40:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 253.16666666666669)), ] let calculated = insulinCounteractionEffects.subtracting(carbEffects, withUniformInterval: .minutes(5)) let expected = loadGlucoseEffectFixture("ice_minus_carb_effect_with_gaps_output", formatter: DateFormatter.descriptionFormatter) XCTAssertEqual(expected, calculated) } func testSubtractingFlatCarbEffectFromICE() { let perMinute = HKUnit.milligramsPerDeciliter.unitDivided(by: .minute()) let mgdl = HKUnit.milligramsPerDeciliter let formatter = DateFormatter.descriptionFormatter let f = { (input) in return formatter.date(from: input)! } let insulinCounteractionEffects = [ GlucoseEffectVelocity(startDate: f("2018-08-26 00:23:27 +0000"), endDate: f("2018-08-26 00:28:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.3711911901542791)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:28:28 +0000"), endDate: f("2018-08-26 00:33:27 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.4382943196158106)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:33:27 +0000"), endDate: f("2018-08-26 00:38:27 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.24797050925219474)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:38:27 +0000"), endDate: f("2018-08-26 00:43:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: -0.05800368381887202)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:43:28 +0000"), endDate: f("2018-08-26 00:48:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.7303422936657988)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:48:28 +0000"), endDate: f("2018-08-26 00:53:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.7166291304729353)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:53:28 +0000"), endDate: f("2018-08-26 00:58:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.2962279320324577)), GlucoseEffectVelocity(startDate: f("2018-08-26 00:58:28 +0000"), endDate: f("2018-08-26 01:03:27 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.2730196016663657)), GlucoseEffectVelocity(startDate: f("2018-08-26 01:03:27 +0000"), endDate: f("2018-08-26 01:08:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.44605609358758713)), GlucoseEffectVelocity(startDate: f("2018-08-26 01:08:28 +0000"), endDate: f("2018-08-26 01:13:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.42131971635266463)), GlucoseEffectVelocity(startDate: f("2018-08-26 01:13:28 +0000"), endDate: f("2018-08-26 01:18:27 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.9948293689475411)), GlucoseEffectVelocity(startDate: f("2018-08-26 01:18:27 +0000"), endDate: f("2018-08-26 01:23:28 +0000"), quantity: HKQuantity(unit: perMinute, doubleValue: 0.9652238210644638)), ] let carbEffects = [ GlucoseEffect(startDate: f("2018-08-26 00:45:00 +0000"), quantity: HKQuantity(unit: mgdl, doubleValue: 385.8235294117647)) ] let calculated = insulinCounteractionEffects.subtracting(carbEffects, withUniformInterval: .minutes(5)) let expected = loadGlucoseEffectFixture("ice_minus_flat_carb_effect_output", formatter: DateFormatter.descriptionFormatter) XCTAssertEqual(expected, calculated) } func testCombinedSumsWithGaps() { let input = loadGlucoseEffectFixture("ice_minus_carb_effect_with_gaps_output", formatter: DateFormatter.descriptionFormatter) let unit = HKUnit.milligramsPerDeciliter let formatter = DateFormatter.descriptionFormatter let f = { (input) in return formatter.date(from: input)! } let expected = [ GlucoseChange(startDate: f("2018-08-16 01:13:44 +0000"), endDate: f("2018-08-16 01:13:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -7.914677985345208)), GlucoseChange(startDate: f("2018-08-16 01:13:44 +0000"), endDate: f("2018-08-16 01:18:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -13.84284360394594)), GlucoseChange(startDate: f("2018-08-16 01:13:44 +0000"), endDate: f("2018-08-16 01:23:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -12.613217502012784)), GlucoseChange(startDate: f("2018-08-16 01:13:44 +0000"), endDate: f("2018-08-16 01:28:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -11.206618583133514)), GlucoseChange(startDate: f("2018-08-16 02:03:43 +0000"), endDate: f("2018-08-16 02:03:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 6.071196836763691)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:13:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 1.735876471025445)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:18:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 2.2702059848264096)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:23:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 3.754918289224931)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:28:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 5.444256153348801)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:33:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 11.486797488154545)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:38:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 1.7953524267912058)), GlucoseChange(startDate: f("2018-08-16 03:13:44 +0000"), endDate: f("2018-08-16 03:43:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 2.376773676557343)), GlucoseChange(startDate: f("2018-08-16 03:18:44 +0000"), endDate: f("2018-08-16 03:48:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -6.551474763321222)), GlucoseChange(startDate: f("2018-08-16 03:28:44 +0000"), endDate: f("2018-08-16 03:53:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -11.56463836036644)), GlucoseChange(startDate: f("2018-08-16 03:28:44 +0000"), endDate: f("2018-08-16 03:58:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -23.524929675277797)), GlucoseChange(startDate: f("2018-08-16 03:33:43 +0000"), endDate: f("2018-08-16 04:03:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -26.46553805353557)), GlucoseChange(startDate: f("2018-08-16 03:38:43 +0000"), endDate: f("2018-08-16 04:08:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -32.50957095033954)), GlucoseChange(startDate: f("2018-08-16 03:43:44 +0000"), endDate: f("2018-08-16 04:13:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -22.823727411197925)), GlucoseChange(startDate: f("2018-08-16 03:48:43 +0000"), endDate: f("2018-08-16 04:18:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -23.399872617600906)), GlucoseChange(startDate: f("2018-08-16 03:53:44 +0000"), endDate: f("2018-08-16 04:23:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -16.21261395015381)), GlucoseChange(startDate: f("2018-08-16 04:03:43 +0000"), endDate: f("2018-08-16 04:28:44 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -1.2556785583940788)), GlucoseChange(startDate: f("2018-08-16 04:03:43 +0000"), endDate: f("2018-08-16 04:33:43 +0000"), quantity: HKQuantity(unit: unit, doubleValue: -3.0507010894534323)) ] let calculated = input.combinedSums(of: .minutes(30)) XCTAssertEqual(expected, calculated) } func testNetEffect() { let formatter = DateFormatter.descriptionFormatter let f = { (input) in return formatter.date(from: input)! } let unit = HKUnit.milligramsPerDeciliter let input = [ GlucoseEffect(startDate: f("2018-08-16 01:00:00 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 25)), GlucoseEffect(startDate: f("2018-08-16 01:05:00 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 26)), GlucoseEffect(startDate: f("2018-08-16 01:10:00 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 27)) ] let calculated = input.netEffect() let expected = GlucoseChange( startDate: f("2018-08-16 01:00:00 +0000"), endDate: f("2018-08-16 01:10:00 +0000"), quantity: HKQuantity(unit: unit, doubleValue: 2)) XCTAssertEqual(expected, calculated) } }
78.907449
203
0.697448
185b1228f91217bf85349e10736020c068d24f9b
487
// // BudgetMonthTotalsView.swift // YDNYNAB // // Created by Justin Hill on 9/6/18. // Copyright © 2018 Justin Hill. All rights reserved. // import Cocoa class BudgetMonthTotalsView: NSView { required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.wantsLayer = true self.layer?.backgroundColor = NSColor.red.cgColor } }
23.190476
98
0.669405
d732dbd7d59e7efef8265b5f0b2cced693849dbf
2,559
import UIKit import CoreML import Vision /** View controller for the "Camera" screen. This can evaluate both the neural network model and the k-NN model, because they use the same input and output names. On the Simulator this uses the photo library instead of the camera. */ class CameraViewController: UIViewController { @IBOutlet var cameraButton: UIBarButtonItem! @IBOutlet var imageView: UIImageView! @IBOutlet var textView: UITextView! var model: MLModel! var predictor: Predictor! override func viewDidLoad() { super.viewDidLoad() textView.text = "Use the camera to take a photo." predictor = Predictor(model: model) } @IBAction func takePicture() { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = UIImagePickerController.isSourceTypeAvailable(.camera) ? .camera : .photoLibrary picker.allowsEditing = true present(picker, animated: true) } func predict(image: UIImage) { let constraint = imageConstraint(model: model) let imageOptions: [MLFeatureValue.ImageOption: Any] = [ .cropAndScale: VNImageCropAndScaleOption.scaleFill.rawValue ] // In the "Evaluate" screen we load the image from the dataset but here // we use a UIImage / CGImage object. if let cgImage = image.cgImage, let featureValue = try? MLFeatureValue(cgImage: cgImage, orientation: .up, constraint: constraint, options: imageOptions), let prediction = predictor.predict(image: featureValue) { textView.text = makeDisplayString(prediction) } } private func makeDisplayString(_ prediction: Prediction) -> String { var s = "Prediction: \(prediction.label)\n" s += String(format: "Probability: %.2f%%\n\n", prediction.confidence * 100) s += "Results for all classes:\n" s += prediction.sortedProbabilities .map { String(format: "%@ %f", labels.userLabel(for: $0.0), $0.1) } .joined(separator: "\n") return s } } extension CameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) let image = info[UIImagePickerController.InfoKey.editedImage] as! UIImage imageView.image = image predict(image: image) } }
34.12
142
0.674873
bf1627ed1efb19048f5279b9b8475198b583422e
3,005
// // ExtensionDelegate.swift // handWashTimer WatchKit Extension // // Created by Salvatore D'Agostino on 2020-04-11. // Copyright © 2020 Salvatore D'Agostino. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. backgroundTask.setTaskCompletedWithSnapshot(false) case let snapshotTask as WKSnapshotRefreshBackgroundTask: // Snapshot tasks have a unique completion call, make sure to set your expiration date snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // Be sure to complete the connectivity task once you’re done. connectivityTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // Be sure to complete the URL session task once you’re done. urlSessionTask.setTaskCompletedWithSnapshot(false) case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask: // Be sure to complete the relevant-shortcut task once you're done. relevantShortcutTask.setTaskCompletedWithSnapshot(false) case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask: // Be sure to complete the intent-did-run task once you're done. intentDidRunTask.setTaskCompletedWithSnapshot(false) default: // make sure to complete unhandled task types task.setTaskCompletedWithSnapshot(false) } } } }
52.719298
285
0.700499
ff2524611bbe5693a4a879de200672fc384f5550
1,127
// // DataManager.swift // Resolve // // Created by David Mitchell // Copyright © 2021 The App Studio LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import CoreData import CoreResolve public final class DataManager: CoreDataManager, DataService { #if os(watchOS) public func getTapCount() throws -> Int { return try performAndReturn { context in let request: NSFetchRequest<SharedEvent> = SharedEvent.fetchRequest() request.predicate = SharedEvent.predicateForNotSyncedAs([.synchronizingRelationships, .markedForDeletion]) return try context.count(for: request) } } #endif }
29.657895
109
0.740905
6790965dc36d09a19bd0f86b0380f394877f486b
1,497
// // Date+.swift // QuantiBaseExampleTests // // Created by Martin Troup on 05/08/2019. // Copyright © 2019 David Nemec. All rights reserved. // import XCTest class Date_: XCTestCase { func testToStringWithoutParameter() { let now = Date() let fullDateTimeRegex = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{3}$" let fullDateTimePredicate = NSPredicate(format: "SELF MATCHES %@", fullDateTimeRegex) XCTAssertTrue(fullDateTimePredicate.evaluate(with: now.asString())) } func testtoTimeStringWithParameter() { let now = Date() let fullDateTimeRegex = "^[0-9]{2}.[0-9]{2}.[0-9]{2}$" let fullDateTimePredicate = NSPredicate(format: "SELF MATCHES %@", fullDateTimeRegex) XCTAssertTrue(fullDateTimePredicate.evaluate(with: now.asString("hh.mm.ss"))) } func testOfDateTimeStringVariable() { let now = Date() let fullDateTimeRegex = "^[0-9]{2}:[0-9]{2}:[0-9]{2}$" let fullDateTimePredicate = NSPredicate(format: "SELF MATCHES %@", fullDateTimeRegex) XCTAssertTrue(fullDateTimePredicate.evaluate(with: now.timeString)) } func testOfTimeStringVariable() { let now = Date() let fullDateTimeRegex = "^[0-9]{2} [A-Z][a-z]{1,}, [0-9]{2}:[0-9]{2}$" let fullDateTimePredicate = NSPredicate(format: "SELF MATCHES %@", fullDateTimeRegex) XCTAssertTrue(fullDateTimePredicate.evaluate(with: now.dateTimeString)) } }
36.512195
98
0.633935
086a77ac6a34e1334b439b9a276107ddfcd0e352
4,130
// // CCDBConnection.swift // CCModelSwift // // Created by cmw on 2021/7/13. // import Foundation import SQLite3 public class CCDBConnection { static var needUpgrade = false static var needCreate = true static var dbDocumentPath: String? { let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first if let dbDocumentPath = documentPath?.appending("/CCDB_data/") { if !FileManager.default.fileExists(atPath: dbDocumentPath, isDirectory: nil) { do { try FileManager.default.createDirectory(atPath: dbDocumentPath, withIntermediateDirectories: true, attributes: nil) } catch { return nil } } return dbDocumentPath } else { return nil } } /** (初始化CCDB) Please call this method before using the CCDB API. This method will determine whether to update the database based on the version, and when your data model changes, then the value of the version will need to be changed (请在使用CCDB的API之前调用该方法,该方法会根据version来决定是否要更新数据库,当你的数据模型发生变更时,则需要修改version的值) - parameter version: Current version of the database (当前数据库的版本号) */ public static func initializeDBWithVersion(_ version: String) { let dbFileName = "ccdb-" + version + ".db" let dbWalFile = "ccdb-" + version + ".db-wal" let dbShmFile = "ccdb-" + version + ".db-shm" guard let dbDocumentPath = self.dbDocumentPath else { return } let filePath = dbDocumentPath.appending(dbFileName) let dbWalFilePath = dbDocumentPath.appending(dbWalFile) let dbShmFilePath = dbDocumentPath.appending(dbShmFile) if !FileManager.default.fileExists(atPath: filePath) { if let files = FileManager.default.subpaths(atPath: dbDocumentPath) { for file in files { if file.contains("ccdb-") { self.needUpgrade = true self.needCreate = false do { if file.contains("db-shm") { try FileManager.default.moveItem(atPath: dbDocumentPath.appending(file), toPath: dbShmFilePath) } else if file.contains("db-wal") { try FileManager.default.moveItem(atPath: dbDocumentPath.appending(file), toPath: dbWalFilePath) } else { try FileManager.default.moveItem(atPath: dbDocumentPath.appending(file), toPath: filePath) } } catch { } } } } } print(filePath) for _ in 0...CCDBInstancePool.DB_INSTANCE_POOL_SIZE { CCDBInstancePool.shared.addDBInstance(openDatabase(filePath)) } ccdb_syncAllLocalCache() _ = CCDBUpdateManager.shared } static func openDatabase(_ filePath: String) -> OpaquePointer? { var instance: OpaquePointer? if sqlite3_open_v2(filePath.cString(using: String.Encoding.utf8), &instance, SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|SQLITE_OPEN_NOMUTEX, nil) != SQLITE_OK { sqlite3_close(instance) return nil } sqlite3_exec(instance, "PRAGMA journal_mode=WAL;".cString(using: String.Encoding.utf8), nil, nil, nil); sqlite3_exec(instance, "PRAGMA wal_autocheckpoint=100;".cString(using: String.Encoding.utf8), nil, nil, nil); return instance } static func statementWithSql(_ sql: String, instance:CCDBInstance) -> CCDBStatement { if let stmt = instance.dicStatments[sql] { return stmt } else { let stmt = CCDBStatement.init(withDBInstance: instance.instance, withSql: sql) instance.dicStatments[sql] = stmt return stmt } } }
40.097087
223
0.58523
16a53e74ac464540fc99ba844cb32e31175ddbad
1,808
// // PaperOnboardingDataSource.swift // PaperOnboardingDemo // // Created by Abdurahim Jauzee on 05/06/2017. // Copyright © 2017 Alex K. All rights reserved. // // swiftlint:disable all import UIKit /** * The PaperOnboardingDataSource protocol is adopted by an object that mediates the application’™s data model for a PaperOnboarding object. The data source information it needs to construct and modify a PaperOnboarding. */ public protocol PaperOnboardingDataSource { /** Asks the data source to return the number of items. - parameter index: An index of item in PaperOnboarding. - returns: The number of items in PaperOnboarding. */ func onboardingItemsCount() -> Int /** Asks the data source for configureation item. - parameter index: An index of item in PaperOnboarding. - returns: configuration info for item */ func onboardingItem(at index: Int) -> OnboardingItemInfo /** Asks the color for PageView item - parameter index: An index of item in PaperOnboarding. - returns: color PageView Item */ func onboardingPageItemColor(at index: Int) -> UIColor /// Asks for the radius of the PageView item /// /// - Returns: radius of the PageView Item func onboardinPageItemRadius() -> CGFloat /// Asks for the selected state radius of the PageView item /// /// - Returns: selected state radius of the PageView Item func onboardingPageItemSelectedRadius() -> CGFloat } public extension PaperOnboardingDataSource { func onboardingPageItemColor(at index: Int) -> UIColor { return .white } func onboardinPageItemRadius() -> CGFloat { return 8 } func onboardingPageItemSelectedRadius() -> CGFloat { return 22 } }
27.393939
140
0.683628
03d7af51aeae6d75140010143449cd5f47d87d03
322
// // TabBarController.swift // UnderKeyboard // // Created by Evgenii on 20/06/2016. // Copyright © 2016 Marketplacer. All rights reserved. // import UIKit class NavigationController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } }
20.125
58
0.757764
4b69829c32e4446591a56d76584e83d3fcd7d74a
4,802
// DateFieldRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit public protocol DatePickerRowProtocol: class { var minimumDate: Date? { get set } var maximumDate: Date? { get set } var minuteInterval: Int? { get set } } open class DateCell: Cell<Date>, CellType { public var datePicker: UIDatePicker public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { datePicker = UIDatePicker() super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { datePicker = UIDatePicker() super.init(coder: aDecoder) } open override func setup() { super.setup() accessoryType = .none editingAccessoryType = .none datePicker.datePickerMode = datePickerMode() datePicker.addTarget(self, action: #selector(DateCell.datePickerValueChanged(_:)), for: .valueChanged) #if swift(>=5.2) if #available(iOS 13.4, *) { datePicker.preferredDatePickerStyle = .wheels } #endif } deinit { datePicker.removeTarget(self, action: nil, for: .allEvents) } open override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow) datePicker.minimumDate = (row as? DatePickerRowProtocol)?.minimumDate datePicker.maximumDate = (row as? DatePickerRowProtocol)?.maximumDate if let minuteIntervalValue = (row as? DatePickerRowProtocol)?.minuteInterval { datePicker.minuteInterval = minuteIntervalValue } if row.isHighlighted { textLabel?.textColor = tintColor } } open override func didSelect() { super.didSelect() row.deselect() } override open var inputView: UIView? { if let v = row.value { datePicker.setDate(v, animated:row is CountDownRow) } return datePicker } @objc(pickerDateChanged:) func datePickerValueChanged(_ sender: UIDatePicker) { row.value = sender.date detailTextLabel?.text = row.displayValueFor?(row.value) } private func datePickerMode() -> UIDatePicker.Mode { switch row { case is DateRow: return .date case is TimeRow: return .time case is DateTimeRow: return .dateAndTime case is CountDownRow: return .countDownTimer default: return .date } } open override func cellCanBecomeFirstResponder() -> Bool { return canBecomeFirstResponder } override open var canBecomeFirstResponder: Bool { return !row.isDisabled } } open class _DateFieldRow: Row<DateCell>, DatePickerRowProtocol, NoValueDisplayTextConformance { /// The minimum value for this row's UIDatePicker open var minimumDate: Date? /// The maximum value for this row's UIDatePicker open var maximumDate: Date? /// The interval between options for this row's UIDatePicker open var minuteInterval: Int? /// The formatter for the date picked by the user open var dateFormatter: DateFormatter? open var noValueDisplayText: String? = nil required public init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let val = value, let formatter = self.dateFormatter else { return nil } return formatter.string(from: val) } } }
33.117241
110
0.667638
fbde871dbb12e0447e0ab446aaaf5e0e03fc6fd0
10,959
// // ImageMetalDevice.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 9.. // Copyright © 2017년 test. All rights reserved. // #if !os(OSX) import UIKit #else import AppKit #endif #if !os(watchOS) import Metal #endif #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal class ImageMetalDevice: ImageDevice { // MARK: - Property internal let device: MTLDevice internal let commandQueue: MTLCommandQueue internal var drawRect: CGRect? internal var texture: MTLTexture? internal var outputTexture: MTLTexture? // MARK: - Internal internal func makeTexture() { /// Calc size let width = Int(self.drawRect!.width) let height = Int(self.drawRect!.height) guard self.texture == nil else { return } guard let imageRef = self.cgImage else { return } defer { self.image = nil } /// Space Size let scale = self.imageScale /// Alloc Memory let memorySize = width * height * 4 let memoryPool = UnsafeMutablePointer<UInt8>.allocate(capacity: memorySize) defer { #if swift(>=4.1) memoryPool.deallocate() #else memoryPool.deallocate(capacity: memorySize) #endif } memset(memoryPool, 0, memorySize) /// Create Context let bitmapContext = CGContext( data: memoryPool, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue) ) guard let context = bitmapContext else { return } /// Draw Background if let background = self.background { context.saveGState() context.setBlendMode(.normal) context.setFillColor(background.cgColor) context.fill(self.drawRect!) context.restoreGState() } /// Draw let size = self.scale ?? self.spaceSize let tempX = self.offset.x + self.margin.left + self.padding.left let tempY = self.offset.y + self.margin.top + self.padding.top context.saveGState() context.setBlendMode(.normal) context.setAlpha(self.opacity) if let rotateRadius = self.rotate { context.translateBy( x: self.spaceSize.width * 0.5, y: self.spaceSize.height * 0.5 ) context.rotate(by: rotateRadius) let calcX = -size.width * 0.5 + tempX let calcY = -size.height * 0.5 + tempY let rect = CGRect( x: calcX * scale, y: calcY * scale, width: size.width * scale, height: size.height * scale ) self.draw(imageRef, in: rect, on: context) } else { let rect = CGRect( x: tempX * scale, y: tempY * scale, width: size.width * scale, height: size.height * scale ) self.draw(imageRef, in: rect, on: context) } context.restoreGState() /// Make texture let descriptor = MTLTextureDescriptor.texture2DDescriptor( pixelFormat: .rgba8Unorm, width: width, height: height, mipmapped: false ) #if swift(>=4.0) guard let texture = self.device.makeTexture(descriptor: descriptor) else { return } #else let texture = self.device.makeTexture(descriptor: descriptor) #endif texture.replace( region: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0, withBytes: memoryPool, bytesPerRow: width * 4 ) self.texture = texture self.outputTexture = self.device.makeTexture(descriptor: descriptor) } internal func swapBuffer() { let oldTexture = self.texture self.texture = self.outputTexture self.outputTexture = oldTexture } internal override func beginGenerate(_ isAlphaProcess: Bool) { /// Space Size let scale = self.imageScale /// Calc size let tempW = self.spaceSize.width + self.margin.horizontal + self.padding.horizontal let tempH = self.spaceSize.height + self.margin.vertical + self.padding.vertical let width = Int(tempW * scale) let height = Int(tempH * scale) let spaceRect = CGRect( x: 0, y: 0, width: width, height: height ) self.drawRect = spaceRect self.makeTexture() } internal override func endGenerate() -> CGImage? { guard let texture = self.texture else { return nil } defer { self.texture = nil self.outputTexture = nil } let scale = self.imageScale let width = Int(self.drawRect!.width) let height = Int(self.drawRect!.height) let memorySize = width * height * 4 let memoryPool = UnsafeMutablePointer<UInt8>.allocate(capacity: memorySize) defer { #if swift(>=4.1) memoryPool.deallocate() #else memoryPool.deallocate(capacity: memorySize) #endif } texture.getBytes( memoryPool, bytesPerRow: width * 4, from: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0 ) let bitmapContext = CGContext( data: memoryPool, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue) ) guard let context = bitmapContext else { return nil } /// Draw border if let border = self.border { let borderPath: FIBezierPath let borderSize = self.scale ?? self.spaceSize let borderRect = CGRect( x: (self.offset.x + self.margin.left) * scale, y: (self.offset.y + self.margin.top) * scale, width: (borderSize.width + self.padding.left + self.padding.right) * scale, height: (borderSize.height + self.padding.top + self.padding.bottom) * scale ) if border.radius > 0 { #if !os(OSX) borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: border.radius * 2) #else borderPath = NSBezierPath(roundedRect: borderRect, xRadius: border.radius * 2, yRadius: border.radius * 2) #endif } else { borderPath = FIBezierPath(rect: borderRect) } context.saveGState() context.setStrokeColor(border.color.cgColor) context.addPath(borderPath.cgPath) context.setLineWidth(border.lineWidth) context.replacePathWithStrokedPath() context.drawPath(using: .stroke) context.restoreGState() } /// Post-processing self.postProcessList.forEach { closure in closure(context, texture.width, texture.height, memoryPool) } guard let cgImage = context.makeImage() else { return nil } /// Corner Radius if self.corner.isZero() == false { let cornerDrawContext = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue) ) guard let cornerContext = cornerDrawContext else { return nil } let cornerPath = self.corner.clipPath(self.drawRect!) cornerContext.addPath(cornerPath.cgPath) cornerContext.clip() cornerContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height)) /// Convert Image return cornerContext.makeImage() } else { /// Convert Image return cgImage } } // MARK: - Lifecycle internal override init() { #if os(OSX) let devices = MTLCopyAllDevices() for device in devices { // [0] -> "AMD Radeon Pro 455", [1] -> "Intel(R) HD Graphics 530" #if swift(>=4.0) print(device.name) #else print(device.name!) #endif } self.device = devices[0] #else // Make device self.device = MTLCreateSystemDefaultDevice()! #endif // Make command queue #if swift(>=4.0) self.commandQueue = self.device.makeCommandQueue()! #else self.commandQueue = self.device.makeCommandQueue() #endif super.init() self.type = .Metal } } #endif
35.237942
130
0.472215
f8e989b650b78560a1ef0c4f77870c50ab588e7a
9,061
// // ThemeModel.swift // // // Created by Lukas Pistrol on 31.03.22. // import SwiftUI /// The Theme View Model. Accessible via the singleton "``ThemeModel/shared``". /// /// **Usage:** /// ```swift /// @StateObject /// private var themeModel: ThemeModel = .shared /// ``` public final class ThemeModel: ObservableObject { public static let shared: ThemeModel = .init() /// The selected appearance in the sidebar. /// - **0**: dark mode themes /// - **1**: light mode themes @Published var selectedAppearance: Int = 0 /// The selected tab in the main section. /// - **0**: Preview /// - **1**: Editor /// - **2**: Terminal @Published var selectedTab: Int = 1 /// An array of loaded ``Theme``. @Published public var themes: [Theme] = [] { didSet { saveThemes() objectWillChange.send() } } /// The currently selected ``Theme``. @Published public var selectedTheme: Theme? { didSet { AppPreferencesModel.shared.preferences.theme.selectedTheme = selectedTheme?.name } } /// Only themes where ``Theme/appearance`` == ``Theme/ThemeType/dark`` public var darkThemes: [Theme] { themes.filter { $0.appearance == .dark } } /// Only themes where ``Theme/appearance`` == ``Theme/ThemeType/light`` public var lightThemes: [Theme] { themes.filter { $0.appearance == .light } } private init() { do { try loadThemes() } catch { print(error) } } /// Loads a theme from a given url and appends it to ``themes``. /// - Parameter url: The URL of the theme /// - Returns: A ``Theme`` private func load(from url: URL) throws -> Theme { // get the data from the provided file let json = try Data(contentsOf: url) // decode the json into ``Theme`` let theme = try JSONDecoder().decode(Theme.self, from: json) return theme } /// Loads all available themes from `~/.codeedit/themes/` /// /// If no themes are available, it will create a default theme and save /// it to the location mentioned above. /// /// When overrides are found in `~/.codeedit/.preferences.json` /// they are applied to the loaded themes without altering the original /// the files in `~/.codeedit/themes/`. public func loadThemes() throws { // remove all themes from memory themes.removeAll() let url = themesURL var isDir: ObjCBool = false // check if a themes directory exists, otherwise create one if !filemanager.fileExists(atPath: url.path, isDirectory: &isDir) { try filemanager.createDirectory(at: url, withIntermediateDirectories: true) } // get all filenames in themes folder that end with `.json` let content = try filemanager.contentsOfDirectory(atPath: url.path).filter { $0.contains(".json") } // if the folder does not contain any themes create a default bundled theme, // write it to disk and return if content.isEmpty { guard let defaultUrl = Bundle.main.url(forResource: "default-dark", withExtension: "json") else { return } let json = try Data(contentsOf: defaultUrl) let jsonObject = try JSONSerialization.jsonObject(with: json) let prettyJSON = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) try prettyJSON.write(to: url.appendingPathComponent("Default (Dark).json")) return } let prefs = AppPreferencesModel.shared.preferences // load each theme from disk try content.forEach { file in let fileURL = url.appendingPathComponent(file) var theme = try load(from: fileURL) // get all properties of terminal and editor colors guard let terminalColors = try theme.terminal.allProperties() as? [String: Theme.Attributes], let editorColors = try theme.editor.allProperties() as? [String: Theme.Attributes] else { print("error") throw NSError() } // check if there are any overrides in `preferences.json` if let overrides = prefs?.theme.overrides[theme.name]?["terminal"] { terminalColors.forEach { (key, _) in if let attributes = overrides[key] { theme.terminal[key] = attributes } } } if let overrides = prefs?.theme.overrides[theme.name]?["editor"] { editorColors.forEach { (key, _) in if let attributes = overrides[key] { theme.editor[key] = attributes } } } // add the theme to themes array self.themes.append(theme) // if there already is a selected theme in `preferences.json` select this theme // otherwise take the first in the list self.selectedTheme = self.themes.first { $0.name == prefs?.theme.selectedTheme } ?? self.themes.first } } /// Removes all overrides of the given theme in /// `~/.codeedit/preferences.json` /// /// After removing overrides, themes are reloaded /// from `~/.codeedit/themes`. See ``loadThemes()`` /// for more information. /// /// - Parameter theme: The theme to reset public func reset(_ theme: Theme) { AppPreferencesModel.shared.preferences.theme.overrides[theme.name] = [:] do { try self.loadThemes() } catch { print(error) } } /// Removes the given theme from `–/.codeedit/themes` /// /// After removing the theme, themes are reloaded /// from `~/.codeedit/themes`. See ``loadThemes()`` /// for more information. /// /// - Parameter theme: The theme to delete public func delete(_ theme: Theme) { let url = themesURL .appendingPathComponent(theme.name) .appendingPathExtension("json") do { // remove the theme from the list try filemanager.removeItem(at: url) // remove from overrides in `preferences.json` AppPreferencesModel.shared.preferences.theme.overrides.removeValue(forKey: theme.name) // reload themes try self.loadThemes() } catch { print(error) } } /// Saves changes on theme properties to `overrides` /// in `~/.codeedit/preferences.json`. private func saveThemes() { let url = themesURL themes.forEach { theme in do { // load the original theme from `~/.codeedit/themes/` let originalUrl = url.appendingPathComponent(theme.name).appendingPathExtension("json") let originalData = try Data(contentsOf: originalUrl) let originalTheme = try JSONDecoder().decode(Theme.self, from: originalData) // get properties of the current theme as well as the original guard let terminalColors = try theme.terminal.allProperties() as? [String: Theme.Attributes], let editorColors = try theme.editor.allProperties() as? [String: Theme.Attributes], let oTermColors = try originalTheme.terminal.allProperties() as? [String: Theme.Attributes], let oEditColors = try originalTheme.editor.allProperties() as? [String: Theme.Attributes] else { throw NSError() } // compare the properties and if there are differences, save to overrides // in `preferences.json var newAttr: [String: [String: Theme.Attributes]] = ["terminal": [:], "editor": [:]] terminalColors.forEach { (key, value) in if value != oTermColors[key] { newAttr["terminal"]?[key] = value } } editorColors.forEach { (key, value) in if value != oEditColors[key] { newAttr["editor"]?[key] = value } } AppPreferencesModel.shared.preferences.theme.overrides[theme.name] = newAttr } catch { print(error) } } } /// Default instance of the `FileManager` private let filemanager = FileManager.default /// The base folder url `~/.codeedit/` private var baseURL: URL { filemanager.homeDirectoryForCurrentUser.appendingPathComponent(".codeedit") } /// The URL of the `themes` folder internal var themesURL: URL { baseURL.appendingPathComponent("themes", isDirectory: true) } }
35.394531
114
0.567818
7541364d76ed49c730e35dfb0f982df332fc5a5a
14,187
// // Response.swift // ACINetworking // // Created by 张伟 on 2021/11/12. // import Foundation #if canImport(AppKit) import AppKit public typealias Image = NSImage #elseif canImport(UIKit) import UIKit public typealias Image = UIImage #endif // MARK: - ProgressResponse public enum ProgressResponse { case progress(Progress) case completed(Result<Response, HTTPError>) } extension ProgressResponse { public var isCompleted: Bool { switch self { case .progress: return false case .completed: return true } } public var progress: Double { switch self { case let .progress(value): return value.fractionCompleted case .completed: return 1.0 } } public var response: Response? { switch self { case .progress: return nil case let .completed(result): return try? result.get() } } public var error: Error? { switch self { case .progress: return nil case let .completed(result): return result.error } } } // MARK: - Response public final class Response { public let request: URLRequest? public let response: HTTPURLResponse? public private(set) var data: Data? public let statusCode: Int public init (request: URLRequest?, response: HTTPURLResponse?, data: Data?) { self.request = request self.response = response self.data = data self.statusCode = response?.statusCode ?? Int.min } public func updateData(_ data: Data?) { self.data = data } } extension Response : CustomDebugStringConvertible { public var description: String { return "StatusCode: \(statusCode), data: \(data?.count ?? 0)" } public var debugDescription: String { return """ Response Request: \(request?.url?.absoluteString ?? "") StatusCode: \(statusCode) data: \(data?.count ?? 0) """ } } extension Response : Equatable {} public func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } // MAKR: - Filter extension Response { /// 过滤 Status Code 如果不为指定范围的 Code 时抛出异常 /// - Throws: HTTPError /// - Returns: 当前 Response public func filter<R: RangeExpression>(statusCodes: R) throws -> Response where R.Bound == Int { guard statusCodes.contains(statusCode) else { let context = HTTPError.Context(request: request, response: response) throw HTTPError.statusCode(code: statusCode, context: context) } return self } /// 过滤 Status Code 如果不为指定的 Code 时抛出异常 /// - Throws: HTTPError /// - Returns: 当前 Response public func filter(statusCode: Int) throws -> Response { return try filter(statusCodes: statusCode...statusCode) } /// 过滤 Status Code 如果不为正确的 Code 时抛出异常 /// - Throws: HTTPError /// - Returns: 当前 Response public func filterSuccessfulStatusCodes() throws -> Response { return try filter(statusCodes: 200...299) } /// 过滤 Status Code 如果不为正确或重定向 Code 时抛出异常 /// - Throws: HTTPError /// - Returns: 当前 Response public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filter(statusCodes: 200...399) } } // MARK: - Mapping extension Response { /// 将数据转换为图片 /// - Throws: HTTPError /// - Returns: 图片对象 public func mapImage(logSwitch: Bool = true) throws -> Image { guard let data = data else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.emptyResponse(context) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } guard let image = UIImage(data: data) else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: data, targetType: UIImage.self, context: context ) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } if logSwitch { HTTPLogger.logSuccess(.transform, urlRequest: request, data: image) } return image } /// 将数据转换为 JSON 对象 /// - Parameters: /// - atKeyPath: 从字典的中取出 `keyPath` 对应的值 /// - options: JSONSerialization.ReadingOptions /// - failsOnEmptyData: 错误时是否,返回一个 NSNull 对象 /// - Throws: HTTPError /// - Returns: JSON 对象 public func mapJSON( atKeyPath keyPath: String? = nil, options: JSONSerialization.ReadingOptions = [.allowFragments], failsOnEmptyData: Bool = true, logSwitch: Bool = true ) throws -> Any { guard let data = data else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.emptyResponse(context) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } do { let json = try JSONSerialization.jsonObject(with: data, options: options) if let keyPath = keyPath { guard let dictionary = (json as? [String: Any]) as NSDictionary?, let value = dictionary.value(forKey: keyPath) else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.emptyResponse(context) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } if logSwitch { HTTPLogger.logSuccess(.transform, urlRequest: request, data: value) } return value } else { if logSwitch { HTTPLogger.logSuccess(.transform, urlRequest: request, data: json) } return json } } catch { if data.count < 1 && !failsOnEmptyData { return NSNull() } let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: Any.self, context: context ) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } } /// 将数据转换为字符串 /// - Parameter keyPath: KeyPath /// - Throws: HTTPError /// - Returns: 字符串 public func mapString(atKeyPath keyPath: String? = nil, logSwitch: Bool = true) throws -> String { guard let data = data else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.emptyResponse(context) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } if let keyPath = keyPath { let value: Any do { value = try mapJSON(atKeyPath: keyPath, logSwitch: false) } catch let error as HTTPError { if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } catch { /// 此处错误抓取不会执行,此处仅保证 `mapJSON`方法抛出异常必定被捕捉到 let context = HTTPError.Context(request: request, response: response, underlyingError: error) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: String.self, context: context ) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } guard let string = value as? String else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: String.self, context: context ) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } if logSwitch { HTTPLogger.logSuccess(.transform, urlRequest: request, data: string) } return string } else { guard let string = String(data: data, encoding: .utf8) else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: String.self, context: context ) if logSwitch { HTTPLogger.logFailure(.transform, error: error) } throw error } if logSwitch { HTTPLogger.logSuccess(.transform, urlRequest: request, data: string) } return string } } /// 将数据转换为 JSON 对象 /// - Parameters: /// - type: 映射对象类型 /// - keyPath: 从字典的中取出 `keyPath` 对应的值,用于映射数据 /// - decoder: JSON 解析器 /// - failsOnEmptyData: 错误时是否,返回一个 NSNull 对象 /// - Throws: HTTPError /// - Returns: JSON 对象 public func map<T>( _ type: T.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true ) throws -> T where T: Decodable { let serializedData: Data? if let keyPath = keyPath, !keyPath.isEmpty { let value: Any do { value = try mapJSON(atKeyPath: keyPath, failsOnEmptyData: failsOnEmptyData, logSwitch: false) } catch let error as HTTPError { HTTPLogger.logFailure(.transform, error: error) throw error } catch { /// 此处错误抓取不会执行,此处仅保证 `mapJSON`方法抛出异常必定被捕捉到 let context = HTTPError.Context(request: request, response: response, underlyingError: error) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: T.self, context: context ) HTTPLogger.logFailure(.transform, error: error) throw error } if JSONSerialization.isValidJSONObject(value) { do { serializedData = try JSONSerialization.data(withJSONObject: value) } catch { let context = HTTPError.Context(request: request, response: response, underlyingError: error) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: T.self, context: context ) HTTPLogger.logFailure(.transform, error: error) throw error } } else { let wrappedJSONObject = ["value": value] let wrappedJSONData = try JSONSerialization.data(withJSONObject: wrappedJSONObject) do { let data = try decoder.decode(DecodableWrapper<T>.self, from: wrappedJSONData).value HTTPLogger.logSuccess(.transform, urlRequest: request, data: data) return data } catch { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: T.self, context: context ) HTTPLogger.logFailure(.transform, error: error) throw error } } } else { serializedData = data } guard let serializedData = serializedData else { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.emptyResponse(context) HTTPLogger.logFailure(.transform, error: error) throw error } do { let decodable = try decoder.decode(T.self, from: serializedData) HTTPLogger.logSuccess(.transform, urlRequest: request, data: decodable) return decodable } catch { let context = HTTPError.Context(request: request, response: response) let error = HTTPError.typeMismatch( value: try? mapJSON(logSwitch: false), targetType: T.self, context: context ) HTTPLogger.logFailure(.transform, error: error) throw error } } } // MARK: - DecodableWrapper private struct DecodableWrapper<T: Decodable>: Decodable { let value: T } // MARK: - Result public extension Result { var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } var isFailure: Bool { switch self { case .success: return false case .failure: return true } } var error: Error? { switch self { case .success: return nil case let .failure(error): return error } } }
31.526667
113
0.536689
1cecba7f976f8398853bd43abe5bb42a404b9e3c
6,815
// // SettingViewController.swift // HttpCapture // // Created by liuyihao1216 on 16/9/7. // Copyright © 2016年 liuyihao1216. All rights reserved. // import UIKit class IndexSection:NSObject{ var row = 0; var section = 0; } class SettingViewController: CaptureBaseViewController,UITableViewDelegate,UITableViewDataSource { var tableView = UITableView() var headerValues = NSMutableDictionary() var selectIndexpath = IndexSection() let browserName = "手机浏览器" let wxName = "微信" let qqName = "手q" override func viewDidLoad() { super.viewDidLoad() headerValues.setObject([browserName,wxName,qqName], forKey: "环境切换") selectIndexpath.row = 0; selectIndexpath.section = 0; self.automaticallyAdjustsScrollViewInsets = false tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Grouped) tableView.delegate = self; tableView.dataSource = self; tableView.tableFooterView = UIView(frame:CGRectZero) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellID") self.view.addSubview(tableView) } override func useDefaultBackButton() -> Bool{ return false; } func scrollToTop(){ self.tableView.scrollRectToVisible(CGRectMake(0, 0, self.view.width, 10), animated: true) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cell = tableView.dequeueReusableCellWithIdentifier("CellID") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CellID") } let keys = headerValues.allKeys if keys.count > indexPath.section { if let key = keys[indexPath.section] as? String, let ar = headerValues[key] as? Array<String> { cell?.textLabel?.text = ar[indexPath.row] } } cell?.textLabel?.numberOfLines = 3; cell?.textLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail; cell?.accessoryType = UITableViewCellAccessoryType.None if indexPath.row == selectIndexpath.row && indexPath.section == selectIndexpath.section { cell?.accessoryType = UITableViewCellAccessoryType.Checkmark } return cell! } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ let keys = headerValues.allKeys if keys.count > section { if let key = keys[section] as? String, let ar = headerValues[key] as? Array<String> { return ar.count; } } return 0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.cellForRowAtIndexPath(indexPath) let number = tableView.numberOfRowsInSection(indexPath.section) for var i=0;i < number;i=i+1 { let newIndexpath = NSIndexPath(forRow: i, inSection: indexPath.section) tableView.cellForRowAtIndexPath(newIndexpath)?.accessoryType = UITableViewCellAccessoryType.None } let keys = headerValues.allKeys if keys.count > indexPath.section { if let key = keys[indexPath.section] as? String, let _ = headerValues[key] as? Array<String> { cell?.accessoryType = UITableViewCellAccessoryType.Checkmark } } self.configUAPlatform(indexPath) } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let key = headerValues.allKeys[section] as? String { let header = UIButton(frame:CGRectMake(0,0,self.view.width,30)) header.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left header.setTitle(" \(key)", forState: UIControlState.Normal) header.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) header.titleLabel?.font = UIFont.boldSystemFontOfSize(14) header.titleLabel?.numberOfLines = 1 header.tag = 1000 + section // header.addTarget(self, action: "exposure:", forControlEvents: UIControlEvents.TouchUpInside) return header } return nil; } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30; } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return headerValues.allKeys.count } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { self.onSetMarginOrInset(true, fSetOffset: 10, cell: cell) } func configUAPlatform(indexPath:NSIndexPath) { let keys = headerValues.allKeys if keys.count > indexPath.section { if let key = keys[indexPath.section] as? String, let ar = headerValues[key] as? Array<String> { if ar[indexPath.row] == browserName { HttpCaptureManager.shareInstance().platform = UAPlatform.keepSameUA } else if ar[indexPath.row] == wxName { HttpCaptureManager.shareInstance().platform = UAPlatform.WeixinUA } else if ar[indexPath.row] == qqName { HttpCaptureManager.shareInstance().platform = UAPlatform.QQUA } } } } func onSetMarginOrInset(bSetTable:Bool,fSetOffset:CGFloat,cell:UITableViewCell){ if #available(iOS 8.0, *) { tableView.layoutMargins = UIEdgeInsetsZero cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = UIEdgeInsetsMake(0, fSetOffset, 0, 0) } tableView.separatorInset = UIEdgeInsetsZero cell.separatorInset = UIEdgeInsetsMake(0, fSetOffset, 0, 0) } func reload() { self.tableView.reloadData() } deinit { } }
35.494792
123
0.625238
9154abab8f0486227abaab31274bffde92f4b7e2
3,167
// // CharacteristicEmailAddress.swift // BluetoothMessageProtocol // // Created by Kevin Hoogheem on 8/19/17. // // 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 DataDecoder import FitnessUnits /// BLE Email Address Characteristic @available(swift 3.1) @available(iOS 10.0, tvOS 10.0, watchOS 3.0, OSX 10.12, *) open class CharacteristicEmailAddress: Characteristic { /// Characteristic Name public static var name: String { return "Email Address" } /// Characteristic UUID public static var uuidString: String { return "2A87" } /// Email Address private(set) public var emailAddress: String /// Creates Email Address Characteristic /// /// - Parameter emailAddress: Email Address public init(emailAddress: String) { self.emailAddress = emailAddress super.init(name: CharacteristicEmailAddress.name, uuidString: CharacteristicEmailAddress.uuidString) } /// Decodes Characteristic Data into Characteristic /// /// - Parameter data: Characteristic Data /// - Returns: Characteristic Result open override class func decode<C: CharacteristicEmailAddress>(with data: Data) -> Result<C, BluetoothDecodeError> { if let emailAddress = data.safeStringValue { return.success(CharacteristicEmailAddress(emailAddress: emailAddress) as! C) } return.failure(.invalidStringValue) } /// Deocdes the BLE Data /// /// - Parameter data: Data from sensor /// - Returns: Characteristic Instance /// - Throws: BluetoothDecodeError @available(*, deprecated, message: "use results based decoder instead") open override class func decode(data: Data) throws -> CharacteristicEmailAddress { return try decode(with: data).get() } /// Encodes the Characteristic into Data /// /// - Returns: Characteristic Data Result open override func encode() -> Result<Data, BluetoothEncodeError> { /// Not Yet Supported return.failure(BluetoothEncodeError.notSupported) } }
35.988636
120
0.70161
1cec5fc9947cf7ce4b79178de4028c3940447b03
976
// // User.swift // WCWeiBo // // Created by 王充 on 15/5/18. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class User: NSObject { /// 用户UID var id : Int = 0 /// 友好显示名称 var name : String? /// 用户头像地址(中图),50×50像素 var profile_image_url :String? { didSet{ iconUrl = NSURL(string: profile_image_url!) } } // 头像url var iconUrl : NSURL? /// 是否是微博认证用户,即加V用户,true:是,false:否 var verified: Bool = false /// 认证类型 -1:没有认证,0,认证用户,2,3,5: 企业认证,220: 草根明星 var verified_type : Int = -1 /// 属性数组 // 1~6 一共6级会员 var mbrank: Int = 0 private static let proparties = ["id","name","profile_image_url","verified","verified_type","mbrank"] init(dic : [String : AnyObject]){ super.init() for key in User.proparties { if dic[key] != nil { setValue(dic[key], forKey: key) } } } }
21.688889
105
0.530738
5b4ea3ab994205e197e7d399dde50deb6126cae5
796
// // MNBannerEntity.swift // Moon // // Created by YKing on 16/6/4. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNBannerEntity: NSObject { var start: Int = 0 var type: String? var id: Int = 0 var name: String? var entity_list: [MNBanner]? init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "entity_list" { guard let array = (value as?[[String : AnyObject]]) else { return } var bannerArray = [MNBanner]() for dict in array { bannerArray.append(MNBanner(dict:dict)) } entity_list = bannerArray return } super.setValue(value, forKey: key) } }
18.090909
66
0.586683
acde33aa988ed2c8004fbb2b82d48bb6d550547a
1,086
// // FlowLayout.swift // MoreFuncPage // // Created by ShenYj on 2020/11/26. // import UIKit internal class FLowLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() scrollDirection = .vertical sectionInset = UIEdgeInsets(top: verticalMargin, left: horizontalMargin, bottom: verticalMargin, right: horizontalMargin) minimumLineSpacing = verticalMargin minimumInteritemSpacing = horizontalMargin minimumInteritemSpacing = verticalMargin itemSize = CGSize(width: itemWidth, height: itemHeight) collectionView?.showsVerticalScrollIndicator = true collectionView?.showsHorizontalScrollIndicator = false sectionHeadersPinToVisibleBounds = true } var rowItemCount: Int { 4 } var horizontalMargin: CGFloat { 5 } var verticalMargin: CGFloat { 5 } var itemWidth: CGFloat { (UIScreen.main.bounds.width - CGFloat((rowItemCount + 1)) * horizontalMargin) / CGFloat(rowItemCount) } var itemHeight: CGFloat { itemWidth * 1.0 } }
31.941176
132
0.690608
214e94571ae78d7c195898d291e42e49fc8c8950
2,173
// // AppDelegate.swift // SpriteKitSwiftParticleTutorial // // Created by Arthur Knopper on 26/05/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.234043
285
0.756558
898f56b0a347d9982afd1d9966783e8997a6daf0
562
// // This source file is part of the Collector-Analyst-Presenter Example open source project // // SPDX-FileCopyrightText: 2021 Paul Schmiedmayer and the project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import AnalystPresenter import SwiftUI @main struct ExampleApp: App { @StateObject var model = Model() var body: some Scene { WindowGroup { ContentView(model: model) } } init() { Presenter.use(plugin: AnalystPresenter()) } }
19.37931
122
0.649466
d95a83aee2651433279fb75f6707d3b9d9dfd8ed
428
// 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 // RUN: not %target-swift-frontend %s -parse { if{ case{{ case((((){ class case,
28.533333
78
0.733645
29fbc1b465e6d8c7ac2fe2693a60fadfb3abecf0
964
// // CodeBaseTests.swift // CodeBaseTests // // Created by Hafiz on 18/09/2017. // Copyright © 2017 github. All rights reserved. // import XCTest @testable import CodeBase class CodeBaseTests: 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.054054
111
0.631743
1861e8d533fdfbeb5f01f23f8453a93e6e432dc5
381
// // FlipTransform.swift // FilestackSDK // // Created by Ruben Nine on 21/08/2017. // Copyright © 2017 Filestack. All rights reserved. // import Foundation /** Flips/mirrors the image vertically. */ @objc(FSFlipTransform) public class FlipTransform: Transform { /** Initializes a `FlipTransform` object. */ public init() { super.init(name: "flip") } }
16.565217
62
0.664042
39deeec5a5420a66b51e167edbd1af421fe56292
1,280
// // CollectionAnimationDemoUITests.swift // CollectionAnimationDemoUITests // // Created by Andrew on 16/7/20. // Copyright © 2016年 Andrew. All rights reserved. // import XCTest class CollectionAnimationDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.594595
182
0.673438
e61b1bd448bbb51d3b28ebf50d642761ad42c524
15,319
// // SynologySwiftURLResolver.swift // SynologySwift // // Created by Thomas le Gravier on 20/12/2018. // Copyright © 2018 Thomas Le Gravier. All rights reserved. // import Foundation public class SynologySwiftURLResolver { public struct DSInfos: Codable { public let quickId: String public let host: String public let port: Int public init(quickId: String, host: String, port: Int) { self.quickId = quickId self.host = host self.port = port } } static func resolve(quickConnectId: String, completion: @escaping (SynologySwift.Result<DSInfos>) -> ()) { /* Time profiler */ let startTime = DispatchTime.now() let endBlock: (SynologySwift.Result<DSInfos>) -> Void = { (result: SynologySwift.Result<DSInfos>) in let endTime = DispatchTime.now() SynologySwiftTools.logTimeProfileInterval(message: "URLResolver", start: startTime, end: endTime) completion(result) } getServerInfosForId(quickConnectId) { (result) in switch result { case .success(let data): let port = data.service?.port ?? SynologySwiftConstants.defaultPort /* Create Queues */ let pingpongQueue = OperationQueue() pingpongQueue.name = "Ping pong queue operation" let pingpongTunnelQueue = OperationQueue() pingpongTunnelQueue.name = "Ping pong existing tunnel queue operation" let newTunnelQueue = OperationQueue() newTunnelQueue.name = "Create new tunnel queue operation" ///// // 1 - Ping DS directly ///// SynologySwiftTools.logMessage("URLResolver : (Step 1) Test direct interfaces") /* Ping completion block */ var hasSuccedCompletePing = false let pingpongCompletion = { (result: SynologySwift.Result<SynologySwiftURLResolverObjectMapper.PingPongInfos>?) -> Void in /* Call after each pingpong call complete */ guard !hasSuccedCompletePing, let result = result else {return} switch result { case .success(let data): guard data.success && !data.diskHibernation, let host = data.host, let port = data.port else {return} /* Suspend queue & cancel other operations */ hasSuccedCompletePing = true pingpongQueue.isSuspended = true pingpongQueue.cancelAllOperations() pingpongTunnelQueue.isSuspended = true pingpongTunnelQueue.cancelAllOperations() newTunnelQueue.isSuspended = true newTunnelQueue.cancelAllOperations() let infos = self.DSInfos(quickId: quickConnectId, host: host, port: port) return endBlock(SynologySwift.Result.success(infos)) case .failure(_): (/* Nothing to do, not reachable */) } } /* Ping interfaces */ if let interfaces = data.server?.interface { pingPongOperationsForInterfaces(interfaces, withPortService: port, forQueue: pingpongQueue, withCompletion: { (result) in pingpongCompletion(result) }) } /* Ping host address ddns */ if let ddns = data.server?.ddns, ddns != "NULL" { let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: ddns, port: port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {pingpongCompletion(asyncOperation.result)} pingpongQueue.addOperation(asyncOperation) } /* Ping host address fqdn */ if let fqdn = data.server?.fqdn, fqdn != "NULL" { let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: fqdn, port: port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {pingpongCompletion(asyncOperation.result)} pingpongQueue.addOperation(asyncOperation) } /* Ping external address IPV4 */ if let ip = data.server?.external?.ip { let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: ip, port: data.server?.external?.port ?? port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {pingpongCompletion(asyncOperation.result)} pingpongQueue.addOperation(asyncOperation) } /* Ping external address IPV6 */ if let ip = data.server?.external?.ipv6, ip != "::" { let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: ip, port: data.server?.external?.port ?? port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {pingpongCompletion(asyncOperation.result)} pingpongQueue.addOperation(asyncOperation) } ///// // 2 - Ping DS through existing tunnel ///// pingpongTunnelQueue.addOperation({ pingpongQueue.waitUntilAllOperationsAreFinished() /* Check if tunnel existing */ guard let service = data.service, let relayIp = service.relayIp, let relayPort = service.relayPort, port != 0 else {return} let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in SynologySwiftTools.logMessage("URLResolver : (Step 2) Test existing tunnel") testPingPongHost(host: relayIp, port: relayPort, timeout: 10, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {pingpongCompletion(asyncOperation.result)} pingpongTunnelQueue.addOperation(asyncOperation) }) ///// // 3 - Request tunnel ///// newTunnelQueue.addOperation({ pingpongTunnelQueue.waitUntilAllOperationsAreFinished() guard let controlHost = data.environment?.host else { return endBlock(.failure(.other("No valid url resolved - Control host missing"))) } let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.ServerInfos>() asyncOperation.setBlockOperation { (operationEnded) in SynologySwiftTools.logMessage("URLResolver : (Step 3) Start tunnel creation") let params = [ "id": "dsm", "serverID": quickConnectId, "command": "request_tunnel", "version": "1" ] SynologySwiftCoreNetwork.performRequest(with: "https://\(controlHost)/Serv.php", for: SynologySwiftURLResolverObjectMapper.ServerInfos.self, method: .POST, params: params, timeout: 60) { (result) in switch result { case .success(let serverInfos): operationEnded(.success(serverInfos)) case .failure(let error): operationEnded(.failure(.requestError(error))) } } } asyncOperation.completionBlock = { guard let result = asyncOperation.result else { return endBlock(.failure(.other("No valid url resolved - No valid result"))) } switch result { case .success(let data): guard let ip = data.service?.relayIp, let port = data.service?.relayPort else { return endBlock(.failure(.other("No valid url resolved - Relay informations missing"))) } let infos = DSInfos(quickId: quickConnectId, host: ip, port: port) return endBlock(.success(infos)) case .failure(let error): return endBlock(.failure(error)) } } newTunnelQueue.addOperation(asyncOperation) }) case .failure(let error): endBlock(.failure(error)) } } } static func ping(dsInfos: SynologySwiftURLResolver.DSInfos, completion: @escaping (SynologySwift.Result<DSInfos>) -> ()) { /* Test dsInfos interface */ testPingPongHost(host: dsInfos.host, port: dsInfos.port, timeout: 10, completion: { (result) in switch result { case .success(let data): if data.success && !data.diskHibernation { completion(.success(dsInfos)) } else { completion(.failure(.other("Ping error. Disk maybe under hibernation but host is reachable."))) } case .failure(let error): completion(.failure(error)) } }) } /* * Get server infos */ private static func getServerInfosForId(_ quickConnectId: String, completion: @escaping (SynologySwift.Result<SynologySwiftURLResolverObjectMapper.ServerInfos>) -> ()) { let params = [ "id": "dsm", "serverID": quickConnectId, "command": "get_server_info", "version": "1" ] SynologySwiftCoreNetwork.performRequest(with: "https://global.QuickConnect.to/Serv.php", for: SynologySwiftURLResolverObjectMapper.ServerInfos.self, method: .POST, params: params) { (result) in switch result { case .success(let serverInfos): /* Check data integrity */ if serverInfos.error == 0 {completion(.success(serverInfos))} else { let errorDescription = serverInfos.errorInfo ?? "An error occured - Server infos not reachable" completion(.failure(.other(SynologySwiftTools.parseErrorMessage(errorDescription)))) } case .failure(let error): completion(.failure(.requestError(error))) } } } } private typealias SynologySwiftURLResolverPingPong = SynologySwiftURLResolver extension SynologySwiftURLResolverPingPong { private static func pingPongOperationsForInterfaces(_ interfaces: [SynologySwiftURLResolverObjectMapper.ServerInfosServerInterface], withPortService port: Int, forQueue queue: OperationQueue, withCompletion handler: ((SynologySwift.Result<SynologySwiftURLResolverObjectMapper.PingPongInfos>?)->())? = nil) { var operations: [Operation] = [] for interface in interfaces { /* IPV4 interface */ if let ip = interface.ip { let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: ip, port: port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {handler?(asyncOperation.result)} operations.append(asyncOperation) } /* IPV6 interfaces */ if let ipv6 = interface.ipv6 { for ip in ipv6 { guard ip.address != "::" else {continue} let asyncOperation = SynologySwiftAsyncOperation<SynologySwiftURLResolverObjectMapper.PingPongInfos>() asyncOperation.setBlockOperation { (operationEnded) in testPingPongHost(host: "[\(ip.address)]", port: port, completion: { (result) in operationEnded(result) }) } asyncOperation.completionBlock = {handler?(asyncOperation.result)} operations.append(asyncOperation) } } } queue.addOperations(operations, waitUntilFinished: false) } private static func testPingPongHost(host: String, port: Int? = nil, timeout: TimeInterval = 5, completion: @escaping (SynologySwift.Result<SynologySwiftURLResolverObjectMapper.PingPongInfos>) -> ()) { var url = "http://\(host)" if let port = port {url = url + ":\(String(port))"} SynologySwiftCoreNetwork.performRequest(with: url + "/webman/pingpong.cgi", for: SynologySwiftURLResolverObjectMapper.PingPongInfos.self, timeout: timeout) { (result) in switch result { case .success(var success): success.host = host; success.port = port; completion(.success(success)) case .failure(let error): completion(.failure(.requestError(error))) } } } }
49.099359
311
0.528951
dba265f32322510ac65c0ea01860b7c69e0510b2
859
// // Picker+MediaType.swift // AnyImageKit // // Created by 刘栋 on 2020/1/6. // Copyright © 2020-2021 AnyImageProject.org. All rights reserved. // import Photos extension MediaType { init(asset: PHAsset, selectOptions: PickerSelectOption) { let selectPhotoGIF = selectOptions.contains(.photoGIF) let selectPhotoLive = selectOptions.contains(.photoLive) switch asset.mediaType { case .image: if selectPhotoLive && asset.mediaSubtypes == .photoLive { self = .photoLive } else { if selectPhotoGIF && asset.isGIF { self = .photoGIF } else { self = .photo } } case .video: self = .video default: self = .photo } } }
24.542857
69
0.521537
f89f682340d98aed8f97756708c35f4e9a280538
8,093
// // StackedCollectionViewLayout.swift // HypeKit // // Created by Tony Heupel on 01/05/2017. // Copyright © 2017 Tony Heupel.. All rights reserved. // import Foundation protocol StackedCollectionViewLayoutDelegate: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, heightForCellAtIndexPath indexPath:IndexPath, withWidth:CGFloat) -> CGFloat func collectionView(_ collectionView: UICollectionView, layoutAttributesForCellAtIndexPath indexPath: IndexPath, withFrame: CGRect) -> UICollectionViewLayoutAttributes func collectionView(_ collectionView: UICollectionView, collectionViewLayout layout: UICollectionViewLayout, referenceSizeForHeaderInSection section :Int) -> CGSize func layoutAttributesForSupplementaryViewOfKind(_ elementKind: String, atIndexPath indexPath: IndexPath) -> UICollectionViewLayoutAttributes? } class StackedCollectionViewLayout: UICollectionViewFlowLayout { // MARK: - Properties var delegate: StackedCollectionViewLayoutDelegate? var numberOfColumns = 2 var spaceBetweenCellsOnSameLine: CGFloat = 8 var spaceBetweenLines: CGFloat = 8 var spaceBetweenHeaderAndResults: CGFloat = 8 var defaultCellHeight: CGFloat = 100 var customLayoutAttributesClass: AnyClass? = nil let indexPathItemForHeader = 0 let indexPathItemForFooter = 0 // MARK: - Private properties fileprivate var layoutAttributesCache = [IndexPath: UICollectionViewLayoutAttributes]() fileprivate var headerLayoutAttributesCache = [IndexPath: UICollectionViewLayoutAttributes]() fileprivate var contentWidth: CGFloat = 0.0 fileprivate var contentHeight: CGFloat = 0.0 // MARK: - Overrides - Instance override var collectionViewContentSize : CGSize { // These are calculated in prepareLayout return CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return layoutAttributesCache[indexPath] } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if elementKind == UICollectionElementKindSectionHeader { return headerLayoutAttributesCache[indexPath] } return nil } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // The cache is populated as part of prepareLayout var layoutAttributes = [UICollectionViewLayoutAttributes]() var allLayoutAttributes: Array<UICollectionViewLayoutAttributes> = Array(layoutAttributesCache.values) allLayoutAttributes.append(contentsOf: headerLayoutAttributesCache.values) for attributes in allLayoutAttributes { if attributes.frame.intersects(rect) { layoutAttributes.append(attributes) } } return layoutAttributes } override func prepare() { // Specifically only check the cell layout attributes cache and not // the header and footers since the results determine whether there // are any headers and footers if !layoutAttributesCache.isEmpty { return } calculateLayoutAttributes() } override func invalidateLayout() { super.invalidateLayout() layoutAttributesCache.removeAll() headerLayoutAttributesCache.removeAll() } // MARK: - Private helpers fileprivate func calculateXOffsetsWithLeftInset(_ leftInset: CGFloat, andColumnWidth columnWidth: CGFloat) -> [CGFloat] { var offsets = [CGFloat]() for columnIndex in 0..<numberOfColumns { offsets.append(CGFloat(columnIndex) * (columnWidth + CGFloat(spaceBetweenCellsOnSameLine))) } return offsets } fileprivate func calculateLayoutAttributes() { let insets = collectionView!.contentInset contentWidth = (collectionView!.bounds.width - (insets.left + insets.right)) contentHeight = 0 let columnWidth = (contentWidth - (CGFloat(numberOfColumns - 1) * spaceBetweenCellsOnSameLine)) / CGFloat(numberOfColumns) var xOffsets = calculateXOffsetsWithLeftInset(insets.left, andColumnWidth: columnWidth) let numberOfSections = collectionView?.numberOfSections ?? 0 var needSpaceBetweenLines = false for sectionIndex in 0..<numberOfSections { var headerSize = CGSize.zero if let d = delegate { headerSize = d.collectionView(self.collectionView!, collectionViewLayout: self, referenceSizeForHeaderInSection: sectionIndex) if headerSize.height > 0 || headerSize.width > 0 { let indexPathForSectionHeader = IndexPath(item: indexPathItemForHeader, section: sectionIndex) if let headerAttributes = d.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: indexPathForSectionHeader) { // Adjust the origin.y value to account for where this WILL be: headerAttributes.frame = CGRect(origin: CGPoint(x: headerAttributes.frame.origin.x, y: contentHeight), size: headerAttributes.frame.size) headerLayoutAttributesCache[indexPathForSectionHeader] = headerAttributes contentHeight += headerAttributes.bounds.height + spaceBetweenHeaderAndResults needSpaceBetweenLines = true } } } var yOffsets = [CGFloat](repeating: contentHeight, count: numberOfColumns) var columnIndex = 0 let numberOfItemsInCurrentSection = collectionView?.numberOfItems(inSection: sectionIndex) ?? 0 for itemIndex in 0..<numberOfItemsInCurrentSection { let indexPath = IndexPath(item: itemIndex, section: sectionIndex) let width = columnWidth var innerContentHeight: CGFloat { if let d = delegate { return d.collectionView(collectionView!, heightForCellAtIndexPath: indexPath, withWidth: width) } return defaultCellHeight } let height = innerContentHeight let cellFrame = CGRect(x: xOffsets[columnIndex], y: yOffsets[columnIndex], width: columnWidth, height: height) var attributes: UICollectionViewLayoutAttributes? = nil if let d = delegate { attributes = d.collectionView(collectionView!, layoutAttributesForCellAtIndexPath: indexPath, withFrame: cellFrame) } else { attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes!.frame = cellFrame } layoutAttributesCache[indexPath] = attributes! contentHeight = max(contentHeight, cellFrame.maxY) yOffsets[columnIndex] = yOffsets[columnIndex] + height + spaceBetweenLines columnIndex = calculateNextColumnIndexBasedOnCurrentYOffsets(yOffsets) needSpaceBetweenLines = true } // Make sure that as we start a new section, we retain our margin between lines if needSpaceBetweenLines { contentHeight += spaceBetweenLines } } contentHeight += insets.bottom } fileprivate func calculateNextColumnIndexBasedOnCurrentYOffsets(_ yOffsets: [CGFloat]) -> Int { // Return the column that has the top-most offset to fill that in next var minOffset = CGFloat.greatestFiniteMagnitude var minOffsetIndex = 0 for (index, offset) in yOffsets.enumerated() { if offset < minOffset { minOffsetIndex = index minOffset = offset } } return minOffsetIndex } }
39.286408
171
0.677746
8f76aa094f9784d6c58331b1c61e80ad162e077e
1,711
import Foundation import RealmSwift import RuuviOntology public class SensorSettingsRealm: Object { @objc public dynamic var luid: String? @objc public dynamic var macId: String? public let temperatureOffset = RealmProperty<Double?>() @objc public dynamic var temperatureOffsetDate: Date? public let humidityOffset = RealmProperty<Double?>() @objc public dynamic var humidityOffsetDate: Date? public let pressureOffset = RealmProperty<Double?>() @objc public dynamic var pressureOffsetDate: Date? public convenience init(ruuviTag: RuuviTagSensor) { self.init() luid = ruuviTag.luid?.value macId = ruuviTag.macId?.value } public convenience init(settings: SensorSettings) { self.init() luid = settings.luid?.value macId = settings.macId?.value temperatureOffset.value = settings.temperatureOffset temperatureOffsetDate = settings.temperatureOffsetDate humidityOffset.value = settings.humidityOffset humidityOffsetDate = settings.humidityOffsetDate pressureOffset.value = settings.pressureOffset pressureOffsetDate = settings.pressureOffsetDate } } extension SensorSettingsRealm { public var sensorSettings: SensorSettings { return SensorSettingsStruct( luid: luid?.luid, macId: macId?.mac, temperatureOffset: temperatureOffset.value, temperatureOffsetDate: temperatureOffsetDate, humidityOffset: humidityOffset.value, humidityOffsetDate: humidityOffsetDate, pressureOffset: pressureOffset.value, pressureOffsetDate: pressureOffsetDate ) } }
33.54902
62
0.700175
229e928022ae0935b511a65c3d6d58e5b6c1e703
1,569
// // EligibilityRequestTests.swift // SwiftFHIR // // Generated from FHIR 1.0.2.7202 on 2016-09-16. // 2016, SMART Health IT. // import XCTest import SwiftFHIR class EligibilityRequestTests: XCTestCase { func instantiateFrom(filename: String) throws -> SwiftFHIR.EligibilityRequest { return instantiateFrom(json: try readJSONFile(filename)) } func instantiateFrom(json: FHIRJSON) -> SwiftFHIR.EligibilityRequest { let instance = SwiftFHIR.EligibilityRequest(json: json) XCTAssertNotNil(instance, "Must have instantiated a test instance") return instance } func testEligibilityRequest1() { do { let instance = try runEligibilityRequest1() try runEligibilityRequest1(instance.asJSON()) } catch { XCTAssertTrue(false, "Must instantiate and test EligibilityRequest successfully, but threw") } } @discardableResult func runEligibilityRequest1(_ json: FHIRJSON? = nil) throws -> SwiftFHIR.EligibilityRequest { let inst = (nil != json) ? instantiateFrom(json: json!) : try instantiateFrom(filename: "eligibilityrequest-example.json") XCTAssertEqual(inst.created?.description, "2014-08-16") XCTAssertEqual(inst.id, "52345") XCTAssertEqual(inst.identifier?[0].system?.absoluteString, "http://happyvalley.com/elegibilityrequest") XCTAssertEqual(inst.identifier?[0].value, "52345") XCTAssertEqual(inst.organization?.reference, "Organization/2") XCTAssertEqual(inst.text?.div, "<div>A human-readable rendering of the EligibilityRequest</div>") XCTAssertEqual(inst.text?.status, "generated") return inst } }
31.38
124
0.752709
03f04b7d53deaa90808abc61c367f2bd9efd0b08
2,284
// // SceneDelegate.swift // CXG-Demo // // Created by CuiXg on 2021/9/5. // 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.09434
147
0.711909
fb9cc5991761378378036f9aa6e7bba919da28d8
2,133
// Copyright © 2019 Pedro Daniel Prieto Martínez. Distributed under MIT License. public protocol SectionManager: AnyObject { func add(section: Section, at index: Int?, notify: Bool) func update(section: Section, at index: Int, notify: Bool) func update(sectionData: SectionDataModelType, at index: Int, notify: Bool) func update(allSections sections: [Section], notify: Bool) func remove(sectionAt index: Int, notify: Bool) func removeAllSections(notify: Bool) } extension DataSourceController: SectionManager { public func add( section: Section, at index: Int? = nil, notify: Bool = true ) { if let index = index, (0..<sectionCount).contains(index) { sections.insert(section, at: index) } else { sections.append(section) } if notify { delegate?.dataSourceWasMutated(self) } } public func update( section: Section, at index: Int, notify: Bool = true ) { guard (0..<sectionCount).contains(index) else { return } sections[index] = section if notify { delegate?.dataSourceWasMutated(self, section: index) } } public func update( sectionData: SectionDataModelType, at index: Int, notify: Bool = true ) { guard (0..<sectionCount).contains(index) else { return } let section = sections[index] section.sectionData = sectionData update(section: section, at: index, notify: notify) } public func update( allSections sections: [Section], notify: Bool = true ) { self.sections = sections if notify { delegate?.dataSourceWasMutated(self) } } public func remove( sectionAt section: Int, notify: Bool = true ) { guard (0..<sectionCount).contains(section) else { return } sections.remove(at: section) if notify { delegate?.dataSourceWasMutated(self) } } public func removeAllSections(notify: Bool) { sections.removeAll() if notify { delegate?.dataSourceWasMutated(self) } } }
30.913043
81
0.622128
5b9545dddf4478e8b99f8aef0415909c00c6c586
2,694
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s class C { init(x: Int) {} required init(required: Double) {} } class D { required init(required: Double) {} } protocol P { init(proto: String) } extension P { init(protoExt: Float) { self.init(proto: "") } } // CHECK-LABEL: sil hidden @_T018partial_apply_init06class_c1_a1_B0{{[_0-9a-zA-Z]*}}F func class_init_partial_apply(c: C.Type) { // Partial applications at the static metatype use the direct (_TTd) thunk. // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd let xC: (Int) -> C = C.init // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd let requiredC: (Double) -> C = C.init // Partial applications to a dynamic metatype must be dynamically dispatched and use // the normal thunk. // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredM: (Double) -> C = c.init } // CHECK-LABEL: sil shared [thunk] @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK-LABEL: sil shared [thunk] @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK-LABEL: sil shared [thunk] @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK: class_method %0 : $@thick C.Type, #C.init!allocator.1 // CHECK-LABEL: sil hidden @_T018partial_apply_init010archetype_c1_a1_B0{{[_0-9a-zA-Z]*}}F func archetype_init_partial_apply<T: C where T: P>(t: T.Type) { // Archetype initializations are always dynamic, whether applied to the type or a metatype. // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredT: (Double) -> T = T.init // CHECK: function_ref @_T018partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC let protoT: (String) -> T = T.init // CHECK: function_ref @_T018partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC let protoExtT: (Float) -> T = T.init // CHECK: function_ref @_T018partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredM: (Double) -> T = t.init // CHECK: function_ref @_T018partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC let protoM: (String) -> T = t.init // CHECK: function_ref @_T018partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC let protoExtM: (Float) -> T = t.init } // CHECK-LABEL: sil shared [thunk] @_T018partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC // CHECK: witness_method $Self, #P.init!allocator.1 // CHECK-LABEL: sil shared [thunk] @_T018partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC // CHECK: function_ref @_T018partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC
40.208955
93
0.691908
5b4ba6869c6e63a4cb2c7a8fa963008bfc3188ef
3,033
// // AppDelegate.swift // CloudKitDemo // // Created by Douglas Frari on 17/08/18. // Copyright © 2018 CESAR School. All rights reserved. // import UIKit // pacote Cloud Kit import CloudKit extension UIViewController { var container: CKContainer { // caminho do Container return CKContainer(identifier: "iCloud.school.cesar.apps.turma2018.CloudKit.CloudKitDemo") } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. configureCloudKit() 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:. } private func configureCloudKit() { // caminho do Container let container = CKContainer(identifier: "iCloud.school.cesar.apps.turma2018.CloudKit.CloudKitDemo") container.privateCloudDatabase.fetchAllRecordZones { zones, error in guard let zones = zones, error == nil else { // error handling magic print(error.debugDescription) return } print("I have these zones: \(zones)") } } }
38.392405
285
0.701945
76021416b6ef202951593724ae9eeed9a2563d5d
2,279
import Foundation import MapKit import UIKit final class SnapShotter: ObservableObject { let defaultMap: UIImage private(set) var mapSnapShot: UIImage? private let imageName: String private let region: MKCoordinateRegion private let fileLocation: URL private let options: MKMapSnapshotter.Options private var mapSnapshotter : MKMapSnapshotter? @Published private(set) var isOnDevice = false init(imageName: String, region: MKCoordinateRegion) { self.imageName = imageName self.region = region guard let map = UIImage(named: "map.png") else { fatalError("Missing default map") } self.defaultMap = map options = MKMapSnapshotter.Options() options.region = region options.size = CGSize(width: 200, height: 200) options.scale = UIScreen.main.scale let fileManager = FileManager.default guard let url = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else { fatalError("Unable to get file.") } fileLocation = url.appendingPathComponent("\(imageName).png") if fileManager.fileExists(atPath: fileLocation.path), let image = UIImage(contentsOfFile: fileLocation.path) { mapSnapShot = image isOnDevice = true } } func takeSnapShot() { mapSnapshotter = MKMapSnapshotter(options: options) mapSnapshotter?.start { snapshot, error in guard let snapshot = snapshot else { fatalError("Unable to take snapshot") } let imageData = snapshot.image.pngData() guard let data = imageData, let imageSnapshot = UIImage(data: data) else { fatalError("Unable to produce map image") } DispatchQueue.main.async { [weak self] in self?.isOnDevice = true self?.writeToDisk(imageData: data) self?.mapSnapShot = imageSnapshot } } } func writeToDisk(imageData: Data) { do { try imageData.write(to: fileLocation) } catch { fatalError("Unable to write file") } } }
32.098592
118
0.598947
bf52aa74a9c6eba17b3b27db6c08d888c139c900
1,856
/* * Copyright (c) 2019 Telekom Deutschland AG * * 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 MicroBlink public class RomaniaIDFrontCardResult: IDCardResult { public var cardNumber: String? public var idSeries: String? public var cnp: String? public var parentNames: String? public var nonMRZNationality: String? public var placeOfBirth: String? public var nonMRZSex: String? public var validFrom: Date? public var rawValidFrom: String? public var validUntil: Date? public var rawValidUntil: String? init(with result: MBRomaniaIdFrontRecognizerResult) { super.init() self.lastName = result.lastName self.firstName = result.firstName self.cardNumber = result.cardNumber self.idSeries = result.idSeries self.cnp = result.cnp self.parentNames = result.parentNames self.nonMRZNationality = result.nonMRZNationality self.placeOfBirth = result.placeOfBirth self.address = result.address self.issuer = result.issuedBy self.nonMRZSex = result.nonMRZSex self.validFrom = result.validFrom self.rawValidFrom = result.rawValidFrom self.validUntil = result.validUntil self.rawValidUntil = result.rawValidUntil self.faceImage = result.faceImage?.image } }
34.37037
74
0.709052
64a9cd9d00a78b84282c17139008a6cf7daaf2c9
44,462
// // GTAlertCollection.swift // // Created by Gabriel Theodoropoulos. // // MIT License // Copyright © 2018 Gabriel Theodoropoulos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /// A collection of several `UIAlertController` variations gathered in one place. /// /// With `GTAlertCollection` you can present fast, easily and efficiently: /// /// * One-button alert controller /// * Alert controller with variable number of buttons with all supported styles: Default, Cancel, Destructive /// * Buttonless alert controller /// * Alert controller with an activity indicator /// * Alert controller with a progress bar, including text representation of the progress (either percentage, or number of steps made) /// * Alert controller with a single text field /// * Alert controller with multiple text fields /// * Alert controller with an image view /// /// See more on [GitHub](https://github.com/gabrieltheodoropoulos/gtalertcollection) class GTAlertCollection: NSObject { // MARK: - Properties /// The `GTAlertCollection` shared instance. static let shared = GTAlertCollection() /// The presented alert controller. var alertController: UIAlertController! /// The view controller that the alert controller is presented to. var hostViewController: UIViewController! /// The activity indicator of the alert. var activityIndicator: UIActivityIndicatorView! /// The `UIProgressView` object that displays the progress bar. var progressBar: UIProgressView! /// The label right below the progress bar. var label: UILabel! /// The image view of the alert. var imageView: UIImageView! // MARK: - Initialization /// Custom `init` method that accepts the host view controller as an argument. /// /// You are advised to use this initializer when creating objects of this class and you are not /// using the shared instance. /// /// - Parameter hostViewController: The view controller that will present the alert controller. init(withHostViewController hostViewController: UIViewController) { super.init() self.hostViewController = hostViewController } /// Default `init` method. override init() { super.init() } // MARK: - Fileprivate Methods /// It makes the alertController property `nil` in case it's not already. fileprivate func cleanUpAlertController() { if alertController != nil { alertController = nil if let _ = self.progressBar { self.progressBar = nil } if let _ = self.label { self.label = nil } if let _ = self.imageView { self.imageView = nil } } } /// It creates and returns `UIAlertAction` objects for the alert controller. /// /// - Parameters: /// - buttonTitles: The titles of the action buttons. /// - cancelButtonIndex: The position of the Cancel-styled action among all action buttons (if any). /// - destructiveButtonIndices: An array with the positions of Destructive-styled action buttons among all action buttons (if any). /// - actionHandler: The action handler to be called when an action button gets tapped. /// - Returns: A collection with `UIAlertAction` objects that must be added to the alert controller. fileprivate func createAlertActions(usingTitles buttonTitles: [String], cancelButtonIndex: Int?, destructiveButtonIndices: [Int]?, actionHandler: @escaping (_ actionIndex: Int) -> Void) -> [UIAlertAction] { var actions = [UIAlertAction]() // Create as many UIAlertAction actions as the items in the buttonTitles array are. for i in 0..<buttonTitles.count { // By default, all action buttons will have the .default style. var buttonStyle: UIAlertAction.Style = .default // Check if there should be a Cancel-like button. if let index = cancelButtonIndex { // Check if the current button should be displayed using the .cancel style. if index == i { // If so, set the proper button style. buttonStyle = .cancel } } // Check if there should be destructive buttons. if let destructiveButtonIndices = destructiveButtonIndices { // Go through each destructive button index and check if the current button should be one of them. for index in destructiveButtonIndices { if index == i { // If so, apply the .destructive style. buttonStyle = .destructive break } } } // Create a new UIAlertAction and pass the title for the current button, as well as the button style as defined above. let action = UIAlertAction(title: buttonTitles[i], style: buttonStyle, handler: { (action) in // Call the actionHandler passing the index of the current action when user taps on the current one. actionHandler(i) }) // Append each new action to the actions array. actions.append(action) } // Return the collection of the alert actions. return actions } // MARK: - Public Methods /// It dismisses the alert controller. /// /// - Parameter completion: If the `completion` is not `nil`, it's called to notify that the alert has been dismissed. func dismissAlert(completion: (() -> Void)?) { DispatchQueue.main.async { [unowned self] in if let alertController = self.alertController { alertController.dismiss(animated: true) { self.alertController = nil if let _ = self.progressBar { self.progressBar = nil } if let _ = self.label { self.label = nil } if let _ = self.imageView { self.imageView = nil } if let completion = completion { completion() } } } } } /// It presents the alert controller with one action button only. /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - buttonTitle: The action button title. Required. /// - actionHandler: It's called when the action button is tapped by the user. Use it to implement the required logic after the user has tapped on your alert's button. func presentSingleButtonAlert(withTitle title: String?, message: String?, buttonTitle: String, actionHandler: @escaping () -> Void) { // Check if the hostViewController has been set. if let hostVC = hostViewController { // Perform all actions on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController object is nil before initializing it. self.cleanUpAlertController() // Initialize the alertController object. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Create one UIAlertAction using the .default style. let action = UIAlertAction(title: buttonTitle, style: UIAlertAction.Style.default, handler: { (action) in // Call the actionHandler when the action button is tapped. actionHandler() }) // Add the alert action to the alert controller. self.alertController.addAction(action) // Present the alert controller to the host view controller. hostVC.present(self.alertController, animated: true, completion: nil) } } else { // The host view controller has no value. NSLog("[GTAlertCollection]: No host view controller was specified") } } /// It presents an alert controller with as many action buttons as the `buttonTitles` array items, using the provided title and message for the displayed text. /// It can have one *Cancel-styled* and one or more *Destructive-styled* action buttons. /// /// - Parameters: /// - title: The *optional* title of the alert. /// - message: The *optional* message of the alert. /// - buttonTitles: The array with the action button titles. Give the titles in the order you want them to appear. /// - cancelButtonIndex: If there's a *Cancel-styled* button you want to exist among buttons, then here's the place where you specify it's **position** in the `buttonTitles` array. Pass `nil` if there's no Cancel-styled button. /// - destructiveButtonIndices: An array with the **position** of one or more *destructive* buttons in the collection of buttons. Pass `nil` if you have no destructive buttons to show. /// - actionHandler: Use this block to determine which action button was tapped by the user. An `actionIndex` value provides you with that information. func presentAlert(withTitle title: String?, message: String?, buttonTitles: [String], cancelButtonIndex: Int?, destructiveButtonIndices: [Int]?, actionHandler: @escaping (_ actionIndex: Int) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Perform all operations on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController object is nil. self.cleanUpAlertController() // Initialize the alert controller using the given title and message. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Create the action buttons and add them to the alert controller. let actions = self.createAlertActions(usingTitles: buttonTitles, cancelButtonIndex: cancelButtonIndex, destructiveButtonIndices: destructiveButtonIndices, actionHandler: actionHandler) for action in actions { self.alertController.addAction(action) } // After having finished with the actions, present the alert controller animated. hostVC.present(self.alertController, animated: true, completion: nil) } } else { // The host view controller has no value. NSLog("[GTAlertCollection]: No host view controller was specified") } } /// It presents a buttonless alert controller. /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - presentationCompletion: Called after the alert controller has been presented or when the `hostViewController` is `nil`, and indicates whether the alert controller was presented successfully or not. /// - success: When `true` the alert controller has been successfully presented to the host view controller, otherwise it's `false`. func presentButtonlessAlert(withTitle title: String?, message: String?, presentationCompletion: @escaping (_ success: Bool) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Operate on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Present the alert controller to the host view controller. hostVC.present(self.alertController, animated: true, completion: { // Pass true to the presentationCompletion indicating that the alert controller was presented. presentationCompletion(true) }) } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") // Pass false to the presentationCompletion indicating that presenting the alert controller failed. presentationCompletion(false) } } /// It presents a buttonless alert controller with an activity indicator in it. The indicator's color and size can be optionally customized. /// /// **Implementation Example:** /// ``` /// GTAlertCollection.shared.presentActivityAlert(withTitle: "Please wait", /// message: "You are being connected to your account...", /// activityIndicatorColor: .blue, /// showLargeIndicator: false) { (success) in /// if success { /// // The alert controller was presented successfully... /// } /// } /// ``` /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - activityIndicatorColor: The color of the activity indicator. By default, the color is set to *black*. /// - showLargeIndicator: Pass `true` when you want to use the large indicator style, `false` when you want to display the small one. Default value is `false`. /// - presentationCompletion: Called after the alert controller has been presented or when the `hostViewController` is `nil`, and indicates whether the alert controller was presented successfully or not. /// - success: When `true` the alert controller has been successfully presented to the host view controller, otherwise it's `false`. func presentActivityAlert(withTitle title: String?, message: String?, activityIndicatorColor: UIColor = UIColor.black, showLargeIndicator: Bool = false, presentationCompletion: @escaping (_ success: Bool) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Operate on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. // If the alert message is not nil, then add additional spaces at the end, or if it's nil add just these spaces, so it's possible to make // room for the activity indicator. // If the large activity indicator is about to be shown, then add three spaces, otherwise two. self.alertController = UIAlertController(title: title, message: (message ?? "") + (showLargeIndicator ? "\n\n\n" : "\n\n"), preferredStyle: .alert) // Initialize the activity indicator as large or small according to the showLargeIndicator parameter value. self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: showLargeIndicator ? .whiteLarge : .gray) // Set the activity indicator color. self.activityIndicator.color = activityIndicatorColor // Start animating. self.activityIndicator.startAnimating() // Add it to the alert controller's view as a subview. self.alertController.view.addSubview(self.activityIndicator) // Specify the following constraints to make it appear properly. self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false self.activityIndicator.centerXAnchor.constraint(equalTo: self.alertController.view.centerXAnchor).isActive = true self.activityIndicator.bottomAnchor.constraint(equalTo: self.alertController.view.bottomAnchor, constant: -8.0).isActive = true self.alertController.view.layoutIfNeeded() // Present the alert controller to the host view controller. hostVC.present(self.alertController, animated: true, completion: { // Pass true to the presentationCompletion indicating that the alert controller was presented. presentationCompletion(true) }) } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") // Pass false to the presentationCompletion indicating that presenting the alert controller failed. presentationCompletion(false) } } /// It presents an alert controller that contains a text field, and two action buttons (Done & Cancel). Title and message are included too. The action button titles are modifiable. /// /// **Implementation Example:** /// /// ``` /// GTAlertCollection.shared.presentSingleTextFieldAlert(withTitle: "Editor", /// message: "Type something:", /// doneButtonTitle: "OK", /// cancelButtonTitle: "Cancel", /// configurationHandler: { (textField, didFinishConfiguration) in /// /// if let textField = textField { /// // Configure the textfield properties. /// textField.delegate = self /// textField.placeholder = "Write here" /// // ... more configuration ... /// /// // Always call the following to let the alert controller appear. /// didFinishConfiguration() /// } /// /// }) { (textField) in /// if let textField = textField { /// // Do something with the textfield's text. /// } /// } /// ``` /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - doneButtonTitle: The Done button title. Default value is "Done". /// - cancelButtonTitle: The Cancel button title. Default value is "Cancel". /// - configurationHandler: A closure where you can configure the text field's properties before the alert is presented. The first parameter of the closure is the textfield itself, the second parameter it's a closure that must be called manually when you finish configuring the textfield, so it's possible for the alert to be presented. /// - completionHandler: Called when the Done button is tapped. It contains the textfield as a parameter. /// - didFinishConfiguration: Calling this closure from your code is **mandatory**. You do that after having configured the text field. If you don't make any configuration, call it directly in the `configurationHandler` closure. /// - textField: The single text field of the alert. Be careful with it and always unwrap it before using it, as it can be `nil`. /// - editedTextField: The single text field of the alert as returned when the Done button gets tapped. Always unwrap it before using it as it might be `nil`. func presentSingleTextFieldAlert(withTitle title: String?, message: String?, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", configurationHandler: @escaping (_ textField: UITextField?, _ didFinishConfiguration: () -> Void) -> Void, completionHandler: @escaping (_ editedTextField: UITextField?) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Work on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add a textfield to the alert controller. self.alertController.addTextField(configurationHandler: { (textField) in }) // Add the two actions to the alert controller (Done & Cancel). self.alertController.addAction(UIAlertAction(title: doneButtonTitle, style: .default, handler: { (action) in if let textFields = self.alertController.textFields { if textFields.count > 0 { // When the Done button is tapped, return the first textfield in the textfields collection. completionHandler(textFields[0]) } else { completionHandler(nil) } } else { completionHandler(nil) } })) self.alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { (action) in completionHandler(nil) })) // After having added the textfield and the action buttons to the alert controller, // call the configurationHandler closure and pass the first textfield and the didFinishConfiguration closure. // When that one gets called, the alert will be presented. if let textFields = self.alertController.textFields { if textFields.count > 0 { configurationHandler(textFields[0], { DispatchQueue.main.async { [unowned self] in hostVC.present(self.alertController, animated: true, completion: nil) } }) } else { configurationHandler(nil, {}) } } else { configurationHandler(nil, {}) } } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") configurationHandler(nil, {}) } } /// It presents an alert controller with variable number of text fields, as well as a Done and a Cancel action button. Titles of both are modifiable. Alert title and message included too. /// /// **Implementation Example:** /// /// ``` /// GTAlertCollection.shared.presentMultipleTextFieldsAlert(withTitle: "Input Data", /// message: "Lots of stuff to type here...", /// doneButtonTitle: "OK", /// cancelButtonTitle: "Cancel", /// numberOfTextFields: 5, /// configurationHandler: { (textFields, didFinishConfiguration) in /// if let textFields = textFields { /// let placeholders = ["First name", "Last name", "Nickname", "Email", "Password"] /// for i in 0..<textFields.count { /// textFields[i].placeholder = placeholders[i] /// } /// /// textFields.last?.isSecureTextEntry = true /// /// // ... more configuration ... /// /// didFinishConfiguration() /// } /// }) { (textFields) in /// if let textFields = textFields { /// // Do something with the textfields. /// } /// } /// ``` /// /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - doneButtonTitle: The Done button title. Default value is "Done". /// - cancelButtonTitle: The Cancel button title. Default value is "Cancel". /// - numberOfTextFields: The number of textfields you want to display on the alert. /// - configurationHandler: A closure where you can configure the properties of all textfields before the alert is presented. The first parameter of the closure is the collection of the textfields in the alert, the second parameter it's a closure that must be called manually when you finish configuring the textfields, so it's possible for the alert to be presented. /// - completionHandler: Called when the Done button is tapped. It contains the collection of textfields as a parameter. /// - didFinishConfiguration: Calling this closure from your code is **mandatory**. You do that after having configured the textfields. If you don't make any configuration, call it directly in the `configurationHandler` closure. /// - textFields: The collection of the text fields in the alert. Be careful with it and always unwrap it before using it, as it can be `nil`. /// - editedTextFields: The collection of the text fields in the alert as they're at the moment the Done button gets tapped. Always unwrap it before using it as it might be `nil`. func presentMultipleTextFieldsAlert(withTitle title: String?, message: String?, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", numberOfTextFields: Int, configurationHandler: @escaping (_ textFields: [UITextField]?, _ didFinishConfiguration: () -> Void) -> Void, completionHandler: @escaping (_ editedTextFields: [UITextField]?) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Work on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add the desired number of textfields to the alert controller. for _ in 0..<numberOfTextFields { self.alertController.addTextField(configurationHandler: { (textField) in }) } // Add the two actions to the alert controller (Done & Cancel). self.alertController.addAction(UIAlertAction(title: doneButtonTitle, style: .default, handler: { (action) in if let textFields = self.alertController.textFields { if textFields.count > 0 { // When the Done button is tapped, return the textfields collection. completionHandler(textFields) } else { completionHandler(nil) } } else { completionHandler(nil) } })) self.alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { (action) in })) // After having added the textfield and the action buttons to the alert controller, // call the configurationHandler closure and pass the textfields collection and the didFinishConfiguration closure. // When that one gets called, the alert will be presented. if let textFields = self.alertController.textFields { if textFields.count > 0 { configurationHandler(textFields, { DispatchQueue.main.async { [unowned self] in hostVC.present(self.alertController, animated: true, completion: nil) } }) } else { configurationHandler(nil, {}) } } else { configurationHandler(nil, {}) } } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") configurationHandler(nil, {}) } } /// It presents a buttonless alert controller with a progress bar, and optionally a label indicating the progress percentage or the progress steps made out of all steps at any given moment. /// /// The default configuration of the progress view and the label taking place in this method is good enough for most cases. /// However, if you want to set or modify additional properties on any of those two controls, you can use the class properties `progressBar` and `label` respectively. /// /// **Implementation Example:** /// /// ``` /// // Step 1: In your class declare the following property: /// var updateHandler: ((_ currentItem: Int, _ totalItems: Int) -> Void)! /// /// // Step 2: Implement the alert presentation somewhere in a method: /// GTAlertCollection.shared.presentProgressBarAlert(withTitle: "Upload", message: "Your files are being uploaded...", progressTintColor: .red, trackTintColor: .lightGray, showPercentage: true, showStepsCount: false, updateHandler: { (updateHandler) in /// /// self.updateHandler = updateHandler /// /// }) { (success) in /// if success { /// // doRealWork() is a method that makes the actual work and updates the progress as well. /// self.doRealWork() /// } /// } /// /// // Step 3: In the doRealWork() method: /// func doRealWork() { /// // Implement the method's logic. /// /// // When the time comes to update the progress: /// if let updateHandler = self.updateHandler { /// // currentStep and totalSteps represent the progress steps. /// updateHandler(currentStep, totalSteps) /// } /// } /// /// ``` /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - progressTintColor: The progress tint color. /// - trackTintColor: The track tint color. /// - showPercentage: Make it `true` when you want the progress to be displayed as a percentage right below the progress bar. Make it `false` to show the items count, or disable the label appearance. /// - showStepsCount: Make it `true` to show the steps that have been made at any given moment, or `false` when you want to either show the progress as a percentage, or totally disable the label. /// - updateHandler: Use that closure to update the progress. /// - currentStep: The current step represented by the progress bar among all steps. /// - totalSteps: The total number of steps until the progress reaches at 100%. /// - presentationCompletion: Called after the alert controller has been presented or when the `hostViewController` is `nil`, and indicates whether the alert controller was presented successfully or not. /// - success: When `true` the alert controller has been successfully presented to the host view controller, otherwise it's `false`. func presentProgressBarAlert(withTitle title: String?, message: String?, progressTintColor: UIColor, trackTintColor: UIColor, showPercentage: Bool, showStepsCount: Bool, updateHandler: @escaping (_ updateHandler: @escaping (_ currentStep: Int, _ totalSteps: Int) -> Void) -> Void, presentationCompletion: @escaping (_ success: Bool) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Operate on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. self.alertController = UIAlertController(title: title, message: (message ?? "") + "\n\n", preferredStyle: .alert) // Add more space if the progress percentage or steps count should be displayed. if showPercentage || showStepsCount { self.alertController.message! += "\n" } // Initialize the progress bar. if self.progressBar != nil { self.progressBar = nil } self.progressBar = UIProgressView() // Set its color. self.progressBar.progressTintColor = progressTintColor self.progressBar.trackTintColor = trackTintColor // Set the initial progress. self.progressBar.progress = 0.0 // Add it to the alert controller's view as a subview. self.alertController.view.addSubview(self.progressBar) // Specify the following constraints to make it appear properly. self.progressBar.translatesAutoresizingMaskIntoConstraints = false self.progressBar.leftAnchor.constraint(equalTo: self.alertController.view.leftAnchor, constant: 16.0).isActive = true self.progressBar.rightAnchor.constraint(equalTo: self.alertController.view.rightAnchor, constant: -16.0).isActive = true if showPercentage || showStepsCount { self.progressBar.bottomAnchor.constraint(equalTo: self.alertController.view.bottomAnchor, constant: -28.0).isActive = true } else { self.progressBar.bottomAnchor.constraint(equalTo: self.alertController.view.bottomAnchor, constant: -8.0).isActive = true } // Uncomment the following to change the height of the progress bar. // self.progressBar.heightAnchor.constraint(equalToConstant: 5.0).isActive = true // Create a label right below the progress view if any text status should be displayed. if showPercentage || showStepsCount { if self.label != nil { self.label = nil } self.label = UILabel() self.label.font = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize) self.label.textColor = UIColor.black self.label.textAlignment = .center if showPercentage { self.label.text = "\(self.progressBar.progress * 100.0)%" } else { self.label.text = "0 / 0" } self.alertController.view.addSubview(self.label) self.label.translatesAutoresizingMaskIntoConstraints = false self.label.centerXAnchor.constraint(equalTo: self.alertController.view.centerXAnchor).isActive = true self.label.topAnchor.constraint(equalTo: self.progressBar.bottomAnchor, constant: 8.0).isActive = true self.label.widthAnchor.constraint(equalToConstant: 180.0).isActive = true self.label.heightAnchor.constraint(equalToConstant: 12.0).isActive = true } self.alertController.view.layoutIfNeeded() // Present the alert controller to the host view controller. hostVC.present(self.alertController, animated: true, completion: { // Call the presentation completion handler passing true to indicate that the alert was presented. presentationCompletion(true) // Implement the updateHandler closure. // In it, update the progress of the progress bar, and the label if any text output should be displayed. updateHandler({ currentStep, totalSteps in DispatchQueue.main.async { [unowned self] in self.progressBar.setProgress(Float(currentStep)/Float(totalSteps), animated: true) if showPercentage { self.label.text = "\(Int(self.progressBar.progress * 100.0))%" } else if showStepsCount { self.label.text = "\(currentStep) / \(totalSteps)" } } }) }) } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") presentationCompletion(false) } } /// It presents an alert controller that contains an image view. It also displays action buttons, and the default title and message of the alert. /// /// To access the image view and set or modify additional properties, use the `imageView` class property. /// /// **Implementation example:** /// /// ``` /// // Specify your image: /// // let image = ... /// /// // Present the alert. /// GTAlertCollection.shared.presentImageViewAlert(withTitle: "Your Avatar", message: "What do you want to do with it?", buttonTitles: ["Change it", "Remove it", "Cancel"], cancelButtonIndex: 2, destructiveButtonIndices: [1], image: image) { (actionIndex) in /// // Handle the actionIndex value... /// } /// /// ``` /// /// - Parameters: /// - title: The optional title of the alert. /// - message: The optional message of the alert. /// - buttonTitles: The array with the action button titles. Give the titles in the order you want them to appear. /// - cancelButtonIndex: If there's a *Cancel-styled* button you want to exist among buttons, then here's the place where you specify it's **position** in the `buttonTitles` array. Pass `nil` if there's no Cancel-styled button. /// - destructiveButtonIndices: An array with the **position** of one or more *destructive* buttons in the collection of buttons. Pass `nil` if you have no destructive buttons to show. /// - image: The image to be displayed in the image view. /// - actionHandler: Use this block to determine which action button was tapped by the user. The `actionIndex` parameter provides you with that information. /// - actionIndex: The index of the tapped action. func presentImageViewAlert(withTitle title: String?, message: String?, buttonTitles: [String], cancelButtonIndex: Int?, destructiveButtonIndices: [Int]?, image: UIImage, actionHandler: @escaping (_ actionIndex: Int) -> Void) { // Check if the host view controller has been set. if let hostVC = hostViewController { // Operate on the main thread. DispatchQueue.main.async { [unowned self] in // Make sure that the alertController is nil before initializing it. self.cleanUpAlertController() // Initialize the alert controller. self.alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add a few empty lines to make room for the imageview. var updatedMessage = self.alertController.message ?? "" for _ in 0..<10 { updatedMessage += "\n" } self.alertController.message = updatedMessage // Create the action buttons. let actions = self.createAlertActions(usingTitles: buttonTitles, cancelButtonIndex: cancelButtonIndex, destructiveButtonIndices: destructiveButtonIndices, actionHandler: actionHandler) for action in actions { self.alertController.addAction(action) } // Initialize the imageview and configure it. if let _ = self.imageView { self.imageView = nil } self.imageView = UIImageView() self.imageView.image = image self.imageView.contentMode = .scaleAspectFill self.imageView.layer.cornerRadius = 8.0 self.imageView.layer.masksToBounds = false self.imageView.clipsToBounds = true // Add it to the alert controller's view. self.alertController.view.addSubview(self.imageView) // Specify its constraints. self.imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView.centerXAnchor.constraint(equalTo: self.alertController.view.centerXAnchor).isActive = true self.imageView.bottomAnchor.constraint(equalTo: self.alertController.view.bottomAnchor, constant: -16.0 - (44.0 * CGFloat(buttonTitles.count))).isActive = true self.imageView.widthAnchor.constraint(equalToConstant: self.alertController.view.frame.size.width/3).isActive = true self.imageView.heightAnchor.constraint(equalToConstant: self.alertController.view.frame.size.width/3).isActive = true self.alertController.view.layoutIfNeeded() // Present the alert controller to the host view controller. hostVC.present(self.alertController, animated: true, completion: { }) } } else { // The host view controller is nil and the alert controller cannot be presented. NSLog("[GTAlertCollection]: No host view controller was specified") } } }
54.756158
373
0.598803
eba3338362b11e698c4f8faf502298faef47cf4c
333
// // BCTitleCell.swift // Backchat // // Created by Bradley Mackey on 24/12/2016. // Copyright © 2016 Bradley Mackey. All rights reserved. // import UIKit /// # BCTitleCell /// A cell used to display a single label for use in the `BCAboutController` final class BCTitleCell: UITableViewCell { static let id = "BCTitleCell" }
20.8125
76
0.711712
62fbd287732c61517b4fcf9a8243ee3460599506
13,375
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import PackageModel /// Create an initial template package. public final class InitPackage { /// The tool version to be used for new packages. public static let newPackageToolsVersion = ToolsVersion(version: "5.0.0") /// Represents a package type for the purposes of initialization. public enum PackageType: String, CustomStringConvertible { case empty = "empty" case library = "library" case executable = "executable" case systemModule = "system-module" public var description: String { return rawValue } } /// A block that will be called to report progress during package creation public var progressReporter: ((String) -> Void)? /// Where to create the new package let destinationPath: AbsolutePath /// The type of package to create. let packageType: PackageType /// The name of the package to create. let pkgname: String /// The name of the target to create. var moduleName: String /// The name of the type to create (within the package). var typeName: String { return moduleName } /// Create an instance that can create a package with given arguments. public init(name: String, destinationPath: AbsolutePath, packageType: PackageType) throws { self.packageType = packageType self.destinationPath = destinationPath self.pkgname = name self.moduleName = name.spm_mangledToC99ExtendedIdentifier() } /// Actually creates the new package at the destinationPath public func writePackageStructure() throws { progressReporter?("Creating \(packageType) package: \(pkgname)") // FIXME: We should form everything we want to write, then validate that // none of it exists, and then act. try writeManifestFile() try writeREADMEFile() try writeGitIgnore() try writeSources() try writeModuleMap() try writeTests() } private func writePackageFile(_ path: AbsolutePath, body: (OutputByteStream) -> Void) throws { progressReporter?("Creating \(path.relative(to: destinationPath))") try localFileSystem.writeFileContents(path, body: body) } private func writeManifestFile() throws { let manifest = destinationPath.appending(component: Manifest.filename) guard localFileSystem.exists(manifest) == false else { throw InitError.manifestAlreadyExists } try writePackageFile(manifest) { stream in stream <<< """ // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( """ var pkgParams = [String]() pkgParams.append(""" name: "\(pkgname)" """) if packageType == .library { pkgParams.append(""" products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "\(pkgname)", targets: ["\(pkgname)"]), ] """) } pkgParams.append(""" dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ] """) if packageType == .library || packageType == .executable { pkgParams.append(""" targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "\(pkgname)", dependencies: []), .testTarget( name: "\(pkgname)Tests", dependencies: ["\(pkgname)"]), ] """) } stream <<< pkgParams.joined(separator: ",\n") <<< "\n)\n" } // Create a tools version with current version but with patch set to zero. // We do this to avoid adding unnecessary constraints to patch versions, if // the package really needs it, they should add it manually. let version = InitPackage.newPackageToolsVersion.zeroedPatch // Write the current tools version. try writeToolsVersion( at: manifest.parentDirectory, version: version, fs: localFileSystem) } private func writeREADMEFile() throws { let readme = destinationPath.appending(component: "README.md") guard localFileSystem.exists(readme) == false else { return } try writePackageFile(readme) { stream in stream <<< """ # \(pkgname) A description of this package. """ } } private func writeGitIgnore() throws { let gitignore = destinationPath.appending(component: ".gitignore") guard localFileSystem.exists(gitignore) == false else { return } try writePackageFile(gitignore) { stream in stream <<< """ .DS_Store /.build /Packages /*.xcodeproj """ } } private func writeSources() throws { if packageType == .systemModule { return } let sources = destinationPath.appending(component: "Sources") guard localFileSystem.exists(sources) == false else { return } progressReporter?("Creating \(sources.relative(to: destinationPath))/") try makeDirectories(sources) if packageType == .empty { return } let moduleDir = sources.appending(component: "\(pkgname)") try makeDirectories(moduleDir) let sourceFileName = (packageType == .executable) ? "main.swift" : "\(typeName).swift" let sourceFile = moduleDir.appending(RelativePath(sourceFileName)) try writePackageFile(sourceFile) { stream in switch packageType { case .library: stream <<< """ struct \(typeName) { var text = "Hello, World!" } """ case .executable: stream <<< """ print("Hello, world!") """ case .systemModule, .empty: fatalError("invalid") } } } private func writeModuleMap() throws { if packageType != .systemModule { return } let modulemap = destinationPath.appending(component: "module.modulemap") guard localFileSystem.exists(modulemap) == false else { return } try writePackageFile(modulemap) { stream in stream <<< """ module \(moduleName) [system] { header "/usr/include/\(moduleName).h" link "\(moduleName)" export * } """ } } private func writeTests() throws { if packageType == .systemModule { return } let tests = destinationPath.appending(component: "Tests") guard localFileSystem.exists(tests) == false else { return } progressReporter?("Creating \(tests.relative(to: destinationPath))/") try makeDirectories(tests) switch packageType { case .systemModule, .empty: break case .library, .executable: try writeLinuxMain(testsPath: tests) try writeTestFileStubs(testsPath: tests) } } private func writeLinuxMain(testsPath: AbsolutePath) throws { try writePackageFile(testsPath.appending(component: "LinuxMain.swift")) { stream in stream <<< """ import XCTest import \(moduleName)Tests var tests = [XCTestCaseEntry]() tests += \(moduleName)Tests.allTests() XCTMain(tests) """ } } private func writeLibraryTestsFile(_ path: AbsolutePath) throws { try writePackageFile(path) { stream in stream <<< """ import XCTest @testable import \(moduleName) final class \(moduleName)Tests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(\(typeName)().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] } """ } } private func writeExecutableTestsFile(_ path: AbsolutePath) throws { try writePackageFile(path) { stream in stream <<< """ import XCTest import class Foundation.Bundle final class \(moduleName)Tests: XCTestCase { func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. // Some of the APIs that we use below are available in macOS 10.13 and above. guard #available(macOS 10.13, *) else { return } let fooBinary = productsDirectory.appendingPathComponent("\(pkgname)") let process = Process() process.executableURL = fooBinary let pipe = Pipe() process.standardOutput = pipe try process.run() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8) XCTAssertEqual(output, "Hello, world!\\n") } /// Returns path to the built products directory. var productsDirectory: URL { #if os(macOS) for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") { return bundle.bundleURL.deletingLastPathComponent() } fatalError("couldn't find the products directory") #else return Bundle.main.bundleURL #endif } static var allTests = [ ("testExample", testExample), ] } """ } } private func writeTestFileStubs(testsPath: AbsolutePath) throws { let testModule = testsPath.appending(RelativePath(pkgname + Target.testModuleNameSuffix)) progressReporter?("Creating \(testModule.relative(to: destinationPath))/") try makeDirectories(testModule) let testClassFile = testModule.appending(RelativePath("\(moduleName)Tests.swift")) switch packageType { case .systemModule, .empty: break case .library: try writeLibraryTestsFile(testClassFile) case .executable: try writeExecutableTestsFile(testClassFile) } try writePackageFile(testModule.appending(component: "XCTestManifests.swift")) { stream in stream <<< """ import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(\(moduleName)Tests.allTests), ] } #endif """ } } } // Private helpers private enum InitError: Swift.Error { case manifestAlreadyExists } extension InitError: CustomStringConvertible { var description: String { switch self { case .manifestAlreadyExists: return "a manifest file already exists in this directory" } } }
33.605528
138
0.533607
61ac5bf6b8c9f73e54b3b25652cfb23bf6557495
12,064
// // SelectAvatarVC.swift // TranslationEditor // // Created by Mikko Hilpinen on 21.2.2017. // Copyright © 2017 SIL. All rights reserved. // import UIKit // This view controller handles avatar selection and authorization class SelectAvatarVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, LiveQueryListener, StackDismissable { // TYPES ------------------- typealias QueryTarget = AvatarView // OUTLETS ------------------- @IBOutlet weak var avatarCollectionView: UICollectionView! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var loginButton: BasicButton! @IBOutlet weak var passwordView: KeyboardReactiveView! @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var topBar: TopBarUIView! @IBOutlet weak var avatarsStackView: StatefulStackView! // ATTRIBUTES --------------- private var queryManager: LiveQueryManager<QueryTarget>? private var avatarData = [(Avatar, AvatarInfo)]() private var selectedData: (Avatar, AvatarInfo)? private var usesSharedAccount = true // COMPUTED PROPERTIES ------- var shouldDismissBelow: Bool { return !usesSharedAccount } // LOAD ----------------------- override func viewDidLoad() { super.viewDidLoad() topBar.configure(hostVC: self, title: "Select User") avatarsStackView.register(avatarCollectionView, for: .data) avatarsStackView.setState(.loading) guard let projectId = Session.instance.projectId else { print("ERROR: No selected project -> No available avatar data") avatarsStackView.errorOccurred() return } guard let accountId = Session.instance.accountId else { print("ERROR: No account information available.") avatarsStackView.errorOccurred() return } // If logged in with a non-shared account, uses the only avatar for the project // Otherwises reads all avatar data and filters out the non-shared later do { if let project = try Project.get(projectId) { usesSharedAccount = project.sharedAccountId == accountId if usesSharedAccount { queryManager = AvatarView.instance.avatarQuery(projectId: projectId).liveQueryManager } else { queryManager = AvatarView.instance.avatarQuery(projectId: projectId, accountId: accountId).liveQueryManager } } } catch { print("ERROR: Failed to read associated database data. \(error)") } avatarCollectionView.delegate = self avatarCollectionView.dataSource = self queryManager?.addListener(AnyLiveQueryListener(self)) passwordView.configure(mainView: view, elements: [loginButton, errorLabel, passwordField]) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hidePasswordView() topBar.updateUserView() // If the project has not been chosen, doesn't configure anything if Session.instance.projectId != nil { // Sets up the top bar let title = "Select User" if let presentingViewController = presentingViewController { if let presentingViewController = presentingViewController as? SelectProjectVC { topBar.configure(hostVC: self, title: title, leftButtonText: presentingViewController.shouldDismissBelow ? "Log Out" : "Switch Project") { Session.instance.projectId = nil presentingViewController.dismissFromAbove() } } else { topBar.configure(hostVC: self, title: title, leftButtonText: "Back", leftButtonAction: { self.dismiss(animated: true, completion: nil) }) } } // If the avatar has already been chosen, skips this phase // (The avatar must be enabled, however) if let avatarId = Session.instance.avatarId { do { if let avatar = try Avatar.get(avatarId), !avatar.isDisabled { print("STATUS: Avatar already selected") proceed(animated: false) return } else { Session.instance.bookId = nil Session.instance.avatarId = nil } } catch { print("ERROR: Failed to read avatar data. \(error)") } } // Otherwise starts the queries queryManager?.start() passwordView.startKeyboardListening() } } override func viewDidDisappear(_ animated: Bool) { passwordView.endKeyboardListening() // Doen't need to continue with live queries while the view is not visible queryManager?.stop() } // ACTIONS ------------------- @IBAction func passwordFieldChanged(_ sender: Any) { // Enables or disables login button loginButton.isEnabled = passwordField.text.exists { !$0.isEmpty } || selectedData.exists { !$0.1.requiresPassword } } @IBAction func cancelPressed(_ sender: Any) { // Hide password area. Resets selection hidePasswordView() } @IBAction func loginPressed(_ sender: Any) { guard let (selectedAvatar, selectedInfo) = selectedData else { print("ERROR: No selected avatar") return } // Checks password, moves to next view guard (passwordField.text.exists { selectedInfo.authenticate(loggedAccountId: Session.instance.accountId, password: $0) }) else { errorLabel.isHidden = false return } Session.instance.avatarId = selectedAvatar.idString proceed() } // IMPLEMENTED METHODS ------- func rowsUpdated(rows: [Row<QueryTarget>]) { do { // If using a shared account, presents all viable options in the collection view if usesSharedAccount { avatarData = try rows.map { try $0.object() }.compactMap { avatar in if !avatar.isDisabled, let info = try avatar.info(), info.isShared { return (avatar, info) } else { return nil } } avatarsStackView.dataLoaded() avatarCollectionView.reloadData() } // Otherwise just finds the first applicable avatar and uses that else { if let avatar = try rows.first?.object() { // If the user's avatar was disabled for some reason, enables it if avatar.isDisabled { avatar.isDisabled = false try avatar.push() } print("STATUS: Proceeding with non-shared account avatar") Session.instance.avatarId = avatar.idString proceed() } else { do { if let accountId = Session.instance.accountId, let account = try AgricolaAccount.get(accountId) { avatarsStackView.dataLoaded() createAvatar(withName: account.username) } else { print("ERROR: No account data available") avatarsStackView.errorOccurred(title: "Can't create a new user", description: "Account data was not found") return } } catch { print("ERROR: Failed to read account data. \(error)") avatarsStackView.errorOccurred(title: "Can't create a new user", canContinueWithData: false) } } } } catch { print("ERROR: Failed to process avatar data. \(error)") avatarsStackView.errorOccurred() } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return avatarData.count + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AvatarCell.identifier, for: indexPath) as! AvatarCell // The last row is used for the avatar addition if indexPath.row == avatarData.count { cell.configure(avatarName: "New User", avatarImage: #imageLiteral(resourceName: "addIcon")) } else { let (avatar, info) = avatarData[indexPath.row] cell.configure(avatarName: avatar.name, avatarImage: info.image) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // Selects an avatar and displays the password view if selectedData == nil { // If the last cell was selected, displays a view for adding a new avatar if indexPath.row == avatarData.count { createAvatar() } else { selectedData = avatarData[indexPath.row] if selectedData!.1.requiresPassword { errorLabel.isHidden = true passwordView.isHidden = false } else { Session.instance.avatarId = selectedData!.0.idString proceed() } } } } func willDissmissBelow() { // Deselects the project Session.instance.projectId = nil } // OTHER METHODS -------- func proceed(animated: Bool = true) { // Presents the main menu let storyboard = UIStoryboard(name: "MainMenu", bundle: nil) guard let controller = storyboard.instantiateInitialViewController() else { print("ERROR: Failed to instantiate VC for the main menu") return } present(controller, animated: animated, completion: nil) } private func createAvatar(withName avatarName: String? = nil) { displayAlert(withIdentifier: "EditAvatar", storyBoardId: "MainMenu") { ($0 as! EditAvatarVC).configureForCreate(avatarName: avatarName) } } private func hidePasswordView() { // Hide password area. Resets selection passwordField.text = nil selectedData = nil passwordView.isHidden = true avatarCollectionView.selectItem(at: nil, animated: true, scrollPosition: .left) } }
33.418283
157
0.52379
1a7394a25d965944185e6edef110dbe1947f8805
4,521
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import Amplify import AWSRekognition import AWSTextract import AWSPolly import AWSTranslate import AWSComprehend class PredictionsErrorHelper { static func mapHttpResponseCode(statusCode: Int, serviceKey: String) -> PredictionsError? { switch statusCode { case 200 ..< 300: return nil case 404: return PredictionsError.httpStatus(statusCode, "Please check your request and try again") case 400: return PredictionsError.httpStatus(statusCode, """ There are number of reasons for receiving a 400 status code. Please check the service documentation for the specific service you are hitting. """) case 500: return PredictionsError.httpStatus(statusCode, """ The request processing has failed because of an unknown error, exception or failure. Please check aws-amplify github for known issues. """) case 503: return PredictionsError.httpStatus(statusCode, "The request has failed due to a temporary failure of the server.") default: return PredictionsError.httpStatus(statusCode, """ Status code unrecognized, please refer to the AWS Service error documentation. https://docs.aws.amazon.com/directoryservice/latest/devguide/CommonErrors.html """) } } // swiftlint:disable cyclomatic_complexity static func mapPredictionsServiceError(_ error: NSError) -> PredictionsError { let defaultError = PredictionsErrorHelper.getDefaultError(error) switch error.domain { case AWSServiceErrorDomain: let errorTypeOptional = AWSServiceErrorType.init(rawValue: error.code) guard let errorType = errorTypeOptional else { return defaultError } return AWSServiceErrorMessage.map(errorType) ?? defaultError case AWSRekognitionErrorDomain: guard let errorType = AWSRekognitionErrorType.init(rawValue: error.code) else { return defaultError } return AWSRekognitionErrorMessage.map(errorType) ?? defaultError case AWSPollyErrorDomain: guard let errorType = AWSPollyErrorType.init(rawValue: error.code) else { return defaultError } return AWSPollyErrorMessage.map(errorType) ?? defaultError case AWSTextractErrorDomain: guard let errorType = AWSTextractErrorType.init(rawValue: error.code) else { return defaultError } return AWSTextractErrorMessage.map(errorType) ?? defaultError case AWSComprehendErrorDomain: guard let errorType = AWSComprehendErrorType.init(rawValue: error.code) else { return defaultError } return AWSComprehendErrorMessage.map(errorType) ?? defaultError case AWSTranslateErrorDomain: guard let errorType = AWSTranslateErrorType.init(rawValue: error.code) else { return defaultError } return AWSTranslateErrorMessage.map(errorType) ?? defaultError default: return defaultError } } static func getDefaultError(_ error: NSError) -> PredictionsError { let errorMessage = """ Domain: [\(error.domain) Code: [\(error.code) LocalizedDescription: [\(error.localizedDescription) LocalizedFailureReason: [\(error.localizedFailureReason ?? "") LocalizedRecoverySuggestion: [\(error.localizedRecoverySuggestion ?? "") """ return PredictionsError.unknown(errorMessage, "") } }
43.471154
125
0.558505
09a9be8889a18c1fab5934b75be0e4e3e9f214f6
3,259
import UIKit import Firebase import FirebaseAuth import FirebaseDatabase class ForceUpdateController: UIViewController { private let logoView: CustomImageView = { let iv = CustomImageView() iv.contentMode = .scaleAspectFill iv.layer.zPosition = 10 iv.clipsToBounds = true iv.backgroundColor = UIColor(white: 0, alpha: 1) return iv }() private let updateLabel: UILabel = { let label = UILabel() label.textColor = UIColor.black label.layer.zPosition = 4 label.numberOfLines = 0 label.textAlignment = .center let attributedText = NSMutableAttributedString(string: "Please Update GroupRoots", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)]) label.attributedText = attributedText return label }() private let updateBackground: UIView = { let view = UIView() view.backgroundColor = UIColor(white: 1, alpha: 1) view.layer.zPosition = 3 view.isUserInteractionEnabled = false view.layer.cornerRadius = 10 return view }() private lazy var updateButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(sent_to_update), for: .touchUpInside) button.layer.zPosition = 4; button.layer.borderWidth = 1 button.layer.borderColor = UIColor.white.cgColor button.backgroundColor = UIColor.black button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.setTitle("Update Now", for: .normal) return button }() override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13.0, *) { overrideUserInterfaceStyle = .light } self.navigationController?.isNavigationBarHidden = true // logoView.heightAnchor.constraint(equalToConstant: 20).isActive = true logoView.layer.cornerRadius = 0 logoView.frame = CGRect(x: UIScreen.main.bounds.width/2-20, y: UIScreen.main.bounds.height/2-80, width: 40, height: 40) logoView.image = #imageLiteral(resourceName: "Small_White_Logo") self.view.insertSubview(logoView, at: 10) updateButton.frame = CGRect(x: UIScreen.main.bounds.width/2-70, y: UIScreen.main.bounds.height/2 + 25, width: 140, height: 50) updateButton.layer.cornerRadius = 18 self.view.insertSubview(updateButton, at: 4) updateLabel.frame = CGRect(x: 0, y: UIScreen.main.bounds.height/2-20, width: UIScreen.main.bounds.width, height: 20) self.view.insertSubview(updateLabel, at: 4) updateBackground.frame = CGRect(x: UIScreen.main.bounds.width/2-150, y: UIScreen.main.bounds.height/2-100, width: 300, height: 200) self.view.insertSubview(updateBackground, at: 3) view.backgroundColor = UIColor(white: 0.15, alpha: 1) } @objc func sent_to_update() { Database.database().fetch_link_to_app(completion: { (link_to_app) in guard let url = URL(string: link_to_app) else { return } UIApplication.shared.open(url) }) } }
39.26506
169
0.647131
e0934172c1c74f0b0df8f543c87a730ceccfc099
2,894
import XCTest @testable import PackStream class StructureTests: XCTestCase { func testEmptyStructure() throws { let value = Structure(signature: 42, items: []) let expected: [Byte] = [0xB0, 0x2A] let actual: [Byte] = try value.pack() XCTAssertEqual(expected, actual) let unpackedValue = try Structure.unpack(actual[0..<actual.count]) XCTAssertEqual(value, unpackedValue) } func testThreeSmallInts() throws { let value = Structure(signature: 42, items: [Int8(1), Int8(2), Int8(3)]) let expected: [Byte] = [0xB3, 0x2A, 0x01, 0x02, 0x03] let actual: [Byte] = try value.pack() XCTAssertEqual(expected, actual) let unpackedValue = try Structure.unpack(actual[0..<actual.count]) XCTAssertEqual(value, unpackedValue) } func testFourtySmallInts() throws { let items = Array(Int8(1)...Int8(40)) let value = Structure(signature: 42, items: items) let expected: [Byte] = [0xDC, 0x28, 0x2A, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28] let actual: [Byte] = try value.pack() XCTAssertEqual(expected, actual) let unpackedValue = try Structure.unpack(actual[0..<actual.count]) XCTAssertEqual(value, unpackedValue) } func testTheeHetrogenousTypes() throws { let items: [PackProtocol] = [ Int8(1), Double(2.0), "three" ] let value = Structure(signature: 42, items: items) let expected: [Byte] = [0xB3, 0x2A, 0x01, 0xC1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x74, 0x68, 0x72, 0x65, 0x65] let actual: [Byte] = try value.pack() XCTAssertEqual(expected, actual) let unpackedValue = try Structure.unpack(actual[0..<actual.count]) XCTAssertEqual(value, unpackedValue) } func testStructureOf256Ones() throws { let items = (0...255).map { _ in Int8(1) } let value = Structure(signature: 42, items: items) let expected: [Byte] = [0xDD, 0x01, 0x00, 0x2A] + ((0...255).map { _ in Byte(1) }) let actual: [Byte] = try value.pack() XCTAssertEqual(expected, actual) let unpackedValue = try Structure.unpack(actual[0..<actual.count]) XCTAssertEqual(value, unpackedValue) } static var allTests : [(String, (StructureTests) -> () throws -> Void)] { return [ ("testEmptyStructure", testEmptyStructure), ("testThreeSmallInts", testThreeSmallInts), ("testFourtySmallInts", testFourtySmallInts), ("testTheeHetrogenousTypes", testTheeHetrogenousTypes), ("testStructureOf256Ones", testStructureOf256Ones), ] } }
36.175
289
0.626814
0a20af553a9592c02ed3771439980e44be949088
1,257
// // APIRouter.swift // TripTracker // // Created by quangpc on 7/18/18. // Copyright © 2018 triptracker. All rights reserved. // import Foundation import Moya import SwiftyJSON import ObjectMapper enum ReportAPIRouter { // báo cáo web case reportPhishing(url: String) } enum APIConstant { static let baseURL = "https://app.visafe.vn/api/v1" // static let baseURL = "https://staging.visafe.vn/api/v1" } enum APIError: Error { case serverLogicError(message: String) case parseError } extension ReportAPIRouter: TargetType { var baseURL: URL { return URL(string: APIConstant.baseURL)! } var path: String { return "/report_phishing" } var method: Moya.Method { return .post } var parameters: [String: Any] { var pars = [String: Any]() switch self { case .reportPhishing(url: let url): pars["url"] = url } return pars } var task: Task { return .requestParameters(parameters: parameters, encoding: JSONEncoding.default) } var sampleData: Data { return "".data(using: .utf8)! } var headers: [String : String]? { var hea: [String: String] = [:] return hea } }
19.338462
89
0.608592
d6107039970cd6d157df8bbe23343f6b466c83a3
804
// // UIBarbuttonItemViewController.swift // actions // // Created by Manuel García-Estañ on 1/11/16. // Copyright © 2016 manuege. All rights reserved. // import UIKit import Actions class UIBarbuttonItemViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "Actions - UIBarButtonItem" let systemItem = UIBarButtonItem(barButtonSystemItem: .action) { [unowned self] in self.showAlert(message: "Did press \"Action\" item") } let titleItem = UIBarButtonItem(title: "Item") { [unowned self] (item: UIBarButtonItem) in self.showAlert(message: "Did press \(item)") } navigationItem.rightBarButtonItems = [systemItem, titleItem] } }
26.8
98
0.63806
fc681211f184699648c2e4620c937438d2b58372
2,281
import TSCBasic import TuistCore import TuistGraph import TuistSupport import XCTest @testable import TuistDependencies @testable import TuistDependenciesTesting @testable import TuistSupportTesting final class DependenciesControllerTests: TuistUnitTestCase { private var subject: DependenciesController! private var carthageInteractor: MockCarthageInteractor! private var cocoaPodsInteractor: MockCocoaPodsInteractor! private var swiftPackageManagerInteractor: MockSwiftPackageManagerInteractor! override func setUp() { super.setUp() carthageInteractor = MockCarthageInteractor() cocoaPodsInteractor = MockCocoaPodsInteractor() swiftPackageManagerInteractor = MockSwiftPackageManagerInteractor() subject = DependenciesController( carthageInteractor: carthageInteractor, cocoaPodsInteractor: cocoaPodsInteractor, swiftPackageManagerInteractor: swiftPackageManagerInteractor ) } override func tearDown() { subject = nil carthageInteractor = nil cocoaPodsInteractor = nil swiftPackageManagerInteractor = nil super.tearDown() } func test_fetch() throws { // Given let rootPath = try temporaryPath() let dependenciesDirectoryPath = rootPath .appending(component: Constants.tuistDirectoryName) .appending(component: Constants.DependenciesDirectory.name) let stubbedCarthageDependencies = CarthageDependencies( [ .github(path: "Moya", requirement: .exact("1.1.1")), .github(path: "RxSwift", requirement: .exact("2.0.0")), ], platforms: [.iOS], options: [.useXCFrameworks, .noUseBinaries] ) let stubbedDependencies = Dependencies(carthage: stubbedCarthageDependencies) // When try subject.fetch(at: rootPath, dependencies: stubbedDependencies) // Then XCTAssertTrue(carthageInteractor.invokedFetch) XCTAssertEqual(carthageInteractor.invokedFetchParameters?.dependenciesDirectory, dependenciesDirectoryPath) XCTAssertEqual(carthageInteractor.invokedFetchParameters?.dependencies, stubbedCarthageDependencies) } }
34.044776
115
0.707584
ab2456c2cafc417f115dc0bf6b7c73135ef2822f
792
// // File.swift // SongProcessor // // Created by Yaron Karasik on 5/19/18. // Copyright © 2018 AudioKit. All rights reserved. // import Foundation enum LoopType: Int { case bass case drum case guitar case lead case mix static var count: Int { return LoopType.mix.rawValue + 1} var name: String { switch self { case .bass: return "Bass" case .drum: return "Drum" case .guitar: return "Guitar" case .lead: return "Lead" case .mix: return "Mix" } } var filename: String { switch self { case .bass: return "bass" case .drum: return "drum" case .guitar: return "guitar" case .lead: return "lead" case .mix: return "mix" } } }
19.8
61
0.551768
3a3106a64991fc282d14bdb335147816cdbce7af
1,392
// // TronTransactionAPI.swift // TRXWallet // // Created by Maynard on 2018/9/3. // Copyright © 2018年 newborntown. All rights reserved. // import Foundation import Moya enum TronTransactionAPI { case getTransactions(address: String, limit: String, start: String) } extension TronTransactionAPI: TargetType { var baseURL: URL { return URL(string: Constants.tronTransactionAPI)! } var path: String { switch self { case .getTransactions: return "/api/transaction" } } var method: Moya.Method { return .get } var task: Task { switch self { case .getTransactions: return .requestParameters(parameters: self.parameters ?? [:], encoding: URLEncoding()) } } var parameters: [String: Any]? { var dic:[String: Any] = [:] switch self { case .getTransactions(let address, let limit, let start): dic["address"] = address dic["limit"] = limit dic["start"] = start } return dic } var sampleData: Data { return Data() } var headers: [String: String]? { return [ "Content-type": "application/json", "client": Bundle.main.bundleIdentifier ?? "", "client-build": Bundle.main.buildNumber ?? "", ] } }
22.819672
98
0.55819
5098fad9ffddb9cf858df4f7c4a85f321a11d3d8
1,044
// Copyright 2017 Esri. // // 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 ArcGIS extension AGSLocationDisplayAutoPanMode: CustomStringConvertible { public var description: String { switch self { case .off: return "Off" case .recenter: return "Recenter" case .navigation: return "Navigation" case .compassNavigation: return "Compass Navigation" @unknown default: fatalError("Unsupported enum case.") } } }
31.636364
75
0.671456
1467e9bf05a09c5e8644e3942393e242d7564163
899
// // ViewController.swift // IOS8SwiftCoreImageTutorial // // Created by Arthur Knopper on 01/04/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "dog.jpg") let originalImage = CIImage(image: image) var filter = CIFilter(name: "CIPhotoEffectMono") filter.setDefaults() filter.setValue(originalImage, forKey: kCIInputImageKey) var outputImage = filter.outputImage var newImage = UIImage(CIImage: outputImage) imageView.image = newImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
24.297297
64
0.655172
e86633946939a992dff9552a950cc6facdf4784a
849
// // Post.swift // ModelingAndBinding // // Created by B_Litwin on 6/4/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import IGListKit final class Post: ListDiffable { // 1 let username: String let timestamp: String let imageURL: URL let likes: Int let comments: [Comment] // 2 init(username: String, timestamp: String, imageURL: URL, likes: Int, comments: [Comment]) { self.username = username self.timestamp = timestamp self.imageURL = imageURL self.likes = likes self.comments = comments } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return (username + timestamp) as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } }
21.769231
95
0.618375
5627ad2f98ffeee48954cffc2201fcd30ce20f02
498
// // TutorialFilterView.swift // SwiftUI_Mask_Sample // // Created by Tsuruta, Hiromu | ECID on 2021/09/21. // import SwiftUI // MARK: - View struct TutorialFilterView: View { var body: some View { Color.black .opacity(0.7) .mask(TutorialHoleView()) .edgesIgnoringSafeArea(.all) } } // MARK: - PreviewProvider struct TutorialFilterView_Previews: PreviewProvider { static var previews: some View { TutorialFilterView() } }
18.444444
53
0.63253
f7067eb95bc4dd2d896a1615b69b7e15ebb046f5
349
// // ViewController.swift // Revels // // Created by Naman Jain on 19/12/18. // Copyright © 2018 Naman Jain. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
16.619048
80
0.661891
14a069788e640d824d587aeaba10b6b3c1483fd4
1,241
// swift-tools-version:5.4 import PackageDescription let package = Package( name: "DepsValidator", platforms: [.macOS(.v10_13)], products: [ .executable(name: "depsvalidator", targets: ["DepsValidator"]), .library(name: "DepsValidatorLibrary", targets: ["DepsValidatorLibrary"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", from: "0.4.3"), .package(url: "https://github.com/jpsim/Yams", from: "4.0.6"), ], targets: [ .executableTarget( name: "DepsValidator", dependencies: [ .target(name: "DepsValidatorLibrary"), ]), .target( name: "DepsValidatorLibrary", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), .product(name: "Yams", package: "Yams"), ]), .testTarget( name: "DepsValidatorTests", dependencies: [ "DepsValidatorLibrary", ], resources: [ .copy("Example Manifests/Package.swift.example"), .copy("Example Manifests/Example.podspec"), ]), ] )
32.657895
87
0.535052
9cfdd92862a214a36a3f591615a26d4444f31f1c
2,530
extension PathExplorerXML: PathExplorer { public var string: String? { element.string.trimmingCharacters(in: .whitespacesAndNewlines) == "" ? nil : element.string } public var bool: Bool? { element.bool } public var int: Int? { element.int } public var real: Double? { element.double } public var stringValue: String { element.string.trimmingCharacters(in: .whitespacesAndNewlines) } public var description: String { element.xml } public var format: DataFormat { .xml } // MARK: Get public func get(_ pathElements: PathElement...) throws -> Self { try get(pathElements) } public func get(_ pathElements: Path) throws -> Self { var currentPathExplorer = self try pathElements.forEach { currentPathExplorer = try currentPathExplorer.get(pathElement: $0) } return currentPathExplorer } public func get<T>(_ path: Path, as type: KeyType<T>) throws -> T where T: KeyAllowedType { let explorer = try get(path) guard let value = explorer.element.value else { throw PathExplorerError.underlyingError("Program error. No value at '\(path.description)' although the path is valid.") } return try T(value: value) } public func get<T>(_ pathElements: PathElement..., as type: KeyType<T>) throws -> T where T: KeyAllowedType { try get(pathElements, as: type) } // MARK: Set public mutating func set<Type>(_ path: [PathElement], to newValue: Any, as type: KeyType<Type>) throws where Type: KeyAllowedType { try set(path, to: newValue) } public mutating func set(_ pathElements: PathElement..., to newValue: Any) throws { try set(pathElements, to: newValue) } public mutating func set<Type>(_ pathElements: PathElement..., to newValue: Any, as type: KeyType<Type>) throws where Type: KeyAllowedType { try set(pathElements, to: newValue) } // -- Set key name public mutating func set(_ pathElements: PathElement..., keyNameTo newKeyName: String) throws { try set(pathElements, keyNameTo: newKeyName) } // MARK: Add public mutating func add<Type>(_ newValue: Any, at path: Path, as type: KeyType<Type>) throws where Type: KeyAllowedType { try add(newValue, at: path) } public mutating func add<Type>(_ newValue: Any, at pathElements: PathElement..., as type: KeyType<Type>) throws where Type: KeyAllowedType { try add(newValue, at: pathElements) } }
35.138889
144
0.661265
797620be25de4cecff676c76a3a2cd6f106903da
988
import UIKit public protocol TextLineable { @discardableResult func lines(_ number: Int) -> Self @discardableResult func multiline() -> Self } protocol _TextLineable: TextLineable { func _setNumbelOfLines(_ v: Int) } @available(iOS 13.0, *) extension TextLineable { @discardableResult public func lines(_ number: Int) -> Self { guard let s = self as? _TextLineable else { return self } s._setNumbelOfLines(number) return self } @discardableResult public func multiline() -> Self { guard let s = self as? _TextLineable else { return self } s._setNumbelOfLines(0) return self } } // for iOS lower than 13 extension _TextLineable { @discardableResult public func lines(_ number: Int) -> Self { _setNumbelOfLines(number) return self } @discardableResult public func multiline() -> Self { _setNumbelOfLines(0) return self } }
21.478261
65
0.632591
f55e991b9c2900c66439a4f6dcdda626c61ac26d
966
// // TestView.swift // SwiftUIOAuth // // Created by Chee Ket Yung on 27/03/2021. // import SwiftUI struct TabbedView : View { @State private var selectedTab : Int = 0 var body : some View { tabbedViews() .onAppear{ // always reset back to zero self.selectedTab = 0 } } } extension TabbedView { func tabbedViews() -> some View { TabView(selection: $selectedTab ){ HomeView() .tabItem { Label("Home", systemImage: "house") } .tag(0) SettingsView() .tabItem { Label("Settings", systemImage: "gear") } .tag(1) BlogPostsView() .tabItem { Label("Tutorials", systemImage: "book") } .tag(3) } } }
18.226415
55
0.42029
deed8915e8a667f4a29733963db924238f363524
64,512
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore extension Route53Resolver { public struct AssociateResolverEndpointIpAddressRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "IpAddress", required: true, type: .structure), AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// Either the IPv4 address that you want to add to a resolver endpoint or a subnet ID. If you specify a subnet ID, Resolver chooses an IP address for you from the available IPs in the specified subnet. public let ipAddress: IpAddressUpdate /// The ID of the resolver endpoint that you want to associate IP addresses with. public let resolverEndpointId: String public init(ipAddress: IpAddressUpdate, resolverEndpointId: String) { self.ipAddress = ipAddress self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case ipAddress = "IpAddress" case resolverEndpointId = "ResolverEndpointId" } } public struct AssociateResolverEndpointIpAddressResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// The response to an AssociateResolverEndpointIpAddress request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct AssociateResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ResolverRuleId", required: true, type: .string), AWSShapeMember(label: "VPCId", required: true, type: .string) ] /// A name for the association that you're creating between a resolver rule and a VPC. public let name: String? /// The ID of the resolver rule that you want to associate with the VPC. To list the existing resolver rules, use ListResolverRules. public let resolverRuleId: String /// The ID of the VPC that you want to associate the resolver rule with. public let vPCId: String public init(name: String? = nil, resolverRuleId: String, vPCId: String) { self.name = name self.resolverRuleId = resolverRuleId self.vPCId = vPCId } private enum CodingKeys: String, CodingKey { case name = "Name" case resolverRuleId = "ResolverRuleId" case vPCId = "VPCId" } } public struct AssociateResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleAssociation", required: false, type: .structure) ] /// Information about the AssociateResolverRule request, including the status of the request. public let resolverRuleAssociation: ResolverRuleAssociation? public init(resolverRuleAssociation: ResolverRuleAssociation? = nil) { self.resolverRuleAssociation = resolverRuleAssociation } private enum CodingKeys: String, CodingKey { case resolverRuleAssociation = "ResolverRuleAssociation" } } public struct CreateResolverEndpointRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "CreatorRequestId", required: true, type: .string), AWSShapeMember(label: "Direction", required: true, type: .enum), AWSShapeMember(label: "IpAddresses", required: true, type: .list), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "SecurityGroupIds", required: true, type: .list), AWSShapeMember(label: "Tags", required: false, type: .list) ] /// A unique string that identifies the request and that allows failed requests to be retried without the risk of executing the operation twice. CreatorRequestId can be any unique string, for example, a date/time stamp. public let creatorRequestId: String /// Specify the applicable value: INBOUND: Resolver forwards DNS queries to the DNS service for a VPC from your network or another VPC OUTBOUND: Resolver forwards DNS queries from the DNS service for a VPC to your network or another VPC public let direction: ResolverEndpointDirection /// The subnets and IP addresses in your VPC that you want DNS queries to pass through on the way from your VPCs to your network (for outbound endpoints) or on the way from your network to your VPCs (for inbound resolver endpoints). public let ipAddresses: [IpAddressRequest] /// A friendly name that lets you easily find a configuration in the Resolver dashboard in the Route 53 console. public let name: String? /// The ID of one or more security groups that you want to use to control access to this VPC. The security group that you specify must include one or more inbound rules (for inbound resolver endpoints) or outbound rules (for outbound resolver endpoints). public let securityGroupIds: [String] /// A list of the tag keys and values that you want to associate with the endpoint. public let tags: [Tag]? public init(creatorRequestId: String, direction: ResolverEndpointDirection, ipAddresses: [IpAddressRequest], name: String? = nil, securityGroupIds: [String], tags: [Tag]? = nil) { self.creatorRequestId = creatorRequestId self.direction = direction self.ipAddresses = ipAddresses self.name = name self.securityGroupIds = securityGroupIds self.tags = tags } private enum CodingKeys: String, CodingKey { case creatorRequestId = "CreatorRequestId" case direction = "Direction" case ipAddresses = "IpAddresses" case name = "Name" case securityGroupIds = "SecurityGroupIds" case tags = "Tags" } } public struct CreateResolverEndpointResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// Information about the CreateResolverEndpoint request, including the status of the request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct CreateResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "CreatorRequestId", required: true, type: .string), AWSShapeMember(label: "DomainName", required: true, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ResolverEndpointId", required: false, type: .string), AWSShapeMember(label: "RuleType", required: true, type: .enum), AWSShapeMember(label: "Tags", required: false, type: .list), AWSShapeMember(label: "TargetIps", required: false, type: .list) ] /// A unique string that identifies the request and that allows failed requests to be retried without the risk of executing the operation twice. CreatorRequestId can be any unique string, for example, a date/time stamp. public let creatorRequestId: String /// DNS queries for this domain name are forwarded to the IP addresses that you specify in TargetIps. If a query matches multiple resolver rules (example.com and www.example.com), outbound DNS queries are routed using the resolver rule that contains the most specific domain name (www.example.com). public let domainName: String /// A friendly name that lets you easily find a rule in the Resolver dashboard in the Route 53 console. public let name: String? /// The ID of the outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that you specify in TargetIps. public let resolverEndpointId: String? /// Specify FORWARD. Other resolver rule types aren't supported. public let ruleType: RuleTypeOption /// A list of the tag keys and values that you want to associate with the endpoint. public let tags: [Tag]? /// The IPs that you want Resolver to forward DNS queries to. You can specify only IPv4 addresses. Separate IP addresses with a comma. public let targetIps: [TargetAddress]? public init(creatorRequestId: String, domainName: String, name: String? = nil, resolverEndpointId: String? = nil, ruleType: RuleTypeOption, tags: [Tag]? = nil, targetIps: [TargetAddress]? = nil) { self.creatorRequestId = creatorRequestId self.domainName = domainName self.name = name self.resolverEndpointId = resolverEndpointId self.ruleType = ruleType self.tags = tags self.targetIps = targetIps } private enum CodingKeys: String, CodingKey { case creatorRequestId = "CreatorRequestId" case domainName = "DomainName" case name = "Name" case resolverEndpointId = "ResolverEndpointId" case ruleType = "RuleType" case tags = "Tags" case targetIps = "TargetIps" } } public struct CreateResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRule", required: false, type: .structure) ] /// Information about the CreateResolverRule request, including the status of the request. public let resolverRule: ResolverRule? public init(resolverRule: ResolverRule? = nil) { self.resolverRule = resolverRule } private enum CodingKeys: String, CodingKey { case resolverRule = "ResolverRule" } } public struct DeleteResolverEndpointRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// The ID of the resolver endpoint that you want to delete. public let resolverEndpointId: String public init(resolverEndpointId: String) { self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case resolverEndpointId = "ResolverEndpointId" } } public struct DeleteResolverEndpointResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// Information about the DeleteResolverEndpoint request, including the status of the request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct DeleteResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleId", required: true, type: .string) ] /// The ID of the resolver rule that you want to delete. public let resolverRuleId: String public init(resolverRuleId: String) { self.resolverRuleId = resolverRuleId } private enum CodingKeys: String, CodingKey { case resolverRuleId = "ResolverRuleId" } } public struct DeleteResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRule", required: false, type: .structure) ] /// Information about the DeleteResolverRule request, including the status of the request. public let resolverRule: ResolverRule? public init(resolverRule: ResolverRule? = nil) { self.resolverRule = resolverRule } private enum CodingKeys: String, CodingKey { case resolverRule = "ResolverRule" } } public struct DisassociateResolverEndpointIpAddressRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "IpAddress", required: true, type: .structure), AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// The IPv4 address that you want to remove from a resolver endpoint. public let ipAddress: IpAddressUpdate /// The ID of the resolver endpoint that you want to disassociate an IP address from. public let resolverEndpointId: String public init(ipAddress: IpAddressUpdate, resolverEndpointId: String) { self.ipAddress = ipAddress self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case ipAddress = "IpAddress" case resolverEndpointId = "ResolverEndpointId" } } public struct DisassociateResolverEndpointIpAddressResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// The response to an DisassociateResolverEndpointIpAddress request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct DisassociateResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleId", required: true, type: .string), AWSShapeMember(label: "VPCId", required: true, type: .string) ] /// The ID of the resolver rule that you want to disassociate from the specified VPC. public let resolverRuleId: String /// The ID of the VPC that you want to disassociate the resolver rule from. public let vPCId: String public init(resolverRuleId: String, vPCId: String) { self.resolverRuleId = resolverRuleId self.vPCId = vPCId } private enum CodingKeys: String, CodingKey { case resolverRuleId = "ResolverRuleId" case vPCId = "VPCId" } } public struct DisassociateResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleAssociation", required: false, type: .structure) ] /// Information about the DisassociateResolverRule request, including the status of the request. public let resolverRuleAssociation: ResolverRuleAssociation? public init(resolverRuleAssociation: ResolverRuleAssociation? = nil) { self.resolverRuleAssociation = resolverRuleAssociation } private enum CodingKeys: String, CodingKey { case resolverRuleAssociation = "ResolverRuleAssociation" } } public struct Filter: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "Values", required: false, type: .list) ] /// When you're using a List operation and you want the operation to return a subset of objects, such as resolver endpoints or resolver rules, the name of the parameter that you want to use to filter objects. For example, to list only inbound resolver endpoints, specify Direction for the value of Name. public let name: String? /// When you're using a List operation and you want the operation to return a subset of objects, such as resolver endpoints or resolver rules, the value of the parameter that you want to use to filter objects. For example, to list only inbound resolver endpoints, specify INBOUND for the value of Values. public let values: [String]? public init(name: String? = nil, values: [String]? = nil) { self.name = name self.values = values } private enum CodingKeys: String, CodingKey { case name = "Name" case values = "Values" } } public struct GetResolverEndpointRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// The ID of the resolver endpoint that you want to get information about. public let resolverEndpointId: String public init(resolverEndpointId: String) { self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case resolverEndpointId = "ResolverEndpointId" } } public struct GetResolverEndpointResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// Information about the resolver endpoint that you specified in a GetResolverEndpoint request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct GetResolverRuleAssociationRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleAssociationId", required: true, type: .string) ] /// The ID of the resolver rule association that you want to get information about. public let resolverRuleAssociationId: String public init(resolverRuleAssociationId: String) { self.resolverRuleAssociationId = resolverRuleAssociationId } private enum CodingKeys: String, CodingKey { case resolverRuleAssociationId = "ResolverRuleAssociationId" } } public struct GetResolverRuleAssociationResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleAssociation", required: false, type: .structure) ] /// Information about the resolver rule association that you specified in a GetResolverRuleAssociation request. public let resolverRuleAssociation: ResolverRuleAssociation? public init(resolverRuleAssociation: ResolverRuleAssociation? = nil) { self.resolverRuleAssociation = resolverRuleAssociation } private enum CodingKeys: String, CodingKey { case resolverRuleAssociation = "ResolverRuleAssociation" } } public struct GetResolverRulePolicyRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Arn", required: true, type: .string) ] /// The ID of the resolver rule policy that you want to get information about. public let arn: String public init(arn: String) { self.arn = arn } private enum CodingKeys: String, CodingKey { case arn = "Arn" } } public struct GetResolverRulePolicyResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRulePolicy", required: false, type: .string) ] /// Information about the resolver rule policy that you specified in a GetResolverRulePolicy request. public let resolverRulePolicy: String? public init(resolverRulePolicy: String? = nil) { self.resolverRulePolicy = resolverRulePolicy } private enum CodingKeys: String, CodingKey { case resolverRulePolicy = "ResolverRulePolicy" } } public struct GetResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRuleId", required: true, type: .string) ] /// The ID of the resolver rule that you want to get information about. public let resolverRuleId: String public init(resolverRuleId: String) { self.resolverRuleId = resolverRuleId } private enum CodingKeys: String, CodingKey { case resolverRuleId = "ResolverRuleId" } } public struct GetResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRule", required: false, type: .structure) ] /// Information about the resolver rule that you specified in a GetResolverRule request. public let resolverRule: ResolverRule? public init(resolverRule: ResolverRule? = nil) { self.resolverRule = resolverRule } private enum CodingKeys: String, CodingKey { case resolverRule = "ResolverRule" } } public struct IpAddressRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Ip", required: false, type: .string), AWSShapeMember(label: "SubnetId", required: true, type: .string) ] /// The IP address that you want to use for DNS queries. public let ip: String? /// The subnet that contains the IP address. public let subnetId: String public init(ip: String? = nil, subnetId: String) { self.ip = ip self.subnetId = subnetId } private enum CodingKeys: String, CodingKey { case ip = "Ip" case subnetId = "SubnetId" } } public struct IpAddressResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "CreationTime", required: false, type: .string), AWSShapeMember(label: "Ip", required: false, type: .string), AWSShapeMember(label: "IpId", required: false, type: .string), AWSShapeMember(label: "ModificationTime", required: false, type: .string), AWSShapeMember(label: "Status", required: false, type: .enum), AWSShapeMember(label: "StatusMessage", required: false, type: .string), AWSShapeMember(label: "SubnetId", required: false, type: .string) ] /// The date and time that the IP address was created, in Unix time format and Coordinated Universal Time (UTC). public let creationTime: String? /// One IP address that the resolver endpoint uses for DNS queries. public let ip: String? /// The ID of one IP address. public let ipId: String? /// The date and time that the IP address was last modified, in Unix time format and Coordinated Universal Time (UTC). public let modificationTime: String? /// A status code that gives the current status of the request. public let status: IpAddressStatus? /// A message that provides additional information about the status of the request. public let statusMessage: String? /// The ID of one subnet. public let subnetId: String? public init(creationTime: String? = nil, ip: String? = nil, ipId: String? = nil, modificationTime: String? = nil, status: IpAddressStatus? = nil, statusMessage: String? = nil, subnetId: String? = nil) { self.creationTime = creationTime self.ip = ip self.ipId = ipId self.modificationTime = modificationTime self.status = status self.statusMessage = statusMessage self.subnetId = subnetId } private enum CodingKeys: String, CodingKey { case creationTime = "CreationTime" case ip = "Ip" case ipId = "IpId" case modificationTime = "ModificationTime" case status = "Status" case statusMessage = "StatusMessage" case subnetId = "SubnetId" } } public enum IpAddressStatus: String, CustomStringConvertible, Codable { case creating = "CREATING" case failedCreation = "FAILED_CREATION" case attaching = "ATTACHING" case attached = "ATTACHED" case remapDetaching = "REMAP_DETACHING" case remapAttaching = "REMAP_ATTACHING" case detaching = "DETACHING" case failedResourceGone = "FAILED_RESOURCE_GONE" case deleting = "DELETING" case deleteFailedFasExpired = "DELETE_FAILED_FAS_EXPIRED" public var description: String { return self.rawValue } } public struct IpAddressUpdate: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Ip", required: false, type: .string), AWSShapeMember(label: "IpId", required: false, type: .string), AWSShapeMember(label: "SubnetId", required: false, type: .string) ] /// The new IP address. public let ip: String? /// Only when removing an IP address from a resolver endpoint: The ID of the IP address that you want to remove. To get this ID, use GetResolverEndpoint. public let ipId: String? /// The ID of the subnet that includes the IP address that you want to update. To get this ID, use GetResolverEndpoint. public let subnetId: String? public init(ip: String? = nil, ipId: String? = nil, subnetId: String? = nil) { self.ip = ip self.ipId = ipId self.subnetId = subnetId } private enum CodingKeys: String, CodingKey { case ip = "Ip" case ipId = "IpId" case subnetId = "SubnetId" } } public struct ListResolverEndpointIpAddressesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// The maximum number of IP addresses that you want to return in the response to a ListResolverEndpointIpAddresses request. If you don't specify a value for MaxResults, Resolver returns up to 100 IP addresses. public let maxResults: Int32? /// For the first ListResolverEndpointIpAddresses request, omit this value. If the specified resolver endpoint has more than MaxResults IP addresses, you can submit another ListResolverEndpointIpAddresses request to get the next group of IP addresses. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The ID of the resolver endpoint that you want to get IP addresses for. public let resolverEndpointId: String public init(maxResults: Int32? = nil, nextToken: String? = nil, resolverEndpointId: String) { self.maxResults = maxResults self.nextToken = nextToken self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resolverEndpointId = "ResolverEndpointId" } } public struct ListResolverEndpointIpAddressesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "IpAddresses", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// The IP addresses that DNS queries pass through on their way to your network (outbound endpoint) or on the way to Resolver (inbound endpoint). public let ipAddresses: [IpAddressResponse]? /// The value that you specified for MaxResults in the request. public let maxResults: Int32? /// If the specified endpoint has more than MaxResults IP addresses, you can submit another ListResolverEndpointIpAddresses request to get the next group of IP addresses. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? public init(ipAddresses: [IpAddressResponse]? = nil, maxResults: Int32? = nil, nextToken: String? = nil) { self.ipAddresses = ipAddresses self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case ipAddresses = "IpAddresses" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListResolverEndpointsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Filters", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// An optional specification to return a subset of resolver endpoints, such as all inbound resolver endpoints. If you submit a second or subsequent ListResolverEndpoints request and specify the NextToken parameter, you must use the same values for Filters, if any, as in the previous request. public let filters: [Filter]? /// The maximum number of resolver endpoints that you want to return in the response to a ListResolverEndpoints request. If you don't specify a value for MaxResults, Resolver returns up to 100 resolver endpoints. public let maxResults: Int32? /// For the first ListResolverEndpoints request, omit this value. If you have more than MaxResults resolver endpoints, you can submit another ListResolverEndpoints request to get the next group of resolver endpoints. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int32? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListResolverEndpointsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ResolverEndpoints", required: false, type: .list) ] /// The value that you specified for MaxResults in the request. public let maxResults: Int32? /// If more than MaxResults IP addresses match the specified criteria, you can submit another ListResolverEndpoint request to get the next group of results. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The resolver endpoints that were created by using the current AWS account, and that match the specified filters, if any. public let resolverEndpoints: [ResolverEndpoint]? public init(maxResults: Int32? = nil, nextToken: String? = nil, resolverEndpoints: [ResolverEndpoint]? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resolverEndpoints = resolverEndpoints } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resolverEndpoints = "ResolverEndpoints" } } public struct ListResolverRuleAssociationsRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Filters", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// An optional specification to return a subset of resolver rules, such as resolver rules that are associated with the same VPC ID. If you submit a second or subsequent ListResolverRuleAssociations request and specify the NextToken parameter, you must use the same values for Filters, if any, as in the previous request. public let filters: [Filter]? /// The maximum number of rule associations that you want to return in the response to a ListResolverRuleAssociations request. If you don't specify a value for MaxResults, Resolver returns up to 100 rule associations. public let maxResults: Int32? /// For the first ListResolverRuleAssociation request, omit this value. If you have more than MaxResults rule associations, you can submit another ListResolverRuleAssociation request to get the next group of rule associations. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int32? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListResolverRuleAssociationsResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ResolverRuleAssociations", required: false, type: .list) ] /// The value that you specified for MaxResults in the request. public let maxResults: Int32? /// If more than MaxResults rule associations match the specified criteria, you can submit another ListResolverRuleAssociation request to get the next group of results. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The associations that were created between resolver rules and VPCs using the current AWS account, and that match the specified filters, if any. public let resolverRuleAssociations: [ResolverRuleAssociation]? public init(maxResults: Int32? = nil, nextToken: String? = nil, resolverRuleAssociations: [ResolverRuleAssociation]? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resolverRuleAssociations = resolverRuleAssociations } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resolverRuleAssociations = "ResolverRuleAssociations" } } public struct ListResolverRulesRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Filters", required: false, type: .list), AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string) ] /// An optional specification to return a subset of resolver rules, such as all resolver rules that are associated with the same resolver endpoint. If you submit a second or subsequent ListResolverRules request and specify the NextToken parameter, you must use the same values for Filters, if any, as in the previous request. public let filters: [Filter]? /// The maximum number of resolver rules that you want to return in the response to a ListResolverRules request. If you don't specify a value for MaxResults, Resolver returns up to 100 resolver rules. public let maxResults: Int32? /// For the first ListResolverRules request, omit this value. If you have more than MaxResults resolver rules, you can submit another ListResolverRules request to get the next group of resolver rules. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int32? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListResolverRulesResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ResolverRules", required: false, type: .list) ] /// The value that you specified for MaxResults in the request. public let maxResults: Int32? /// If more than MaxResults resolver rules match the specified criteria, you can submit another ListResolverRules request to get the next group of results. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The resolver rules that were created using the current AWS account and that match the specified filters, if any. public let resolverRules: [ResolverRule]? public init(maxResults: Int32? = nil, nextToken: String? = nil, resolverRules: [ResolverRule]? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resolverRules = resolverRules } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resolverRules = "ResolverRules" } } public struct ListTagsForResourceRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "MaxResults", required: false, type: .integer), AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "ResourceArn", required: true, type: .string) ] /// The maximum number of tags that you want to return in the response to a ListTagsForResource request. If you don't specify a value for MaxResults, Resolver returns up to 100 tags. public let maxResults: Int32? /// For the first ListTagsForResource request, omit this value. If you have more than MaxResults tags, you can submit another ListTagsForResource request to get the next group of tags for the resource. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The Amazon Resource Name (ARN) for the resource that you want to list tags for. public let resourceArn: String public init(maxResults: Int32? = nil, nextToken: String? = nil, resourceArn: String) { self.maxResults = maxResults self.nextToken = nextToken self.resourceArn = resourceArn } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resourceArn = "ResourceArn" } } public struct ListTagsForResourceResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "NextToken", required: false, type: .string), AWSShapeMember(label: "Tags", required: false, type: .list) ] /// If more than MaxResults tags match the specified criteria, you can submit another ListTagsForResource request to get the next group of results. In the next request, specify the value of NextToken from the previous response. public let nextToken: String? /// The tags that are associated with the resource that you specified in the ListTagsForResource request. public let tags: [Tag]? public init(nextToken: String? = nil, tags: [Tag]? = nil) { self.nextToken = nextToken self.tags = tags } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case tags = "Tags" } } public struct PutResolverRulePolicyRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Arn", required: true, type: .string), AWSShapeMember(label: "ResolverRulePolicy", required: true, type: .string) ] /// The Amazon Resource Name (ARN) of the account that you want to grant permissions to. public let arn: String /// An AWS Identity and Access Management policy statement that lists the permissions that you want to grant to another AWS account. public let resolverRulePolicy: String public init(arn: String, resolverRulePolicy: String) { self.arn = arn self.resolverRulePolicy = resolverRulePolicy } private enum CodingKeys: String, CodingKey { case arn = "Arn" case resolverRulePolicy = "ResolverRulePolicy" } } public struct PutResolverRulePolicyResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ReturnValue", required: false, type: .boolean) ] /// Whether the PutResolverRulePolicy request was successful. public let returnValue: Bool? public init(returnValue: Bool? = nil) { self.returnValue = returnValue } private enum CodingKeys: String, CodingKey { case returnValue = "ReturnValue" } } public struct ResolverEndpoint: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Arn", required: false, type: .string), AWSShapeMember(label: "CreationTime", required: false, type: .string), AWSShapeMember(label: "CreatorRequestId", required: false, type: .string), AWSShapeMember(label: "Direction", required: false, type: .enum), AWSShapeMember(label: "HostVPCId", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string), AWSShapeMember(label: "IpAddressCount", required: false, type: .integer), AWSShapeMember(label: "ModificationTime", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "SecurityGroupIds", required: false, type: .list), AWSShapeMember(label: "Status", required: false, type: .enum), AWSShapeMember(label: "StatusMessage", required: false, type: .string) ] /// The ARN (Amazon Resource Name) for the resolver endpoint. public let arn: String? /// The date and time that the endpoint was created, in Unix time format and Coordinated Universal Time (UTC). public let creationTime: String? /// A unique string that identifies the request that created the resolver endpoint. The CreatorRequestId allows failed requests to be retried without the risk of executing the operation twice. public let creatorRequestId: String? /// Indicates whether the resolver endpoint allows inbound or outbound DNS queries: INBOUND: allows DNS queries to your VPC from your network or another VPC OUTBOUND: allows DNS queries from your VPC to your network or another VPC public let direction: ResolverEndpointDirection? /// The ID of the VPC that you want to create the resolver endpoint in. public let hostVPCId: String? /// The ID of the resolver endpoint. public let id: String? /// The number of IP addresses that the resolver endpoint can use for DNS queries. public let ipAddressCount: Int32? /// The date and time that the endpoint was last modified, in Unix time format and Coordinated Universal Time (UTC). public let modificationTime: String? /// The name that you assigned to the resolver endpoint when you submitted a CreateResolverEndpoint request. public let name: String? /// The ID of one or more security groups that control access to this VPC. The security group must include one or more inbound resolver rules. public let securityGroupIds: [String]? /// A code that specifies the current status of the resolver endpoint. public let status: ResolverEndpointStatus? /// A detailed description of the status of the resolver endpoint. public let statusMessage: String? public init(arn: String? = nil, creationTime: String? = nil, creatorRequestId: String? = nil, direction: ResolverEndpointDirection? = nil, hostVPCId: String? = nil, id: String? = nil, ipAddressCount: Int32? = nil, modificationTime: String? = nil, name: String? = nil, securityGroupIds: [String]? = nil, status: ResolverEndpointStatus? = nil, statusMessage: String? = nil) { self.arn = arn self.creationTime = creationTime self.creatorRequestId = creatorRequestId self.direction = direction self.hostVPCId = hostVPCId self.id = id self.ipAddressCount = ipAddressCount self.modificationTime = modificationTime self.name = name self.securityGroupIds = securityGroupIds self.status = status self.statusMessage = statusMessage } private enum CodingKeys: String, CodingKey { case arn = "Arn" case creationTime = "CreationTime" case creatorRequestId = "CreatorRequestId" case direction = "Direction" case hostVPCId = "HostVPCId" case id = "Id" case ipAddressCount = "IpAddressCount" case modificationTime = "ModificationTime" case name = "Name" case securityGroupIds = "SecurityGroupIds" case status = "Status" case statusMessage = "StatusMessage" } } public enum ResolverEndpointDirection: String, CustomStringConvertible, Codable { case inbound = "INBOUND" case outbound = "OUTBOUND" public var description: String { return self.rawValue } } public enum ResolverEndpointStatus: String, CustomStringConvertible, Codable { case creating = "CREATING" case operational = "OPERATIONAL" case updating = "UPDATING" case autoRecovering = "AUTO_RECOVERING" case actionNeeded = "ACTION_NEEDED" case deleting = "DELETING" public var description: String { return self.rawValue } } public struct ResolverRule: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Arn", required: false, type: .string), AWSShapeMember(label: "CreatorRequestId", required: false, type: .string), AWSShapeMember(label: "DomainName", required: false, type: .string), AWSShapeMember(label: "Id", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "OwnerId", required: false, type: .string), AWSShapeMember(label: "ResolverEndpointId", required: false, type: .string), AWSShapeMember(label: "RuleType", required: false, type: .enum), AWSShapeMember(label: "ShareStatus", required: false, type: .enum), AWSShapeMember(label: "Status", required: false, type: .enum), AWSShapeMember(label: "StatusMessage", required: false, type: .string), AWSShapeMember(label: "TargetIps", required: false, type: .list) ] /// The ARN (Amazon Resource Name) for the resolver rule specified by Id. public let arn: String? /// A unique string that you specified when you created the resolver rule. CreatorRequestIdidentifies the request and allows failed requests to be retried without the risk of executing the operation twice. public let creatorRequestId: String? /// DNS queries for this domain name are forwarded to the IP addresses that are specified in TargetIps. If a query matches multiple resolver rules (example.com and www.example.com), the query is routed using the resolver rule that contains the most specific domain name (www.example.com). public let domainName: String? /// The ID that Resolver assigned to the resolver rule when you created it. public let id: String? /// The name for the resolver rule, which you specified when you created the resolver rule. public let name: String? /// When a rule is shared with another AWS account, the account ID of the account that the rule is shared with. public let ownerId: String? /// The ID of the endpoint that the rule is associated with. public let resolverEndpointId: String? /// This value is always FORWARD. Other resolver rule types aren't supported. public let ruleType: RuleTypeOption? /// Whether the rules is shared and, if so, whether the current account is sharing the rule with another account, or another account is sharing the rule with the current account. public let shareStatus: ShareStatus? /// A code that specifies the current status of the resolver rule. public let status: ResolverRuleStatus? /// A detailed description of the status of a resolver rule. public let statusMessage: String? /// An array that contains the IP addresses and ports that you want to forward public let targetIps: [TargetAddress]? public init(arn: String? = nil, creatorRequestId: String? = nil, domainName: String? = nil, id: String? = nil, name: String? = nil, ownerId: String? = nil, resolverEndpointId: String? = nil, ruleType: RuleTypeOption? = nil, shareStatus: ShareStatus? = nil, status: ResolverRuleStatus? = nil, statusMessage: String? = nil, targetIps: [TargetAddress]? = nil) { self.arn = arn self.creatorRequestId = creatorRequestId self.domainName = domainName self.id = id self.name = name self.ownerId = ownerId self.resolverEndpointId = resolverEndpointId self.ruleType = ruleType self.shareStatus = shareStatus self.status = status self.statusMessage = statusMessage self.targetIps = targetIps } private enum CodingKeys: String, CodingKey { case arn = "Arn" case creatorRequestId = "CreatorRequestId" case domainName = "DomainName" case id = "Id" case name = "Name" case ownerId = "OwnerId" case resolverEndpointId = "ResolverEndpointId" case ruleType = "RuleType" case shareStatus = "ShareStatus" case status = "Status" case statusMessage = "StatusMessage" case targetIps = "TargetIps" } } public struct ResolverRuleAssociation: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Id", required: false, type: .string), AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ResolverRuleId", required: false, type: .string), AWSShapeMember(label: "Status", required: false, type: .enum), AWSShapeMember(label: "StatusMessage", required: false, type: .string), AWSShapeMember(label: "VPCId", required: false, type: .string) ] /// The ID of the association between a resolver rule and a VPC. Resolver assigns this value when you submit an AssociateResolverRule request. public let id: String? /// The name of an association between a resolver rule and a VPC. public let name: String? /// The ID of the resolver rule that you associated with the VPC that is specified by VPCId. public let resolverRuleId: String? /// A code that specifies the current status of the association between a resolver rule and a VPC. public let status: ResolverRuleAssociationStatus? /// A detailed description of the status of the association between a resolver rule and a VPC. public let statusMessage: String? /// The ID of the VPC that you associated the resolver rule with. public let vPCId: String? public init(id: String? = nil, name: String? = nil, resolverRuleId: String? = nil, status: ResolverRuleAssociationStatus? = nil, statusMessage: String? = nil, vPCId: String? = nil) { self.id = id self.name = name self.resolverRuleId = resolverRuleId self.status = status self.statusMessage = statusMessage self.vPCId = vPCId } private enum CodingKeys: String, CodingKey { case id = "Id" case name = "Name" case resolverRuleId = "ResolverRuleId" case status = "Status" case statusMessage = "StatusMessage" case vPCId = "VPCId" } } public enum ResolverRuleAssociationStatus: String, CustomStringConvertible, Codable { case creating = "CREATING" case complete = "COMPLETE" case deleting = "DELETING" case failed = "FAILED" case overridden = "OVERRIDDEN" public var description: String { return self.rawValue } } public struct ResolverRuleConfig: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ResolverEndpointId", required: false, type: .string), AWSShapeMember(label: "TargetIps", required: false, type: .list) ] /// The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the Route 53 console. public let name: String? /// The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that you specify in TargetIps. public let resolverEndpointId: String? /// For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to. public let targetIps: [TargetAddress]? public init(name: String? = nil, resolverEndpointId: String? = nil, targetIps: [TargetAddress]? = nil) { self.name = name self.resolverEndpointId = resolverEndpointId self.targetIps = targetIps } private enum CodingKeys: String, CodingKey { case name = "Name" case resolverEndpointId = "ResolverEndpointId" case targetIps = "TargetIps" } } public enum ResolverRuleStatus: String, CustomStringConvertible, Codable { case complete = "COMPLETE" case deleting = "DELETING" case updating = "UPDATING" case failed = "FAILED" public var description: String { return self.rawValue } } public enum RuleTypeOption: String, CustomStringConvertible, Codable { case forward = "FORWARD" case system = "SYSTEM" case recursive = "RECURSIVE" public var description: String { return self.rawValue } } public enum ShareStatus: String, CustomStringConvertible, Codable { case notShared = "NOT_SHARED" case sharedWithMe = "SHARED_WITH_ME" case sharedByMe = "SHARED_BY_ME" public var description: String { return self.rawValue } } public struct Tag: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Key", required: false, type: .string), AWSShapeMember(label: "Value", required: false, type: .string) ] /// The name for the tag. For example, if you want to associate Resolver resources with the account IDs of your customers for billing purposes, the value of Key might be account-id. public let key: String? /// The value for the tag. For example, if Key is account-id, then Value might be the ID of the customer account that you're creating the resource for. public let value: String? public init(key: String? = nil, value: String? = nil) { self.key = key self.value = value } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" } } public struct TagResourceRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResourceArn", required: true, type: .string), AWSShapeMember(label: "Tags", required: true, type: .list) ] /// The Amazon Resource Name (ARN) for the resource that you want to add tags to. To get the ARN for a resource, use the applicable Get or List command: GetResolverEndpoint GetResolverRule GetResolverRuleAssociation ListResolverEndpoints ListResolverRuleAssociations ListResolverRules public let resourceArn: String /// The tags that you want to add to the specified resource. public let tags: [Tag] public init(resourceArn: String, tags: [Tag]) { self.resourceArn = resourceArn self.tags = tags } private enum CodingKeys: String, CodingKey { case resourceArn = "ResourceArn" case tags = "Tags" } } public struct TagResourceResponse: AWSShape { public init() { } } public struct TargetAddress: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Ip", required: true, type: .string), AWSShapeMember(label: "Port", required: false, type: .integer) ] /// One IP address that you want to forward DNS queries to. You can specify only IPv4 addresses. public let ip: String /// The port at Ip that you want to forward DNS queries to. public let port: Int32? public init(ip: String, port: Int32? = nil) { self.ip = ip self.port = port } private enum CodingKeys: String, CodingKey { case ip = "Ip" case port = "Port" } } public struct UntagResourceRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResourceArn", required: true, type: .string), AWSShapeMember(label: "TagKeys", required: true, type: .list) ] /// The Amazon Resource Name (ARN) for the resource that you want to remove tags from. To get the ARN for a resource, use the applicable Get or List command: GetResolverEndpoint GetResolverRule GetResolverRuleAssociation ListResolverEndpoints ListResolverRuleAssociations ListResolverRules public let resourceArn: String /// The tags that you want to remove to the specified resource. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } private enum CodingKeys: String, CodingKey { case resourceArn = "ResourceArn" case tagKeys = "TagKeys" } } public struct UntagResourceResponse: AWSShape { public init() { } } public struct UpdateResolverEndpointRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Name", required: false, type: .string), AWSShapeMember(label: "ResolverEndpointId", required: true, type: .string) ] /// The name of the resolver endpoint that you want to update. public let name: String? /// The ID of the resolver endpoint that you want to update. public let resolverEndpointId: String public init(name: String? = nil, resolverEndpointId: String) { self.name = name self.resolverEndpointId = resolverEndpointId } private enum CodingKeys: String, CodingKey { case name = "Name" case resolverEndpointId = "ResolverEndpointId" } } public struct UpdateResolverEndpointResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverEndpoint", required: false, type: .structure) ] /// The response to an UpdateResolverEndpoint request. public let resolverEndpoint: ResolverEndpoint? public init(resolverEndpoint: ResolverEndpoint? = nil) { self.resolverEndpoint = resolverEndpoint } private enum CodingKeys: String, CodingKey { case resolverEndpoint = "ResolverEndpoint" } } public struct UpdateResolverRuleRequest: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "Config", required: true, type: .structure), AWSShapeMember(label: "ResolverRuleId", required: true, type: .string) ] /// The new settings for the resolver rule. public let config: ResolverRuleConfig /// The ID of the resolver rule that you want to update. public let resolverRuleId: String public init(config: ResolverRuleConfig, resolverRuleId: String) { self.config = config self.resolverRuleId = resolverRuleId } private enum CodingKeys: String, CodingKey { case config = "Config" case resolverRuleId = "ResolverRuleId" } } public struct UpdateResolverRuleResponse: AWSShape { public static var _members: [AWSShapeMember] = [ AWSShapeMember(label: "ResolverRule", required: false, type: .structure) ] /// The response to an UpdateResolverRule request. public let resolverRule: ResolverRule? public init(resolverRule: ResolverRule? = nil) { self.resolverRule = resolverRule } private enum CodingKeys: String, CodingKey { case resolverRule = "ResolverRule" } } }
48.872727
381
0.653863
abbef9ec346c68ce49295ae092f658a781689c7d
171
// // HomeType.swift // TV // // Created by GongsiWang on 2022/3/11. // import UIKit class HomeType: BaseModel { var title : String = "" var type : Int = 0 }
12.214286
39
0.590643
281fa1a70fd88177daf344949d8e8b117ee3117f
5,251
// // SessionDelegate.swift // Pyto Watch Extension // // Created by Emma Labbé on 04-02-20. // Copyright © 2018-2021 Emma Labbé. All rights reserved. // import WatchKit import WatchConnectivity import ClockKit /// A delegate for the WatchConnectivity session. class SessionDelegate: NSObject, WCSessionDelegate { /// The shared instance. static let shared = SessionDelegate() private override init() {} /// The console for the current running script. var console = "" /// Code called when the session finished activating. var didActivate: (() -> Void)? var complicationsHandlers = [String: [((Data) -> Void)]]() // MARK: - Session delegate func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { if let error = error { (WKExtension.shared().rootInterfaceController as? InterfaceController)?.label.setText(error.localizedDescription) } else { didActivate?() } } func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) { WCSession.default.sendMessage(["Received":userInfo], replyHandler: nil, errorHandler: nil) if (userInfo["Reload"] as? String) == "All" { for complication in CLKComplicationServer.sharedInstance().activeComplications ?? [] { CLKComplicationServer.sharedInstance().reloadTimeline(for: complication) } } else if (userInfo["Reload"] as? String) == "Descriptors" { CLKComplicationServer.sharedInstance().reloadComplicationDescriptors() } } func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { } func session(_ session: WCSession, didReceiveMessageData messageData: Data) { var str = (String(data: messageData, encoding: .utf8) ?? "") if str.hasPrefix("\r") { if console.hasSuffix("\n") { str = str.components(separatedBy: "\r").last ?? str } str = "\r\(str.components(separatedBy: "\r").last ?? str)" if console.contains("\n") || console.contains("\r") { var comp = console.components(separatedBy: "\n") if comp.count > 0 { comp.removeLast() } console = comp.joined(separator: "\n") } } else if str.contains("\r") { str = str.components(separatedBy: "\r").last ?? str } console += str (WKExtension.shared().rootInterfaceController as? InterfaceController)?.label.setText(console) } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { if message["prompt"] != nil { DispatchQueue.main.async { WKExtension.shared().rootInterfaceController?.presentTextInputController(withSuggestions: (message["suggestions"] as? [String]) ?? ["yes", "no"], allowedInputMode: .plain, completion: { (result) in if let str = result?.first as? String { self.console += "\(str)\n" (WKExtension.shared().rootInterfaceController as? InterfaceController)?.label.setText(self.console) replyHandler(["input": str]) } else { replyHandler(["input": ""]) } }) } } } func session(_ session: WCSession, didReceive file: WCSessionFile) { if let data = try? Data(contentsOf: file.fileURL) { if let image = UIImage(data: data) { DispatchQueue.main.async { WKExtension.shared().rootInterfaceController?.pushController(withName: "Image", context: image) } } else if let id = file.metadata?["id"] as? String { for handler in complicationsHandlers[id] ?? [] { handler(data) } complicationsHandlers[id] = nil } else { do { if FileManager.default.fileExists(atPath: PyWatchUI.cacheURL.path) { try? FileManager.default.removeItem(at: PyWatchUI.cacheURL) } if file.metadata?["Remove"] != nil { let controller = WKExtension.shared().visibleInterfaceController if controller is WatchHostingController { controller?.dismiss() } } else if WKExtension.shared().applicationState == .active { try FileManager.default.moveItem(at: file.fileURL, to: PyWatchUI.cacheURL) PyWatchUI.showView() } } catch { WCSession.default.sendMessage(["error": error.localizedDescription], replyHandler: nil, errorHandler: nil) } } } } }
40.083969
213
0.546943
e04583f4488296097dbdc6b961035ffe90ac2ab2
175
// // AuthorizeType.swift // // // Created by zunda on 2022/03/25. // import Foundation extension Sweet { public enum AuthorizeType { case User case App } }
10.9375
35
0.628571
09e815fd599597e9b60d332bafe551f5c4834d41
997
// // LocationSwiftTests.swift // LocationSwiftTests // // Created by snowlu on 2017/6/23. // Copyright © 2017年 ZhunKuaiTechnology. All rights reserved. // import XCTest @testable import LocationSwift class LocationSwiftTests: 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.945946
111
0.643932
115dd5f399cca5b890c1acd0bad234e48e1431a9
1,432
// // ImagesListView.swift // DockerClientMacApp // // Created by Alexander Steiner on 03.03.21. // import SwiftUI import DockerClientSwift import Combine struct ImagesListView: View { @EnvironmentObject var dockerClient: DockerClient private let changeSubject = PassthroughSubject<Void, Never>() var body: some View { GenericListLoadingView(loading: { completion in try! dockerClient.images.list(all: true) .whenComplete({ result in completion(result) }) }, changeSubject: changeSubject, content: { images in ImageTableView(items: .constant(images), reload: { changeSubject.send() }) { TableColumnBuilder<DockerClientSwift.Image>(name: "ID") { AnyView(Text($0.id.value)) } TableColumnBuilder<DockerClientSwift.Image>(name: "Name") { AnyView(Text($0.repositoryTags.first?.repository ?? "")) } TableColumnBuilder<DockerClientSwift.Image>(name: "Tag") { AnyView(Text($0.repositoryTags.first?.tag ?? "")) } TableColumnBuilder<DockerClientSwift.Image>(name: "Created At") { AnyView(Text($0.createdAt ?? Date(), style: .relative)) } } }) .navigationTitle("Images") } } struct ImagesListView_Previews: PreviewProvider { static var previews: some View { ImagesListView() } }
34.095238
139
0.620112
6aea552e01fc74602e6642c2bc7c5f3694b9dc82
3,350
import AudioKit import AudioKitUI import AVFoundation import SwiftUI struct VariableDelayOperationData { var maxTime: AUValue = 0.2 var frequency: AUValue = 0.3 var feedbackFrequency: AUValue = 0.21 var rampDuration: AUValue = 0.1 var balance: AUValue = 0.5 } class VariableDelayOperationConductor: ObservableObject, ProcessesPlayerInput { let engine = AudioEngine() let player = AudioPlayer() let dryWetMixer: DryWetMixer let buffer: AVAudioPCMBuffer let delay: OperationEffect init() { buffer = Cookbook.sourceBuffer player.buffer = buffer player.isLooping = true delay = OperationEffect(player) { player, parameters in let time = Operation.sineWave(frequency: parameters[1]) .scale(minimum: 0.001, maximum: parameters[0]) let feedback = Operation.sineWave(frequency: parameters[2]) .scale(minimum: 0.5, maximum: 0.9) return player.variableDelay(time: time, feedback: feedback, maximumDelayTime: 1.0) } delay.parameter1 = 0.2 delay.parameter2 = 0.3 delay.parameter3 = 0.21 dryWetMixer = DryWetMixer(player, delay) engine.output = dryWetMixer } @Published var data = VariableDelayOperationData() { didSet { delay.$parameter1.ramp(to: data.maxTime, duration: data.rampDuration) delay.$parameter2.ramp(to: data.frequency, duration: data.rampDuration) delay.$parameter3.ramp(to: data.feedbackFrequency, duration: data.rampDuration) dryWetMixer.balance = data.balance } } func start() { do { try engine.start() } catch let err { Log(err) } } func stop() { engine.stop() } } struct VariableDelayOperationView: View { @ObservedObject var conductor = VariableDelayOperationConductor() var body: some View { ScrollView { PlayerControls(conductor: conductor) ParameterSlider(text: "Max Time", parameter: self.$conductor.data.maxTime, range: 0...0.3, units: "Seconds") ParameterSlider(text: "Frequency", parameter: self.$conductor.data.frequency, range: 0...1, units: "Hz") ParameterSlider(text: "Feedback Frequency", parameter: self.$conductor.data.feedbackFrequency, range: 0...1, units: "Hz") ParameterSlider(text: "Mix", parameter: self.$conductor.data.balance, range: 0...1, units: "%") DryWetMixView(dry: conductor.player, wet: conductor.delay, mix: conductor.dryWetMixer) } .padding() .navigationBarTitle(Text("Variable Delay Fun")) .onAppear { self.conductor.start() } .onDisappear { self.conductor.stop() } } } struct VariableDelayOperation_Previews: PreviewProvider { static var previews: some View { VariableDelayOperationView() } }
33.168317
98
0.561791
3afb929181d02842a3578447e91c60da1d62e967
11,542
// // MainViewController.swift // CoronaContact // import Reusable import UIKit import Lottie final class MainViewController: UIViewController, StoryboardBased, ViewModelBased, FlashableScrollIndicators { var viewModel: MainViewModel? { didSet { viewModel?.viewController = self } } var flashScrollIndicatorsAfter: DispatchTimeInterval { .seconds(1) } @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var userHealthWrapperView: UIView! @IBOutlet weak var userHealthStatusView: QuarantineNotificationView! @IBOutlet weak var contactHealthWrapperView: UIView! @IBOutlet weak var contactHealthStatusView: QuarantineNotificationView! @IBOutlet weak var revocationWrapperView: UIView! @IBOutlet weak var revocationStatusView: QuarantineNotificationView! @IBOutlet weak var historyButton: TransButton! @IBOutlet weak var notificationStackView: UIStackView! @IBOutlet weak var selfTestingStackView: UIStackView! @IBOutlet weak var sicknessCertificateStackView: UIStackView! @IBOutlet weak var automaticHandshakeInactiveView: UIView! @IBOutlet weak var automaticHandshakeActiveView: UIView! @IBOutlet weak var automaticHandshakeAnimationView: AnimationView! @IBOutlet weak var backgroundHandshakeSwitch: UISwitch! @IBOutlet weak var backgroundHandshakeSwitchLabel: TransLabel! @IBOutlet weak var backgroundHandshakeActiveStateLabel: TransLabel! @IBOutlet weak var backgroundHandshakeDescriptionLabel: TransLabel! @IBOutlet weak var contactButton: PrimaryButton! @IBOutlet weak var handshakePausedInformation: UIView! private weak var launchScreenView: LaunchScreenView! override func viewDidLoad() { super.viewDidLoad() setupLaunchScreen() setupAutomatedHandshakeAnimation() registerNotificationObserver() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel?.viewWillAppear() updateView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) flashScrollIndicators() } deinit { removeNotificationObserver() } private func setupLaunchScreen() { launchScreenView = LaunchScreenView.loadFromNib() if let currentWindow = UIApplication.shared.keyWindow { currentWindow.embedSubview(launchScreenView) Timer.scheduledTimer(withTimeInterval: AppConfiguration.launchScreenDuration, repeats: false) { [weak self] _ in self?.launchScreenView.startFadeOutAnimation(withDuration: AppConfiguration.launchScreenFadeOutAnimationDuration) } } } private func setupAutomatedHandshakeAnimation() { automaticHandshakeAnimationView.loopMode = .loop if let path = Bundle.main.path(forResource: "handshakeActive", ofType: "json") { automaticHandshakeAnimationView.animation = Animation.filepath(path, animationCache: nil) } } func updateView() { guard let viewModel = viewModel, isViewLoaded else { return } historyButton.styledTextNormal = String(viewModel.numberOfContacts) notificationStackView.isHidden = !viewModel.displayNotifications configureUserHealthstatusView() configureContactHealthStatusView() configureRevocationStatusView() configureSelfTestingView() configureSicknessCertificateView() configureAutomationHandshakeView() contactButton.isEnabled = !viewModel.hasAttestedSickness } private func configureUserHealthstatusView() { guard let viewModel = viewModel else { return } switch viewModel.userHealthStatus { case .isHealthy: userHealthWrapperView.isHidden = true userHealthStatusView.isHidden = true default: userHealthWrapperView.isHidden = false userHealthStatusView.isHidden = false } userHealthStatusView.indicatorColor = viewModel.userHealthStatus.color userHealthStatusView.icon = viewModel.userHealthStatus.icon userHealthStatusView.headlineText = viewModel.userHealthStatus.headline userHealthStatusView.descriptionText = viewModel.userHealthStatus.description userHealthStatusView.quarantineCounter = viewModel.userHealthStatus.quarantineDays userHealthStatusView.buttonText = viewModel.userHealthStatus.primaryActionText userHealthStatusView.handlePrimaryTap = { [weak self] in self?.viewModel?.tappedPrimaryButtonInUserHealthStatus() } userHealthStatusView.removeButtons() if let secondaryActionText = viewModel.userHealthStatus.secondaryActionText { userHealthStatusView.addButton(title: secondaryActionText) { [weak self] in self?.viewModel?.tappedSecondaryButtonInUserHealthStatus() } } if let tertiaryActionText = viewModel.userHealthStatus.tertiaryActionText { userHealthStatusView.addButton(title: tertiaryActionText) { [weak self] in self?.viewModel?.tappedTertiaryButtonInUserHealthStatus() } } } private func configureContactHealthStatusView() { if let contactHealthStatus = viewModel?.contactHealthStatus { contactHealthWrapperView.isHidden = false contactHealthStatusView.isHidden = false contactHealthStatusView.indicatorColor = contactHealthStatus.color contactHealthStatusView.icon = contactHealthStatus.iconImageNotification contactHealthStatusView.headlineText = contactHealthStatus.headlineNotification contactHealthStatusView.quarantineCounter = contactHealthStatus.quarantineDays contactHealthStatusView.descriptionText = contactHealthStatus.descriptionNotification contactHealthStatusView.buttonText = contactHealthStatus.buttonNotification contactHealthStatusView.handlePrimaryTap = { [weak self] in self?.viewModel?.contactSickness(with: contactHealthStatus) } } else { contactHealthWrapperView.isHidden = true contactHealthStatusView.isHidden = true } } private func configureRevocationStatusView() { guard let revocationStatus = viewModel?.revocationStatus else { revocationWrapperView.isHidden = true revocationStatusView.isHidden = true return } revocationWrapperView.isHidden = false revocationStatusView.isHidden = false revocationStatusView.indicatorColor = revocationStatus.color revocationStatusView.icon = revocationStatus.icon revocationStatusView.headlineText = revocationStatus.headline revocationStatusView.descriptionText = revocationStatus.description revocationStatusView.appearance = revocationStatus.notificationAppearance if let primaryActionText = revocationStatus.primaryActionText { revocationStatusView.buttonText = primaryActionText } else { revocationStatusView.isPrimaryButtonEnabed = false } revocationStatusView.closeButton.isHidden = false revocationStatusView.handleClose = { [weak self] in self?.revocationStatusView.isHidden = true self?.viewModel?.removeRevocationStatus() } } private func configureAutomationHandshakeView() { guard let viewModel = viewModel else { return } if viewModel.isBackgroundHandshakeActive == true { automaticHandshakeInactiveView.isHidden = true automaticHandshakeActiveView.isHidden = false automaticHandshakeAnimationView.play() backgroundHandshakeSwitch.isOn = true backgroundHandshakeDescriptionLabel.styledText = "automatic_handshake_description_on".localized if viewModel.automaticHandshakePaused { handshakePausedInformation.isHidden = false backgroundHandshakeActiveStateLabel.styleName = StyleNames.boldYellow.rawValue backgroundHandshakeActiveStateLabel.styledText = "automatic_handshake_switch_paused".localized backgroundHandshakeSwitch.onTintColor = .ccYellow } else { handshakePausedInformation.isHidden = true backgroundHandshakeActiveStateLabel.styleName = StyleNames.boldBlue.rawValue backgroundHandshakeActiveStateLabel.styledText = "automatic_handshake_switch_on".localized backgroundHandshakeSwitch.onTintColor = .ccBlue } } else { handshakePausedInformation.isHidden = true automaticHandshakeInactiveView.isHidden = false automaticHandshakeActiveView.isHidden = true automaticHandshakeAnimationView.pause() backgroundHandshakeSwitch.isOn = false backgroundHandshakeActiveStateLabel.styleName = StyleNames.boldRed.rawValue backgroundHandshakeActiveStateLabel.styledText = "automatic_handshake_switch_off".localized backgroundHandshakeDescriptionLabel.styledText = "automatic_handshake_description_off".localized } if viewModel.hasAttestedSickness { backgroundHandshakeDescriptionLabel.styledText = "automatic_handshake_description_disabled".localized } backgroundHandshakeSwitch.isEnabled = !viewModel.hasAttestedSickness } private func configureSelfTestingView() { guard let viewModel = viewModel else { return } selfTestingStackView.isHidden = viewModel.isProbablySick || viewModel.hasAttestedSickness } private func configureSicknessCertificateView() { guard let viewModel = viewModel else { return } sicknessCertificateStackView.isHidden = viewModel.hasAttestedSickness } @IBAction func contactTapped(_ sender: Any) { viewModel?.contacts() } @IBAction func helpTapped(_ sender: Any) { viewModel?.help() } @IBAction func startMenuTapped(_ sender: Any) { viewModel?.startMenu() } @IBAction func selfTestingTapped(_ sender: Any) { viewModel?.selfTesting() } @IBAction func sicknessCertificateTapped(_ sender: Any) { viewModel?.sicknessCertificate() } @IBAction func historyButtonTapped(_ sender: Any) { viewModel?.history() } // MARK: - Event Handling private func registerNotificationObserver() { removeNotificationObserver() NotificationCenter.default.addObserver(self, selector: #selector(handleAppWillEnterForegroundNotification(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) } private func removeNotificationObserver() { NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) } @objc func handleAppWillEnterForegroundNotification(notification: Notification) { let isOnScreen = isViewLoaded && view.window != nil // Runs everytime the app comes into foreground and the dashboard screen is visible if isOnScreen { viewModel?.viewWillAppear() } } @IBAction func backgroundHandshakeSwitchValueChanged(_ sender: UISwitch) { viewModel?.backgroundDiscovery(enable: sender.isOn) } }
40.356643
129
0.714001
1a054f796de7b9ae5c1da492b0fc4849a796b4b6
692
// // NSAttributedStringExtension.swift // MarvelAPIApp // // Created by Luciano Sclovsky on 26/06/2018. // import Foundation import UIKit extension NSAttributedString { class func fromString(string: String, lineHeightMultiple: CGFloat) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = lineHeightMultiple let attributedString = NSMutableAttributedString(string: string) attributedString.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.baselineOffset: -1], range: NSMakeRange(0, attributedString.length)) return attributedString } }
31.454545
184
0.761561
efabc7a28aae07ff837a6d25a326df8152caed47
1,051
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Amplify import Foundation import AWSPluginsCore // The AWSS3StoragePlugin which conforms to the Amplify plugin protocols and implements the Storage Plugin APIs for S3. final public class AWSS3StoragePlugin: StorageCategoryPlugin { /// An instance of the S3 storage service var storageService: AWSS3StorageServiceBehaviour! /// An instance of the authentication service var authService: AWSAuthServiceBehavior! /// A queue that regulates the execution of operations. var queue: OperationQueue! /// The default access level used for API calls var defaultAccessLevel: StorageAccessLevel! /// The unique key of the plugin within the storage category. public var key: PluginKey { return PluginConstants.awsS3StoragePluginKey } /// Instantiates an instance of the AWSS3StoragePlugin. public init() { } } extension AWSS3StoragePlugin: AmplifyVersionable { }
27.657895
119
0.745005
7ac44b49f40c919bd88f480be67eea85f1bd98a0
3,578
// // UPennLoginService.swift // Penn Chart Live // // Created by Rashad Abdul-Salam on 3/13/19. // Copyright © 2019 University of Pennsylvania Health System. All rights reserved. // import Foundation class UPennLoginService { static var IsLoggedInNotification = "UPHSIsLoggedInNotification" var isLoggedIn : Bool { return UPennAuthenticationService.IsAuthenticated } var requestService = UPennNetworkRequestService() var loginDelegate: UPennLoginServiceDelegate var shouldAutoLogin : Bool { return UPennAuthenticationService.ShouldAutoLogin } var shouldAutoFill : Bool { return UPennAuthenticationService.ShouldAutoFill } var isFirstLogin : Bool { return UPennAuthenticationService.IsFirstLogin } private let genericLoginError = "Sorry an error occurred while attempting Login. Please try again." private let autoLoginError = "Something went wrong attempting Auto-Login - could not retrieve Username & Password. Please try again." private let usernamePasswordError = "You have entered an incorrect Username or Password. Please try again." init(loginDelegate: UPennLoginServiceDelegate) { self.loginDelegate = loginDelegate } func makeLoginRequest(username: String, password: String) { self.requestService.makeLoginRequest(username: username, password: password) { (response,errorStr) in if let error = errorStr { self.loginDelegate.didFailToLoginUser(errorStr: error) return } if let json = response as? [String:Any], let token = json["access_token"] as? String { print("Auth Token: \(token)") UPennAuthenticationService.storeAuthenticationCredentials( token: token, username: username, password: password) self.loginDelegate.didSuccessfullyLoginUser(username) return } // TODO: Add logic for expired JWT token // Generic Error self.loginDelegate.didFailToLoginUser(errorStr: self.usernamePasswordError) } } func cacheLoginCredentials(username: String, password: String) { UPennAuthenticationService.cacheAuthenticationCredentials(username: username, password: password) } func authenticationAutoFillCheck() { if shouldAutoFill { UPennAuthenticationService.checkAuthenticationCache { (username, password) in if let u = username, let p = password { self.loginDelegate.didReturnAutoFillCredentials(username: u, password: p) } } } } func attemptSilentLogin() { UPennAuthenticationService.checkAuthenticationCache { (username, password) in guard let u = username, let p = password else { self.loginDelegate.didFailToLoginUser(errorStr: self.autoLoginError) return } self.makeLoginRequest(username: u, password: p) } } func toggleShouldAutoLogin(_ autoLogin: Bool) { UPennAuthenticationService.toggleShouldAutoLogin(autoLogin) } func toggleShouldAutoFill(_ autoFill: Bool) { UPennAuthenticationService.toggleShouldAutoFill(autoFill) } func setFirstLogin() { UPennAuthenticationService.setFirstLogin() } func logout() { UPennAuthenticationService.logout() } }
38.06383
137
0.650084
9ca929b7938a120564cdbc011c97b9c6ad540f1f
2,285
// // FakeClassnameTags123API.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif @objc open class FakeClassnameTags123API : NSObject { /** To test class name in snake case - parameter body: (body) client model - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** To test class name in snake case - PATCH /fake_classname_test - To test class name in snake case - API Key: - type: apiKey api_key_query (QUERY) - name: api_key_query - parameter body: (body) client model - returns: RequestBuilder<Client> */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder<Client> { let localVariablePath = "/fake_classname_test" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Client>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } }
37.459016
216
0.701969
87ce51a90c9e96e307abc0d6bda67254fcbf99b2
9,379
// // TextField.swift // PhoneNumberKit // // Created by Roy Marmelstein on 07/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import UIKit /// Custom text field that formats phone numbers open class PhoneNumberTextField: UITextField, UITextFieldDelegate { let phoneNumberKit = PhoneNumberKit() /// Override setText so number will be automatically formatted when setting text by code override open var text: String? { set { if newValue != nil { let formattedNumber = partialFormatter.formatPartial(newValue! as String) super.text = formattedNumber } else { super.text = newValue } } get { return super.text } } /// allows text to be set without formatting open func setTextUnformatted(newValue:String?) { super.text = newValue } /// Override region to set a custom region. Automatically uses the default region code. public var defaultRegion = PhoneNumberKit.defaultRegionCode() { didSet { partialFormatter.defaultRegion = defaultRegion } } public var withPrefix: Bool = true { didSet { partialFormatter.withPrefix = withPrefix if withPrefix == false { self.keyboardType = UIKeyboardType.numberPad } else { self.keyboardType = UIKeyboardType.phonePad } } } public var isPartialFormatterEnabled = true public var maxDigits: Int? { didSet { partialFormatter.maxDigits = maxDigits } } let partialFormatter: PartialFormatter let nonNumericSet: NSCharacterSet = { var mutableSet = NSMutableCharacterSet.decimalDigit().inverted mutableSet.remove(charactersIn: PhoneNumberConstants.plusChars) return mutableSet as NSCharacterSet }() weak private var _delegate: UITextFieldDelegate? override open var delegate: UITextFieldDelegate? { get { return _delegate } set { self._delegate = newValue } } //MARK: Status public var currentRegion: String { get { return partialFormatter.currentRegion } } public var isValidNumber: Bool { get { let rawNumber = self.text ?? String() do { let _ = try phoneNumberKit.parse(rawNumber, withRegion: currentRegion) return true } catch { return false } } } //MARK: Lifecycle /** Init with frame - parameter frame: UITextfield F - returns: UITextfield */ override public init(frame:CGRect) { self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix) super.init(frame:frame) self.setup() } /** Init with coder - parameter aDecoder: decoder - returns: UITextfield */ required public init(coder aDecoder: NSCoder) { self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix) super.init(coder: aDecoder)! self.setup() } func setup(){ self.autocorrectionType = .no self.keyboardType = UIKeyboardType.phonePad super.delegate = self } // MARK: Phone number formatting /** * To keep the cursor position, we find the character immediately after the cursor and count the number of times it repeats in the remaining string as this will remain constant in every kind of editing. */ internal struct CursorPosition { let numberAfterCursor: String let repetitionCountFromEnd: Int } internal func extractCursorPosition() -> CursorPosition? { var repetitionCountFromEnd = 0 // Check that there is text in the UITextField guard let text = text, let selectedTextRange = selectedTextRange else { return nil } let textAsNSString = text as NSString let cursorEnd = offset(from: beginningOfDocument, to: selectedTextRange.end) // Look for the next valid number after the cursor, when found return a CursorPosition struct for i in cursorEnd ..< textAsNSString.length { let cursorRange = NSMakeRange(i, 1) let candidateNumberAfterCursor: NSString = textAsNSString.substring(with: cursorRange) as NSString if (candidateNumberAfterCursor.rangeOfCharacter(from: nonNumericSet as CharacterSet).location == NSNotFound) { for j in cursorRange.location ..< textAsNSString.length { let candidateCharacter = textAsNSString.substring(with: NSMakeRange(j, 1)) if candidateCharacter == candidateNumberAfterCursor as String { repetitionCountFromEnd += 1 } } return CursorPosition(numberAfterCursor: candidateNumberAfterCursor as String, repetitionCountFromEnd: repetitionCountFromEnd) } } return nil } // Finds position of previous cursor in new formatted text internal func selectionRangeForNumberReplacement(textField: UITextField, formattedText: String) -> NSRange? { let textAsNSString = formattedText as NSString var countFromEnd = 0 guard let cursorPosition = extractCursorPosition() else { return nil } for i in stride(from: (textAsNSString.length - 1), through: 0, by: -1) { let candidateRange = NSMakeRange(i, 1) let candidateCharacter = textAsNSString.substring(with: candidateRange) if candidateCharacter == cursorPosition.numberAfterCursor { countFromEnd += 1 if countFromEnd == cursorPosition.repetitionCountFromEnd { return candidateRange } } } return nil } open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = text else { return false } // allow delegate to intervene guard _delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true else { return false } guard isPartialFormatterEnabled else { return true } let textAsNSString = text as NSString let changedRange = textAsNSString.substring(with: range) as NSString let modifiedTextField = textAsNSString.replacingCharacters(in: range, with: string) let filteredCharacters = modifiedTextField.characters.filter { return String($0).rangeOfCharacter(from: (textField as! PhoneNumberTextField).nonNumericSet as CharacterSet) == nil } let rawNumberString = String(filteredCharacters) let formattedNationalNumber = partialFormatter.formatPartial(rawNumberString as String) var selectedTextRange: NSRange? let nonNumericRange = (changedRange.rangeOfCharacter(from: nonNumericSet as CharacterSet).location != NSNotFound) if (range.length == 1 && string.isEmpty && nonNumericRange) { selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: modifiedTextField) textField.text = modifiedTextField } else { selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: formattedNationalNumber) textField.text = formattedNationalNumber } sendActions(for: .editingChanged) if let selectedTextRange = selectedTextRange, let selectionRangePosition = textField.position(from: beginningOfDocument, offset: selectedTextRange.location) { let selectionRange = textField.textRange(from: selectionRangePosition, to: selectionRangePosition) textField.selectedTextRange = selectionRange } return false } //MARK: UITextfield Delegate open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldBeginEditing?(textField) ?? true } open func textFieldDidBeginEditing(_ textField: UITextField) { _delegate?.textFieldDidBeginEditing?(textField) } open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldEndEditing?(textField) ?? true } open func textFieldDidEndEditing(_ textField: UITextField) { _delegate?.textFieldDidEndEditing?(textField) } open func textFieldShouldClear(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldClear?(textField) ?? true } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return _delegate?.textFieldShouldReturn?(textField) ?? true } }
35.259398
207
0.633543
0e335a75e7aa5ede9c7435b6a0d914789d9e47c9
2,620
/* Copyright (c) <2021> 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 public protocol AnyReadable { /// crate a new Instance and initialize with default values without moving the offset static func new<C: Context>(_ bytes: UnsafeRawBufferPointer, with context: inout C, _ symbol: String?) throws -> Self? /// reads the content of the frame mutating func read(_ bytes: UnsafeRawBufferPointer, with reader: FileReader, _ symbol: String?) throws /// size of this readable in bytes @available(*, deprecated, message: "FALSE!") var byteSize : Int { get } /// returns as textual tree representation of this `Readable` and its children var debugLayout : String { get } } extension AnyReadable { static func read<C: Context>(from data: ContiguousBytes, with context: inout C) throws -> Self? { return try data.withUnsafeBytes { ptr in try context.parse(ptr, "\(type(of: self))") } } } //MARK:- Debug Representations extension AnyReadable { public var debugLayout : String { return self.debugLayout(0) } func debugLayout(_ level: Int = 0) -> String { var ret = String(repeating: " ", count: level)+"⎿"+" (\(Self.self)) [\(self.byteSize) bytes]" let mirror = Mirror(reflecting: self) mirror.children.forEach{ child in if let mem = child.value as? ReadableWrapper { ret += "\n" ret += mem.debugLayout(level+1) } } return ret } }
33.589744
122
0.673664
c119ee7a068cca04f66bde546738393191917946
824
// // ApplicationController.swift // cam1 // // Created by Hoon H. on 2015/02/17. // Copyright (c) 2015 Eonil. All rights reserved. // import UIKit @UIApplicationMain class ApplicationController: UIResponder, UIApplicationDelegate { var window = UIWindow(frame: UIScreen.mainScreen().bounds) as UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window!.rootViewController = ExampleViewController() window!.makeKeyAndVisible() return true } } private class ExampleViewController: UIViewController { lazy var manager = CameraManager() private override func viewDidLoad() { super.viewDidLoad() manager.display.frame = self.view.layer.bounds self.view.layer.addSublayer(manager.display) } }
16.156863
124
0.740291
33f909d6cff92cc3de67867e8dbea7de505b6c4b
1,210
import Spots import Sugar class ForYouDetailController: Controller { var lastContentOffset: CGPoint? lazy var barView: UIVisualEffectView = { let effect = UIBlurEffect(style: .extraLight) let view = UIVisualEffectView(effect: effect) view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 20) return view }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(barView) spot(at: 0, ofType: Listable.self)?.tableView.separatorStyle = .none } func detailDidDismiss(_ sender: AnyObject) { navigationController?.dismiss(animated: true, completion: nil) } } extension ForYouDetailController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) guard let navigationController = navigationController, scrollView.isTracking else { return } if let lastContentYOffset = lastContentOffset?.y { let hideNavigationBar = scrollView.contentOffset.y >= lastContentYOffset && scrollView.contentOffset.y > 64 navigationController.setNavigationBarHidden(hideNavigationBar, animated: true) } lastContentOffset = scrollView.contentOffset } }
27.5
115
0.734711
bf92be0e60c03ce4e250ec7eac32018205cd818f
321
import XCTest @testable import OpenCloudKitTests XCTMain([ testCase(OpenCloudKitTests.allTests), testCase(CKPredicateTests.allTests), testCase(CKConfigTests.allTests), testCase(CKRecordTests.allTests), testCase(CKShareMetadataTests.allTests), testCase(CKURLRequestTests.allTests), ])
24.692308
45
0.753894
08e5bc0134142cb2684047f4fe5a12a875e4d110
856
// // API+PetFinder+Network+Route.swift // howToUse // // Created by Dan Koza on 2/14/21. // import Foundation import PopNetworking ///https://www.petfinder.com/developers/v2/docs/ protocol PetFinderRoute: NetworkingRoute { var requiresAuthentication: Bool { get } } extension PetFinderRoute { var baseUrl: String { "https://api.petfinder.com" } var headers: NetworkingRouteHttpHeaders? { guard requiresAuthentication else { return nil } let storedAccess = API.PetFinder.StoredApiAccess.apiAccess return ["Authorization" : "\(storedAccess.tokenType) \(storedAccess.accessToken)" ] } var session: NetworkingSession { if requiresAuthentication { return API.PetFinder.Session.authenticationSession } else { return NetworkingSession.shared } } }
23.777778
91
0.676402
1c9a8d0b68fc172aec5404f1777fa71e8c815e08
279
// // ViewController.swift // deeplink // // Created by Istiak Morsalin on 28/8/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
13.95
58
0.648746
919175784f1eb302efe64beabc3c20ceeabaaa17
2,307
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Fast forward style: ≫ struct DynamicButtonStyleFastForward: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let thirdSize = size / 3 let sixthSize = size / 6 let a = CGPoint(x: center.x + sixthSize, y: center.y) let b = CGPoint(x: center.x - sixthSize, y: center.y + thirdSize) let c = CGPoint(x: center.x - sixthSize, y: center.y - thirdSize) let ofc = PathHelper.gravityPointOffset(fromCenter: center, a: a, b: b, c: c) let p1 = PathHelper.line(from: a, to: b, offset: CGPoint(x: ofc.x + sixthSize, y: ofc.y)) let p2 = PathHelper.line(from: a, to: b, offset: CGPoint(x: ofc.x - sixthSize, y: ofc.y)) let p3 = PathHelper.line(from: a, to: c, offset: CGPoint(x: ofc.x + sixthSize, y: ofc.y)) let p4 = PathHelper.line(from: a, to: c, offset: CGPoint(x: ofc.x - sixthSize, y: ofc.y)) pathVector = DynamicButtonPathVector(p1: p1, p2: p2, p3: p3, p4: p4) } /// "Fast Forward" style. static var styleName: String { return "Player - Fast Forward" } }
41.196429
93
0.710013
e29cba8a515f6949b2a1d6bdd9cec8ca5daba2c1
1,092
/// A hook to use current context value that is provided by `Context<T>.Provider`. /// The purpose is identical to use `Context<T>.Consumer`. /// /// typealias CounterContext = Context<Binding<Int>> /// /// let count = useContext(CounterContext.self) /// /// - Parameter context: The type of context. /// - Returns: A value that provided by provider from upstream of the view tree. public func useContext<T>(_ context: Context<T>.Type) -> T { useHook(ContextHook(context: context)) } internal struct ContextHook<T>: Hook { let context: Context<T>.Type let computation = HookComputation.once func makeValue(coordinator: Coordinator) -> T { guard let value = coordinator.environment[context] else { fatalError( """ No context value of type \(context) found. A \(context).Provider.init(value:content:) is missing as an ancestor of the consumer. - SeeAlso: https://reactjs.org/docs/context.html#contextprovider """ ) } return value } }
33.090909
101
0.625458
8fe4c4f841139229f8495fb4edb8b2462622d7d4
271
// // ServiceProvideListModel.swift // Partner // // Created by Weslie on 10/03/2018. // import UIKit import MJExtension class ServiceProvideListModel: NSObject { @objc var id : NSNumber? @objc var typeName : String? @objc var typeCate : NSNumber? }
15.055556
41
0.682657
d687208221ca9e89511e2c6a5ac667be6f7edcf5
1,432
// // Swift_TestUITests.swift // Swift_TestUITests // // Created by liu dante on 2021/7/27. // import XCTest class Swift_TestUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.302326
182
0.657123