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
e5d74c9a80b716c2beef6fe799fd49708796d6fa
3,270
extension Document: ExpressibleByArrayLiteral { /// Gets all top level values in this Document public var values: [Primitive] { var values = [Primitive]() values.reserveCapacity(32) var index = 4 while index < storage.readableBytes { guard let typeNum = storage.getInteger(at: index, as: UInt8.self), let type = TypeIdentifier(rawValue: typeNum) else { return values } index += 1 guard skipKey(at: &index) else { return values } guard let value = value(forType: type, at: index) else { return values } skipValue(ofType: type, at: &index) values.append(value) } return values } public subscript(index: Int) -> Primitive { get { var offset = 4 for _ in 0..<index { guard skipKeyValuePair(at: &offset) else { fatalError("Index \(index) out of range") } } guard let typeId = storage.getInteger(at: offset, as: UInt8.self), let type = TypeIdentifier(rawValue: typeId) else { fatalError("Index \(index) out of range") } guard skipKey(at: &offset), let value = self.value(forType: type, at: offset) else { fatalError("Index \(index) out of range") } return value } set { var offset = 4 for _ in 0..<index { guard skipKeyValuePair(at: &offset) else { fatalError("Index \(index) out of range") } } overwriteValue(with: newValue, atPairOffset: offset) } } public mutating func remove(at index: Int) { var offset = 4 for _ in 0..<index { guard skipKeyValuePair(at: &offset) else { fatalError("Index \(index) out of range") } } let base = offset guard skipKeyValuePair(at: &offset) else { fatalError("Index \(index) out of range") } let length = offset - base self.removeBytes(at: base, length: length) } /// Appends a `Value` to this `Document` where this `Document` acts like an `Array` /// /// TODO: Analyze what should happen with `Dictionary`-like documents and this function /// /// - parameter value: The `Value` to append public mutating func append(_ value: Primitive) { let key = String(self.count) appendValue(value, forKey: key) } public init(arrayLiteral elements: PrimitiveConvertible...) { self.init(array: elements.compactMap { $0.makePrimitive() } ) } /// Converts an array of Primitives to a BSON ArrayDocument public init(array: [Primitive]) { self.init(isArray: true) for element in array { self.append(element) } } } extension Array where Element == Primitive { public init(valuesOf document: Document) { self = document.values } }
27.478992
96
0.519572
d92ec660a341eb1a099ad25e09cb012b7aef2f27
5,496
import XCTest import Combine import SnapshotTesting import Nimble @testable import Relay @testable import RelayTestHelpers class DataCheckerTests: XCTestCase { var environment: MockEnvironment! var cancellables: Set<AnyCancellable>! override func setUpWithError() throws { environment = MockEnvironment() cancellables = Set<AnyCancellable>() } func testQueryIsMissingWhenItHasntBeenFetched() throws { let operation = MoviesTabQuery().createDescriptor() expect(self.environment.check(operation: operation)) == .missing } func testQueryIsAvailableWhenItHasBeenFetched() throws { let op = MoviesTabQuery() let operation = op.createDescriptor() environment.retain(operation: operation).store(in: &cancellables) try environment.mockResponse(op, MoviesTab.allFilms) waitUntilComplete(environment.fetchQuery(op)) let availability = environment.check(operation: operation) guard case .available(let date) = availability else { fail("Expected query to be available, but it was actually \(availability)") return } expect(date).notTo(beNil()) } func testNoFetchTimeWhenOperationIsNotRetained() throws { let op = MoviesTabQuery() let operation = op.createDescriptor() try environment.mockResponse(op, MoviesTab.allFilms) waitUntilComplete(environment.fetchQuery(op)) expect(self.environment.check(operation: operation)) == .available(nil) } func testMissingOnceOperationIsGarbageCollected() throws { let op = MoviesTabQuery() let operation = op.createDescriptor() let retainToken: AnyCancellable? = environment.retain(operation: operation) try environment.mockResponse(op, MoviesTab.allFilms) waitUntilComplete(environment.fetchQuery(op)) retainToken?.cancel() RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.2)) expect(self.environment.check(operation: operation)) == .missing } func testStaleWhenEntireStoreIsInvalidatedByMutation() throws { let op = CurrentUserToDoListQuery() let operation = op.createDescriptor() environment.retain(operation: operation).store(in: &cancellables) try environment.mockResponse(op, CurrentUserToDoList.myTodos) waitUntilComplete(environment.fetchQuery(op)) let input = ChangeTodoStatusInput( complete: true, id: "VG9kbzox", userId: "me") let mutation = ChangeTodoStatusMutation(variables: .init(input: input)) try environment.mockResponse(mutation, ChangeTodoStatus.completeBuyHorse) waitUntilComplete(environment.commitMutation(mutation, updater: { (store, _) in store.invalidateStore() })) expect(self.environment.check(operation: operation)) == .stale } func testStaleWhenEntireStoreIsInvalidatedLocally() throws { let op = CurrentUserToDoListQuery() let operation = op.createDescriptor() environment.retain(operation: operation).store(in: &cancellables) try environment.mockResponse(op, CurrentUserToDoList.myTodos) waitUntilComplete(environment.fetchQuery(op)) environment.commitUpdate { store in store.invalidateStore() } expect(self.environment.check(operation: operation)) == .stale } func testStaleWhenRecordInQueryDataIsInvalidated() throws { let op = CurrentUserToDoListQuery() let operation = op.createDescriptor() environment.retain(operation: operation).store(in: &cancellables) try environment.mockResponse(op, CurrentUserToDoList.myTodos) waitUntilComplete(environment.fetchQuery(op)) let input = ChangeTodoStatusInput( complete: true, id: "VG9kbzox", userId: "me") let mutation = ChangeTodoStatusMutation(variables: .init(input: input)) try environment.mockResponse(mutation, ChangeTodoStatus.completeBuyHorse) waitUntilComplete(environment.commitMutation(mutation, updater: { (store, _) in store["VG9kbzox"]!.invalidateRecord() })) expect(self.environment.check(operation: operation)) == .stale } func testNotStaleWhenRecordOutsideQueryDataIsInvalidated() throws { let op = CurrentUserToDoListQuery() let operation = op.createDescriptor() environment.retain(operation: operation).store(in: &cancellables) try environment.mockResponse(op, CurrentUserToDoList.myTodos) waitUntilComplete(environment.fetchQuery(op)) var record = Record(dataID: "foobar", typename: "Todo") record["text"] = "Do the thing" environment.store.source["foobar"] = record let input = ChangeTodoStatusInput( complete: true, id: "VG9kbzox", userId: "me") let mutation = ChangeTodoStatusMutation(variables: .init(input: input)) try environment.mockResponse(mutation, ChangeTodoStatus.completeBuyHorse) waitUntilComplete(environment.commitMutation(mutation, updater: { (store, _) in store["foobar"]!.invalidateRecord() })) let availability = environment.check(operation: operation) guard case .available(let date) = availability else { fail("Expected query to be available, but it was actually \(availability)") return } expect(date).notTo(beNil()) } }
37.903448
87
0.687955
f8141a04ecce015a51bc474730cb5a861f91b499
5,239
// // Data+Base64URL.swift // JOSESwift // // Created by Daniel Egger on 22/09/2017. // // --------------------------------------------------------------------------- // Copyright 2019 Airside Mobile Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // --------------------------------------------------------------------------- // import Foundation extension Data { /// Creates a new data buffer from a base64url encoded string. /// /// - Parameter base64URLString: The base64url encoded string to parse. /// - Returns: `nil` if the input is not recognized as valid base64url. public init?(base64URLEncoded base64URLString: String) { var s = base64URLString .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/") let mod = s.count % 4 switch mod { case 0: break case 2: s.append("==") case 3: s.append("=") default: return nil } self.init(base64Encoded: s) } /// Creates a new data buffer from base64url, UTF-8 encoded data. /// /// - Parameter base64URLData: The base64url, UTF-8 encoded data. /// - Returns: `nil` if the input is not recognized as valid base64url. public init?(base64URLEncoded base64URLData: Data) { guard let s = String(data: base64URLData, encoding: .utf8) else { return nil } self.init(base64URLEncoded: s) } /// Returns a base64url encoded string. /// /// - Returns: The base64url encoded string. public func base64URLEncodedString() -> String { let s = self.base64EncodedString() return s .replacingOccurrences(of: "=", with: "") .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") } /// Returns base64url encoded data. /// /// - Returns: The base64url encoded data. public func base64URLEncodedData() -> Data { // UTF-8 can represent [all Unicode characters](https://en.wikipedia.org/wiki/UTF-8), so this // forced unwrap is safe. See also [this](https://stackoverflow.com/a/46152738/5233456) SO answer. // swiftlint:disable:next force_unwrapping return self.base64URLEncodedString().data(using: .utf8)! } /// Returns the byte length of a data object as octet hexadecimal data. /// /// - Returns: The data byte length as octet hexadecimal data. func getByteLengthAsOctetHexData() -> Data { let dataLength = UInt64(self.count * 8) let dataLengthInHex = String(dataLength, radix: 16, uppercase: false) var dataLengthBytes = [UInt8](repeatElement(0x00, count: 8)) var dataIndex = dataLengthBytes.count-1 for index in stride(from: 0, to: dataLengthInHex.count, by: 2) { var offset = 2 var hexStringChunk = "" if dataLengthInHex.count-index == 1 { offset = 1 } let endIndex = dataLengthInHex.index(dataLengthInHex.endIndex, offsetBy: -index) let startIndex = dataLengthInHex.index(endIndex, offsetBy: -offset) let range = Range(uncheckedBounds: (lower: startIndex, upper: endIndex)) hexStringChunk = String(dataLengthInHex[range]) if let hexByte = UInt8(hexStringChunk, radix: 16) { dataLengthBytes[dataIndex] = hexByte } dataIndex -= 1 } return Data(dataLengthBytes) } /// Compares data in constant-time. /// /// The running time of this method is independent of the data compared, making it safe to use for comparing secret values such as cryptographic MACs. /// /// The number of bytes of both data are expected to be of same length. /// /// - Parameter other: Other data for comparison. /// - Returns: `true` if both data are equal, otherwise `false`. func timingSafeCompare(with other: Data) -> Bool { assert(self.count == other.count, "parameters should be of same length") if #available(iOS 10.1, *) { return timingsafe_bcmp([UInt8](self), [UInt8](other), self.count) == 0 } else { return _timingSafeCompare(with: other) } } func _timingSafeCompare(with other: Data) -> Bool { assert(self.count == other.count, "parameters should be of same length") var diff: UInt8 = 0 for i in 0 ..< self.count { diff |= self[i] ^ other[i] } return diff == 0 } } extension Data: DataConvertible { public init(_ data: Data) { self = data } public func data() -> Data { return self } }
35.161074
154
0.598778
c16e662e76a9d05287b3d1de79e9a2c8f8aa4095
751
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "FilesUI", platforms: [.iOS(.v15), .macOS(.v12), .tvOS(.v15), .watchOS(.v8)], products: [ .library( name: "FilesUI", targets: ["FilesUI"]), ], dependencies: [ .package( name: "ViewInspector", url: "https://github.com/nalexn/ViewInspector.git", .upToNextMajor(from: "0.9.0") ) ], targets: [ .target( name: "FilesUI", dependencies: [], linkerSettings: [.linkedFramework("SwiftUI")] ), .testTarget( name: "FilesUITests", dependencies: ["FilesUI", "ViewInspector"]), ] )
24.225806
70
0.499334
ab3ef583450c8f66ca092db0c081cc4c8a1fa72e
391
// // TabList.swift // jimmy // // Created by Jonathan Foucher on 17/02/2022. // import Foundation import SwiftUI class TabList: ObservableObject { @Published var tabs: [Tab] = [] @Published var activeTabId: UUID init() { let tab = Tab(url: URL(string: "gemini://about")!); self.tabs = [tab] self.activeTabId = tab.id tab.load() } }
17.772727
59
0.58312
ff6e461c32ce036f69ccca7207633d353e73a095
2,709
// // SceneDelegate.swift // AdmissionPredict // // Created by Amit Gupta on 11/10/20. // import UIKit import SwiftUI 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). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not 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. } }
42.328125
147
0.705795
501dd52d27750cea8f4035f8eb2bcd69dfc32156
851
import UIKit import Foundation import ConfettiKit @IBDesignable class CountdownLabel: UILabel { let padding = CGSize(width: 10, height: 6) let backgroundColorSoon = Colors.pink let backgroundColorLater = Colors.lightGray var event: EventViewModel! { didSet { backgroundColor = event.isSoon ? backgroundColorSoon : backgroundColorLater text = event.countdown sizeToFit() } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width + padding.width, height: size.height + padding.height) } }
25.029412
94
0.634548
26afc03882d83cc5a25e963cdb923569aba7a6b4
242
// 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 B<T where B : a { let a { protocol A { func c: A func b: T enum A
22
87
0.727273
18d944a52a6c531739c6a1a33f9886fc38d145e1
1,801
// // ViewController.swift // Numbers Keyboard // // Created by Dan Livingston on 3/30/16. // Copyright © 2016 Zombie Koala. All rights reserved. // Thanks to // Suragch ( http://stackoverflow.com/users/3681880/suragch ) // Steve ( http://stackoverflow.com/users/5553768/steve ) // // import UIKit /* class ViewController: UIViewController, UITextFieldDelegate, KeyboardDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var textField2: UITextField! var activeTextField = UITextField() override func viewDidLoad() { super.viewDidLoad() // initialize custom keyboard for iPad only, since iPhone can use the Number Pad if UIDevice.currentDevice().userInterfaceIdiom == .Pad { initializeCustomKeyboard() } } func initializeCustomKeyboard() { // initialize custom keyboard let keyboardView = Keyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300)) // the view controller will be notified by the keyboard whenever a key is tapped keyboardView.delegate = self // required for backspace to work textField.delegate = self textField2.delegate = self // replace system keyboard with custom keyboard textField.inputView = keyboardView textField2.inputView = keyboardView } func textFieldDidBeginEditing(textFieldUser: UITextField) { self.activeTextField = textFieldUser } // // MARK: required methods for keyboard delegate protocol // func keyWasTapped(character: String) { activeTextField.insertText(character) } func backspace() { activeTextField.deleteBackward() } } */
27.287879
88
0.639089
ebc653f58c5bb1dc182ae7c85d4e45bede8b4647
6,543
// // NullBytesTests.swift // ZcashLightClientKit-Unit-Tests // // Created by Francisco Gindre on 6/5/20. // import XCTest @testable import ZcashLightClientKit class NullBytesTests: XCTestCase { let networkType = NetworkType.mainnet func testZaddrNullBytes() throws { let validZaddr = "zs1gqtfu59z20s9t20mxlxj86zpw6p69l0ev98uxrmlykf2nchj2dw8ny5e0l22kwmld2afc37gkfp" // this is a valid zAddr. if you send ZEC to it, you will be contributing to Human Rights Foundation. see more ways to help at https://paywithz.cash/ let ZaddrWithNullBytes = "\(validZaddr)\0something else that makes the address invalid" XCTAssertFalse(try ZcashRustBackend.isValidShieldedAddress(ZaddrWithNullBytes, networkType: networkType)) } func testTaddrNullBytes() throws { let validTAddr = "t1J5pTRzJi7j8Xw9VJTrPxPEkaigr69gKVT" // this is a valid tAddr. if you send ZEC to it, you will be contributing to Human Rights Foundation. see more ways to help at https://paywithz.cash/ let TaddrWithNullBytes = "\(validTAddr)\0fasdfasdf" XCTAssertFalse(try ZcashRustBackend.isValidTransparentAddress(TaddrWithNullBytes, networkType: networkType)) } func testInitAccountTableNullBytes() throws { let wrongHash = "000000000\015c597fab53f\058b9e1ededbe8bd83ca0203788e2039eceeb0d65ca6" let goodHash = "00000000015c597fab53f58b9e1ededbe8bd83ca0203788e2039eceeb0d65ca6" let time: UInt32 = 1582235356 let height: Int32 = 735000 let wrongTree = "0161f2ff97ff6ac6a90f9bce76c11710460f4944d8695aecc7dc99e34cad0131040011015325b185e23e82562db27817be996ffade9597181244f67efc40561aeb9dde1101daeffadc9e38f755bcb55a847a1278518a0ba4a2ef33b2fe01bbb3eb242ab0070000000000011c51f9077e3f7e28e8e337eaf4bb99b41acbc853a37dcc1e172467a1c919fe4100010bb1f55481b2268ef31997dc0fb6b48a530bc17870220f156d832326c433eb0a010b3768d3bf7868a67823e022f49be67982d0588e7041c498a756024\0750065a4a0001a9e1bf4bccb48b14b544e770f21d48f2d3ad8d6ca54eccc92f60634e3078eb48013a1f7fb005388ac6f04099b647ed85d8b025d8ae4b178c2376b473b121b8c052000001d2ea556f49fb934dc76f087935a5c07788000b4e3aae24883adfec51b5f4d260" let goodTree = "0161f2ff97ff6ac6a90f9bce76c11710460f4944d8695aecc7dc99e34cad0131040011015325b185e23e82562db27817be996ffade9597181244f67efc40561aeb9dde1101daeffadc9e38f755bcb55a847a1278518a0ba4a2ef33b2fe01bbb3eb242ab0070000000000011c51f9077e3f7e28e8e337eaf4bb99b41acbc853a37dcc1e172467a1c919fe4100010bb1f55481b2268ef31997dc0fb6b48a530bc17870220f156d832326c433eb0a010b3768d3bf7868a67823e022f49be67982d0588e7041c498a756024750065a4a0001a9e1bf4bccb48b14b544e770f21d48f2d3ad8d6ca54eccc92f60634e3078eb48013a1f7fb005388ac6f04099b647ed85d8b025d8ae4b178c2376b473b121b8c052000001d2ea556f49fb934dc76f087935a5c07788000b4e3aae24883adfec51b5f4d260" XCTAssertThrowsError(try ZcashRustBackend.initBlocksTable(dbData: __dataDbURL(), height: height , hash: wrongHash, time: time, saplingTree: goodTree, networkType: networkType), "InitBlocksTable with Null bytes on hash string should have failed") { (error) in guard let rustError = error as? RustWeldingError else { XCTFail("Expected RustWeldingError") return } switch rustError { case .malformedStringInput: XCTAssertTrue(true) default: XCTFail("expected \(RustWeldingError.malformedStringInput) and got \(rustError)") } } XCTAssertThrowsError(try ZcashRustBackend.initBlocksTable(dbData: __dataDbURL(), height: height , hash: goodHash, time: time, saplingTree: wrongTree, networkType: networkType), "InitBlocksTable with Null bytes on saplingTree string should have failed") { (error) in guard let rustError = error as? RustWeldingError else { XCTFail("Expected RustWeldingError") return } switch rustError { case .malformedStringInput: XCTAssertTrue(true) default: XCTFail("expected \(RustWeldingError.malformedStringInput) and got \(rustError)") } } } func testderiveExtendedFullViewingKeyWithNullBytes() throws { let wrongSpendingKeys = "secret-extended-key-main1qw28psv0qqqqpqr2ru0kss5equx6h0xjsuk5299xrsgdqnhe0cknkl8uqff34prwkyuegyhh5d4rdr8025nl7e0hm8r2txx3fuea5mq\0uy3wnsr9tlajsg4wwvw0xcfk8357k4h850rgj72kt4rx3fjdz99zs9f4neda35cq8tn3848yyvlg4w38gx75cyv9jdpve77x9eq6rtl6d9qyh8det4edevlnc70tg5kse670x50764gzhy60dta0yv3wsd4fsuaz686lgszc7nc9vv" //this spending key corresponds to the "demo app reference seed" let goodSpendingKeys = "secret-extended-key-main1qw28psv0qqqqpqr2ru0kss5equx6h0xjsuk5299xrsgdqnhe0cknkl8uqff34prwkyuegyhh5d4rdr8025nl7e0hm8r2txx3fuea5mquy3wnsr9tlajsg4wwvw0xcfk8357k4h850rgj72kt4rx3fjdz99zs9f4neda35cq8tn3848yyvlg4w38gx75cyv9jdpve77x9eq6rtl6d9qyh8det4edevlnc70tg5kse670x50764gzhy60dta0yv3wsd4fsuaz686lgszc7nc9vv" XCTAssertThrowsError(try ZcashRustBackend.deriveExtendedFullViewingKey(wrongSpendingKeys, networkType: networkType),"Should have thrown an error but didn't! this is dangerous!") { (error) in guard let rustError = error as? RustWeldingError else { XCTFail("Expected RustWeldingError") return } switch rustError { case .malformedStringInput: XCTAssertTrue(true) default: XCTFail("expected \(RustWeldingError.malformedStringInput) and got \(rustError)") } } XCTAssertNoThrow(try ZcashRustBackend.deriveExtendedFullViewingKey(goodSpendingKeys, networkType: networkType)) } func testCheckNullBytes() throws { let validZaddr = "zs1gqtfu59z20s9t20mxlxj86zpw6p69l0ev98uxrmlykf2nchj2dw8ny5e0l22kwmld2afc37gkfp" // this is a valid zAddr. if you send ZEC to it, you will be contributing to Human Rights Foundation. see more ways to help at https://paywithz.cash/ XCTAssertFalse(validZaddr.containsCStringNullBytesBeforeStringEnding()) XCTAssertTrue("zs1gqtfu59z20s\09t20mxlxj86zpw6p69l0ev98uxrmlykf2nchj2dw8ny5e0l22kwmld2afc37gkfp".containsCStringNullBytesBeforeStringEnding()) XCTAssertTrue("\0".containsCStringNullBytesBeforeStringEnding()) XCTAssertFalse("".containsCStringNullBytesBeforeStringEnding()) } }
66.765306
644
0.764328
d56243704ccf201a025750c4d483724131bcc977
2,351
/** © Copyright 2019, The Great Rift Valley Software Company LICENSE: MIT License 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. The Great Rift Valley Software Company: https://riftvalleysoftware.com */ import Cocoa /* ################################################################################################################################## */ // MARK: - Basic Window Controller Class /* ################################################################################################################################## */ /** The main reason for creating this class was to allow us to interpret settings, and to fix an issue with Interface Builder. */ class RVS_BTDriver_OBD_MacOS_Test_Harness_Base_WindowController: NSWindowController { /* ################################################################## */ /** This accounts for a bug in Xcode, where the [`restorable`](https://developer.apple.com/documentation/appkit/nswindow/1526255-restorable) flag is ignored. If you set the name here, it will restore. */ override func windowDidLoad() { super.windowDidLoad() window?.title = window?.title.localizedVariant ?? "ERROR" self.windowFrameAutosaveName = window?.title ?? "ERROR" // This is because there seems to be a bug (maybe in IB), where the auto-restore setting is not saved unless we do this. } }
55.97619
201
0.655891
d673b0814aef81d071452e6ad321582d521d27dc
4,960
// // TKLoggerBaseHandler.swift // FBSnapshotTestCase // // Created by Shper on 2020/5/31. // import Foundation @objc open class TKLogBaseDestination: NSObject { open var format = "$Dyyyy-MM-dd HH:mm:ss $C $L/$T $t $F.$f:$l - $M $I" /// set custom log level words for each level open var levelString = LevelString() /// set custom log level colors for each level open var levelColor = LevelColor() public struct LevelString { public var verbose = "V" public var debug = "D" public var info = "I" public var warning = "W" public var error = "E" } // For a colored log level word in a logged line public struct LevelColor { public var verbose = "💜" // silver public var debug = "💚" // green public var info = "💙" // blue public var warning = "💛" // yellow public var error = "💔" // red } public override init() { } open func handlerLog(_ tkLog: TKLogModel) { } // MARK: Format func formatLog(_ tkLog: TKLogModel) -> String { var text = "" let phrases = ("$i" + format).split(separator: "$") for phrase in phrases where !phrases.isEmpty { let phrasePrefix = phrase[phrase.startIndex] let remainingPhrase = phrase[phrase.index(phrase.startIndex, offsetBy: 1)..<phrase.endIndex] switch phrasePrefix { case "i": // ignore text += remainingPhrase case "D": // Date text += formatDate(String(remainingPhrase)) case "C": // LevelColor text += paddedString(colorForLevel(tkLog.level) , String(remainingPhrase)) case "L": // Level text += paddedString(levelWord(tkLog.level) , String(remainingPhrase)) case "T": // Tag text += paddedString(loggerTag() , String(remainingPhrase)) case "t": // threadName text += paddedString(tkLog.threadName , String(remainingPhrase)) case "c": // clazzName text += paddedString(tkLog.clazzName, String(remainingPhrase)) case "F": // fileName text += paddedString(tkLog.fileName , String(remainingPhrase)) case "f": // functionName text += paddedString(tkLog.functionName , String(remainingPhrase)) case "l": // line text += paddedString(String(tkLog.lineNum ?? -1) , String(remainingPhrase)) case "M": // Message text += paddedString(tkLog.message, String(remainingPhrase)) case "I": // internal text += paddedString(tkLog.internalMessage, String(remainingPhrase)) default: text += phrase } } return text } func paddedString(_ str1: String?, _ str2: String) -> String { var str = (str1 ?? "") + str2 if str == " " { str = "" } return str } func formatDate(_ dateFormat: String, timeZone: String = "") -> String { let formatter = DateFormatter() if !timeZone.isEmpty { formatter.timeZone = TimeZone(abbreviation: timeZone) } formatter.dateFormat = dateFormat let dateStr = formatter.string(from: Date()) return dateStr } /// returns color string for level func colorForLevel(_ level: TKLogLevel) -> String { var color = "" switch level { case .debug: color = levelColor.debug case .info: color = levelColor.info case .warning: color = levelColor.warning case .error: color = levelColor.error default: color = levelColor.verbose } return color } /// returns the string of a level func levelWord(_ level: TKLogLevel) -> String { var str = "" switch level { case .debug: str = levelString.debug case .info: str = levelString.info case .warning: str = levelString.warning case .error: str = levelString.error default: // Verbose is default str = levelString.verbose } return str } func loggerTag() -> String { return TKLogger.loggerTag } // // MARK: Hashable 、Equatable // public func hash(into hasher: inout Hasher) { // // do noting. // } // // public static func == (lhs: TKLogBaseDestination, rhs: TKLogBaseDestination) -> Bool { // return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) // } }
29.52381
104
0.521774
9b2d4a048e92406c05560d32dbdc94f387cf912d
3,696
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import UIKit // MARK: CalendarViewWeekdayHeadingView class CalendarViewWeekdayHeadingView: UIView { private struct Constants { struct Light { static let regularHeight: CGFloat = 26.0 } struct Dark { static let paddingTop: CGFloat = 12.0 static let compactHeight: CGFloat = 26.0 static let regularHeight: CGFloat = 48.0 } } private var firstWeekday: Int? private let headerStyle: DatePickerHeaderStyle private var headingLabels = [UILabel]() init(headerStyle: DatePickerHeaderStyle) { self.headerStyle = headerStyle super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } override func sizeThatFits(_ size: CGSize) -> CGSize { switch headerStyle { case .light: return CGSize( width: size.width, height: Constants.Light.regularHeight ) case .dark: return CGSize( width: size.width, height: traitCollection.verticalSizeClass == .regular ? Constants.Dark.regularHeight : Constants.Dark.compactHeight ) } } override func layoutSubviews() { super.layoutSubviews() let paddingTop = (traitCollection.verticalSizeClass == .regular && headerStyle == .dark) ? Constants.Dark.paddingTop : 0.0 let labelWidth = UIScreen.main.roundToDevicePixels(bounds.size.width / 7.0) let labelHeight = bounds.size.height - paddingTop var left: CGFloat = 0.0 for label in headingLabels { label.frame = CGRect(x: left, y: paddingTop, width: labelWidth, height: labelHeight) left += labelWidth } flipSubviewsForRTL() } override func didMoveToWindow() { super.didMoveToWindow() if let window = window { backgroundColor = headerStyle == .dark ? Colors.primary(for: window) : Colors.Calendar.WeekdayHeading.Light.background } } func setup(horizontalSizeClass: UIUserInterfaceSizeClass, firstWeekday: Int) { if self.firstWeekday != nil && self.firstWeekday == firstWeekday { return } self.firstWeekday = firstWeekday for label in headingLabels { label.removeFromSuperview() } headingLabels = [UILabel]() let weekdaySymbols: [String] = horizontalSizeClass == .regular ? Calendar.current.shortStandaloneWeekdaySymbols : Calendar.current.veryShortStandaloneWeekdaySymbols for (index, weekdaySymbol) in weekdaySymbols.enumerated() { let label = UILabel() label.textAlignment = .center label.text = weekdaySymbol label.font = Fonts.caption1 switch headerStyle { case .light: label.textColor = (index == 0 || index == 6) ? Colors.Calendar.WeekdayHeading.Light.textWeekend : Colors.Calendar.WeekdayHeading.Light.textRegular case .dark: label.textColor = (index == 0 || index == 6) ? Colors.Calendar.WeekdayHeading.Dark.textWeekend : Colors.Calendar.WeekdayHeading.Dark.textRegular } headingLabels.append(label) addSubview(label) } // Shift `headingLabels` to align with `firstWeekday` preference for _ in 1..<firstWeekday { headingLabels.append(headingLabels.removeFirst()) } setNeedsLayout() } }
31.058824
172
0.619048
4b37bdc004d58d69e401982ca9cfafe2fadaff89
17,379
// 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 // /// Key for cookie name public let NSHTTPCookieName: String = "Name" /// Key for cookie value public let NSHTTPCookieValue: String = "Value" /// Key for cookie origin URL public let NSHTTPCookieOriginURL: String = "OriginURL" /// Key for cookie version public let NSHTTPCookieVersion: String = "Version" /// Key for cookie domain public let NSHTTPCookieDomain: String = "Domain" /// Key for cookie path public let NSHTTPCookiePath: String = "Path" /// Key for cookie secure flag public let NSHTTPCookieSecure: String = "Secure" /// Key for cookie expiration date public let NSHTTPCookieExpires: String = "Expires" /// Key for cookie comment text public let NSHTTPCookieComment: String = "Comment" /// Key for cookie comment URL public let NSHTTPCookieCommentURL: String = "CommentURL" /// Key for cookie discard (session-only) flag public let NSHTTPCookieDiscard: String = "Discard" /// Key for cookie maximum age (an alternate way of specifying the expiration) public let NSHTTPCookieMaximumAge: String = "Max-Age" /// Key for cookie ports public let NSHTTPCookiePort: String = "Port" /// `NSHTTPCookie` represents an http cookie. /// /// An `NSHTTPCookie` instance represents a single http cookie. It is /// an immutable object initialized from a dictionary that contains /// the various cookie attributes. It has accessors to get the various /// attributes of a cookie. public class NSHTTPCookie : NSObject { let _comment: String? let _commentURL: NSURL? let _domain: String let _expiresDate: NSDate? let _HTTPOnly: Bool let _secure: Bool let _sessionOnly: Bool let _name: String let _path: String let _portList: [NSNumber]? let _value: String let _version: Int var _properties: [String : Any] /// Initialize a NSHTTPCookie object with a dictionary of parameters /// /// - Parameter properties: The dictionary of properties to be used to /// initialize this cookie. /// /// Supported dictionary keys and value types for the /// given dictionary are as follows. /// /// All properties can handle an NSString value, but some can also /// handle other types. /// /// <table border=1 cellspacing=2 cellpadding=4> /// <tr> /// <th>Property key constant</th> /// <th>Type of value</th> /// <th>Required</th> /// <th>Description</th> /// </tr> /// <tr> /// <td>NSHTTPCookieComment</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Comment for the cookie. Only valid for version 1 cookies and /// later. Default is nil.</td> /// </tr> /// <tr> /// <td>NSHTTPCookieCommentURL</td> /// <td>NSURL or NSString</td> /// <td>NO</td> /// <td>Comment URL for the cookie. Only valid for version 1 cookies /// and later. Default is nil.</td> /// </tr> /// <tr> /// <td>NSHTTPCookieDomain</td> /// <td>NSString</td> /// <td>Special, a value for either NSHTTPCookieOriginURL or /// NSHTTPCookieDomain must be specified.</td> /// <td>Domain for the cookie. Inferred from the value for /// NSHTTPCookieOriginURL if not provided.</td> /// </tr> /// <tr> /// <td>NSHTTPCookieDiscard</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be discarded at /// the end of the session. String value must be either "TRUE" or /// "FALSE". Default is "FALSE", unless this is cookie is version /// 1 or greater and a value for NSHTTPCookieMaximumAge is not /// specified, in which case it is assumed "TRUE".</td> /// </tr> /// <tr> /// <td>NSHTTPCookieExpires</td> /// <td>NSDate or NSString</td> /// <td>NO</td> /// <td>Expiration date for the cookie. Used only for version 0 /// cookies. Ignored for version 1 or greater.</td> /// </tr> /// <tr> /// <td>NSHTTPCookieMaximumAge</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string containing an integer value stating how long in /// seconds the cookie should be kept, at most. Only valid for /// version 1 cookies and later. Default is "0".</td> /// </tr> /// <tr> /// <td>NSHTTPCookieName</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Name of the cookie</td> /// </tr> /// <tr> /// <td>NSHTTPCookieOriginURL</td> /// <td>NSURL or NSString</td> /// <td>Special, a value for either NSHTTPCookieOriginURL or /// NSHTTPCookieDomain must be specified.</td> /// <td>URL that set this cookie. Used as default for other fields /// as noted.</td> /// </tr> /// <tr> /// <td>NSHTTPCookiePath</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Path for the cookie. Inferred from the value for /// NSHTTPCookieOriginURL if not provided. Default is "/".</td> /// </tr> /// <tr> /// <td>NSHTTPCookiePort</td> /// <td>NSString</td> /// <td>NO</td> /// <td>comma-separated integer values specifying the ports for the /// cookie. Only valid for version 1 cookies and later. Default is /// empty string ("").</td> /// </tr> /// <tr> /// <td>NSHTTPCookieSecure</td> /// <td>NSString</td> /// <td>NO</td> /// <td>A string stating whether the cookie should be transmitted /// only over secure channels. String value must be either "TRUE" /// or "FALSE". Default is "FALSE".</td> /// </tr> /// <tr> /// <td>NSHTTPCookieValue</td> /// <td>NSString</td> /// <td>YES</td> /// <td>Value of the cookie</td> /// </tr> /// <tr> /// <td>NSHTTPCookieVersion</td> /// <td>NSString</td> /// <td>NO</td> /// <td>Specifies the version of the cookie. Must be either "0" or /// "1". Default is "0".</td> /// </tr> /// </table> /// /// All other keys are ignored. /// /// - Returns: An initialized `NSHTTPCookie`, or nil if the set of /// dictionary keys is invalid, for example because a required key is /// missing, or a recognized key maps to an illegal value. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public init?(properties: [String : Any]) { guard let path = properties[NSHTTPCookiePath] as? String, name = properties[NSHTTPCookieName] as? String, value = properties[NSHTTPCookieValue] as? String else { return nil } let canonicalDomain: String if let domain = properties[NSHTTPCookieDomain] as? String { canonicalDomain = domain } else if let originURL = properties[NSHTTPCookieOriginURL] as? NSURL, host = originURL.host { canonicalDomain = host } else { return nil } _path = path _name = name _value = value _domain = canonicalDomain if let secureString = properties[NSHTTPCookieSecure] as? String where secureString.characters.count > 0 { _secure = true } else { _secure = false } let version: Int if let versionString = properties[NSHTTPCookieVersion] as? String where versionString == "1" { version = 1 } else { version = 0 } _version = version if let portString = properties[NSHTTPCookiePort] as? String where _version == 1 { _portList = portString.characters .split(separator: ",") .flatMap { Int(String($0)) } .map { NSNumber(value: $0) } } else { _portList = nil } // TODO: factor into a utility function if version == 0 { let expiresProperty = properties[NSHTTPCookieExpires] if let date = expiresProperty as? NSDate { _expiresDate = date } else if let dateString = expiresProperty as? String { let formatter = NSDateFormatter() formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O" // per RFC 6265 '<rfc1123-date, defined in [RFC2616], Section 3.3.1>' let timeZone = NSTimeZone(abbreviation: "GMT") formatter.timeZone = timeZone _expiresDate = formatter.dateFromString(dateString) } else { _expiresDate = nil } } else if let maximumAge = properties[NSHTTPCookieMaximumAge] as? String, secondsFromNow = Int(maximumAge) where _version == 1 { _expiresDate = NSDate(timeIntervalSinceNow: Double(secondsFromNow)) } else { _expiresDate = nil } if let discardString = properties[NSHTTPCookieDiscard] as? String { _sessionOnly = discardString == "TRUE" } else { _sessionOnly = properties[NSHTTPCookieMaximumAge] == nil && version >= 1 } if version == 0 { _comment = nil _commentURL = nil } else { _comment = properties[NSHTTPCookieComment] as? String if let commentURL = properties[NSHTTPCookieCommentURL] as? NSURL { _commentURL = commentURL } else if let commentURL = properties[NSHTTPCookieCommentURL] as? String { _commentURL = NSURL(string: commentURL) } else { _commentURL = nil } } _HTTPOnly = false _properties = [NSHTTPCookieComment : properties[NSHTTPCookieComment], NSHTTPCookieCommentURL : properties[NSHTTPCookieCommentURL], "Created" : NSDate().timeIntervalSinceReferenceDate, // Cocoa Compatibility NSHTTPCookieDiscard : _sessionOnly, NSHTTPCookieDomain : _domain, NSHTTPCookieExpires : _expiresDate, NSHTTPCookieMaximumAge : properties[NSHTTPCookieMaximumAge], NSHTTPCookieName : _name, NSHTTPCookieOriginURL : properties[NSHTTPCookieOriginURL], NSHTTPCookiePath : _path, NSHTTPCookiePort : _portList, NSHTTPCookieSecure : _secure, NSHTTPCookieValue : _value, NSHTTPCookieVersion : _version ] } /// Return a dictionary of header fields that can be used to add the /// specified cookies to the request. /// /// - Parameter cookies: The cookies to turn into request headers. /// - Returns: A dictionary where the keys are header field names, and the values /// are the corresponding header field values. public class func requestHeaderFields(with cookies: [NSHTTPCookie]) -> [String : String] { var cookieString = cookies.reduce("") { (sum, next) -> String in return sum + "\(next._name)=\(next._value); " } //Remove the final trailing semicolon and whitespace if ( cookieString.length > 0 ) { cookieString.characters.removeLast() cookieString.characters.removeLast() } return ["Cookie": cookieString] } /// Return an array of cookies parsed from the specified response header fields and URL. /// /// This method will ignore irrelevant header fields so /// you can pass a dictionary containing data other than cookie data. /// - Parameter headerFields: The response header fields to check for cookies. /// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpeted. /// - Returns: An array of NSHTTPCookie objects public class func cookies(withResponseHeaderFields headerFields: [String : String], forURL URL: NSURL) -> [NSHTTPCookie] { NSUnimplemented() } /// Returns a dictionary representation of the receiver. /// /// This method returns a dictionary representation of the /// `NSHTTPCookie` which can be saved and passed to /// `init(properties:)` later to reconstitute an equivalent cookie. /// /// See the `NSHTTPCookie` `init(properties:)` method for /// more information on the constraints imposed on the dictionary, and /// for descriptions of the supported keys and values. /// /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public var properties: [String : Any]? { return _properties } /// The version of the receiver. /// /// Version 0 maps to "old-style" Netscape cookies. /// Version 1 maps to RFC2965 cookies. There may be future versions. public var version: Int { return _version } /// The name of the receiver. public var name: String { return _name } /// The value of the receiver. public var value: String { return _value } /// Returns The expires date of the receiver. /// /// The expires date is the date when the cookie should be /// deleted. The result will be nil if there is no specific expires /// date. This will be the case only for *session-only* cookies. /*@NSCopying*/ public var expiresDate: NSDate? { return _expiresDate } /// Whether the receiver is session-only. /// /// `true` if this receiver should be discarded at the end of the /// session (regardless of expiration date), `false` if receiver need not /// be discarded at the end of the session. public var isSessionOnly: Bool { return _sessionOnly } /// The domain of the receiver. /// /// This value specifies URL domain to which the cookie /// should be sent. A domain with a leading dot means the cookie /// should be sent to subdomains as well, assuming certain other /// restrictions are valid. See RFC 2965 for more detail. public var domain: String { return _domain } /// The path of the receiver. /// /// This value specifies the URL path under the cookie's /// domain for which this cookie should be sent. The cookie will also /// be sent for children of that path, so `"/"` is the most general. public var path: String { return _path } /// Whether the receiver should be sent only over secure channels /// /// Cookies may be marked secure by a server (or by a javascript). /// Cookies marked as such must only be sent via an encrypted connection to /// trusted servers (i.e. via SSL or TLS), and should not be delievered to any /// javascript applications to prevent cross-site scripting vulnerabilities. public var isSecure: Bool { return _secure } /// Whether the receiver should only be sent to HTTP servers per RFC 2965 /// /// Cookies may be marked as HTTPOnly by a server (or by a javascript). /// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests /// for URL's that match both the path and domain of the respective Cookies. /// Specifically these cookies should not be delivered to any javascript /// applications to prevent cross-site scripting vulnerabilities. public var isHTTPOnly: Bool { return _HTTPOnly } /// The comment of the receiver. /// /// This value specifies a string which is suitable for /// presentation to the user explaining the contents and purpose of this /// cookie. It may be nil. public var comment: String? { return _comment } /// The comment URL of the receiver. /// /// This value specifies a URL which is suitable for /// presentation to the user as a link for further information about /// this cookie. It may be nil. /*@NSCopying*/ public var commentURL: NSURL? { return _commentURL } /// The list ports to which the receiver should be sent. /// /// This value specifies an NSArray of NSNumbers /// (containing integers) which specify the only ports to which this /// cookie should be sent. /// /// The array may be nil, in which case this cookie can be sent to any /// port. public var portList: [NSNumber]? { return _portList } }
37.616883
146
0.602164
dea23e509ae6595dd4f60669a75224ba23742ad5
4,649
import XCTest @testable import MemoArt import ComposableArchitecture // MARK: AppCore High Score related tests extension AppCoreTests { func testPresentNewHighScoreForAnEmptyHighScoresBoard() throws { let store = TestStore( initialState: AppState.almostFinishedGame, reducer: appReducer, environment: .mocked(scheduler: scheduler) ) store.assert( .send(.game(.cardReturned(2))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 2: return Card(id: 2, art: .cave, isFaceUp: true) default: return card } } }, .receive(.game(.save)), .send(.game(.cardReturned(12))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 12: return Card(id: 12, art: .cave, isFaceUp: true) default: return card } } $0.game.isGameOver = true $0.game.moves = 143 $0.game.discoveredArts = $0.game.discoveredArts + [.cave] }, .receive(.game(.clearBackup)), .do { self.scheduler.advance(by: .seconds(0.8)) }, .receive(.presentNewHighScoreView) { $0.isNewHighScoreEntryPresented = true } ) } func testPresentNewHighScoreForAFullHighScoresBoard() throws { let store = TestStore( initialState: AppState.mocked { $0.game = AppState.almostFinishedGame.game $0.game.moves = 10 $0.highScores = .test }, reducer: appReducer, environment: .mocked(scheduler: scheduler) ) store.assert( .send(.game(.cardReturned(2))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 2: return Card(id: 2, art: .cave, isFaceUp: true) default: return card } } }, .receive(.game(.save)), .send(.game(.cardReturned(12))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 12: return Card(id: 12, art: .cave, isFaceUp: true) default: return card } } $0.game.isGameOver = true $0.game.moves = 11 $0.game.discoveredArts = $0.game.discoveredArts + [.cave] }, .receive(.game(.clearBackup)), .do { self.scheduler.advance(by: .seconds(0.8)) }, .receive(.presentNewHighScoreView) { $0.isNewHighScoreEntryPresented = true } ) } func testDoNotPresentNewHighScoreForAFullHighScoresBoardWhenTheScoreIsTooBad() throws { let store = TestStore( initialState: AppState.mocked { $0.game = AppState.almostFinishedGame.game $0.highScores = .test }, reducer: appReducer, environment: .mocked(scheduler: scheduler) ) store.assert( .send(.game(.cardReturned(2))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 2: return Card(id: 2, art: .cave, isFaceUp: true) default: return card } } }, .receive(.game(.save)), .send(.game(.cardReturned(12))) { $0.game.cards = $0.game.cards.map { card in switch card.id { case 12: return Card(id: 12, art: .cave, isFaceUp: true) default: return card } } $0.game.isGameOver = true $0.game.moves = 143 $0.game.discoveredArts = $0.game.discoveredArts + [.cave] }, .receive(.game(.clearBackup)) ) } func testEnteringANewHighScore() { let store = TestStore( initialState: AppState.mocked { $0.isNewHighScoreEntryPresented = true }, reducer: appReducer, environment: .mocked(scheduler: scheduler) ) store.assert( .send(.newHighScoreEntered) { $0.isNewHighScoreEntryPresented = false } ) } }
34.69403
91
0.474296
756384afd9eb42c1ddd1710bdeceaabc02e0c56f
1,222
// // BoolTransform.swift // ObjectMapperAdditions // // Created by Anton Plebanovich on 7/17/17. // Copyright © 2017 Anton Plebanovich. All rights reserved. // import ObjectMapper /// Transforms value of type Any to Bool. Tries to typecast if possible. public class BoolTransform: TransformType { public typealias Object = Bool public typealias JSON = Bool public init() {} public func transformFromJSON(_ value: Any?) -> Object? { if value == nil { return nil } else if let bool = value as? Bool { return bool } else if let int = value as? Int { return (int != 0) } else if let double = value as? Double { return (double != 0) } else if let string = value as? String { return Bool(string) } else if let number = value as? NSNumber { return number.boolValue } else { #if DEBUG print("Can not cast value \(value!) of type \(type(of: value!)) to type \(Object.self)") #endif return nil } } public func transformToJSON(_ value: Object?) -> JSON? { return value } }
27.155556
104
0.55892
dbf77243df9527ce3f39b404a9d74fd57f864f0e
230
// // ApiResponse.swift // github_repo_search_iOS_app // // Created by Dinakar Maurya on 2021/08/12. // /** Something can be added in base api response which is common to all api error data format */ protocol ApiResponse {}
19.166667
89
0.717391
8949e25974a55df25cb7694b83896ef06b01b122
1,557
import Foundation import TSCBasic import TuistAutomation import TuistCore import TuistGenerator import TuistGraph /// Custom mapper provider for automation features /// It uses default `WorkspaceMapperProvider` but adds its own on top final class AutomationWorkspaceMapperProvider: WorkspaceMapperProviding { private let workspaceDirectory: AbsolutePath private let workspaceMapperProvider: WorkspaceMapperProviding convenience init( workspaceDirectory: AbsolutePath ) { self.init( workspaceDirectory: workspaceDirectory, workspaceMapperProvider: WorkspaceMapperProvider( projectMapperProvider: AutomationProjectMapperProvider() ) ) } init( workspaceDirectory: AbsolutePath, workspaceMapperProvider: WorkspaceMapperProviding ) { self.workspaceDirectory = workspaceDirectory self.workspaceMapperProvider = workspaceMapperProvider } func mapper(config: Config) -> WorkspaceMapping { var mappers: [WorkspaceMapping] = [] mappers.append(AutomationPathWorkspaceMapper(workspaceDirectory: workspaceDirectory)) mappers.append(workspaceMapperProvider.mapper(config: config)) if config.generationOptions.contains(.disableAutogeneratedSchemes) { mappers.append(AutogeneratedProjectSchemeWorkspaceMapper( enableCodeCoverage: config.generationOptions.contains(.enableCodeCoverage))) } return SequentialWorkspaceMapper(mappers: mappers) } }
34.6
93
0.73282
3a7061a9c3d65bfb7d1c7bd517ed619fc0442fba
468
// 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 struct A<T where g: a{struct c class b{enum A {var _= d func a{ let g = c()
36
78
0.732906
d5b99013ebeca6b77587761993b5602a36c473a9
20,817
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Logging import NIO import NIOHTTP2 import NIOSSL import NIOTLS import NIOTransportServices import SwiftProtobuf /// Provides a single, managed connection to a server. /// /// The connection to the server is provided by a single channel which will attempt to reconnect /// to the server if the connection is dropped. This connection is guaranteed to always use the same /// event loop. /// /// The connection is initially setup with a handler to verify that TLS was established /// successfully (assuming TLS is being used). /// /// ┌──────────────────────────┐ /// │ DelegatingErrorHandler │ /// └──────────▲───────────────┘ /// HTTP2Frame│ /// ┌──────────┴───────────────┐ /// │ SettingsObservingHandler │ /// └──────────▲───────────────┘ /// HTTP2Frame│ /// │ ⠇ ⠇ ⠇ ⠇ /// │ ┌┴─▼┐ ┌┴─▼┐ /// │ │ | │ | HTTP/2 streams /// │ └▲─┬┘ └▲─┬┘ /// │ │ │ │ │ HTTP2Frame /// ┌─┴────────────────┴─▼───┴─▼┐ /// │ HTTP2StreamMultiplexer | /// └─▲───────────────────────┬─┘ /// HTTP2Frame│ │HTTP2Frame /// ┌─┴───────────────────────▼─┐ /// │ NIOHTTP2Handler │ /// └─▲───────────────────────┬─┘ /// ByteBuffer│ │ByteBuffer /// ┌─┴───────────────────────▼─┐ /// │ TLSVerificationHandler │ /// └─▲───────────────────────┬─┘ /// ByteBuffer│ │ByteBuffer /// ┌─┴───────────────────────▼─┐ /// │ NIOSSLHandler │ /// └─▲───────────────────────┬─┘ /// ByteBuffer│ │ByteBuffer /// │ ▼ /// /// The `TLSVerificationHandler` observes the outcome of the SSL handshake and determines /// whether a `ClientConnection` should be returned to the user. In either eventuality, the /// handler removes itself from the pipeline once TLS has been verified. There is also a handler /// after the multiplexer for observing the initial settings frame, after which it determines that /// the connection state is `.ready` and removes itself from the channel. Finally there is a /// delegated error handler which uses the error delegate associated with this connection /// (see `DelegatingErrorHandler`). /// /// See `BaseClientCall` for a description of the pipelines associated with each HTTP/2 stream. public class ClientConnection { private let connectionManager: ConnectionManager private func getChannel() -> EventLoopFuture<Channel> { switch self.configuration.callStartBehavior.wrapped { case .waitsForConnectivity: return self.connectionManager.getChannel() case .fastFailure: return self.connectionManager.getOptimisticChannel() } } /// HTTP multiplexer from the `channel` handling gRPC calls. internal var multiplexer: EventLoopFuture<HTTP2StreamMultiplexer> { return self.getChannel().flatMap { $0.pipeline.handler(type: HTTP2StreamMultiplexer.self) } } /// The configuration for this client. internal let configuration: Configuration internal let scheme: String internal let authority: String /// A monitor for the connectivity state. public var connectivity: ConnectivityStateMonitor { return self.connectionManager.monitor } /// The `EventLoop` this connection is using. public var eventLoop: EventLoop { return self.connectionManager.eventLoop } /// Creates a new connection from the given configuration. Prefer using /// `ClientConnection.secure(group:)` to build a connection secured with TLS or /// `ClientConnection.insecure(group:)` to build a plaintext connection. /// /// - Important: Users should prefer using `ClientConnection.secure(group:)` to build a connection /// with TLS, or `ClientConnection.insecure(group:)` to build a connection without TLS. public init(configuration: Configuration) { self.configuration = configuration self.scheme = configuration.tls == nil ? "http" : "https" self.authority = configuration.tls?.hostnameOverride ?? configuration.target.host self.connectionManager = ConnectionManager( configuration: configuration, logger: configuration.backgroundActivityLogger ) } /// Closes the connection to the server. public func close() -> EventLoopFuture<Void> { return self.connectionManager.shutdown() } /// Populates the logger in `options` and appends a request ID header to the metadata, if /// configured. /// - Parameter options: The options containing the logger to populate. private func populateLogger(in options: inout CallOptions) { // Get connection metadata. self.connectionManager.appendMetadata(to: &options.logger) // Attach a request ID. let requestID = options.requestIDProvider.requestID() if let requestID = requestID { options.logger[metadataKey: MetadataKey.requestID] = "\(requestID)" // Add the request ID header too. if let requestIDHeader = options.requestIDHeader { options.customMetadata.add(name: requestIDHeader, value: requestID) } } } } extension ClientConnection: GRPCChannel { public func makeCall<Request: Message, Response: Message>( path: String, type: GRPCCallType, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] ) -> Call<Request, Response> { var options = callOptions self.populateLogger(in: &options) return Call( path: path, type: type, eventLoop: self.multiplexer.eventLoop, options: options, interceptors: interceptors, transportFactory: .http2( multiplexer: self.multiplexer, authority: self.authority, scheme: self.scheme, errorDelegate: self.configuration.errorDelegate ) ) } public func makeCall<Request: GRPCPayload, Response: GRPCPayload>( path: String, type: GRPCCallType, callOptions: CallOptions, interceptors: [ClientInterceptor<Request, Response>] ) -> Call<Request, Response> { var options = callOptions self.populateLogger(in: &options) return Call( path: path, type: type, eventLoop: self.multiplexer.eventLoop, options: options, interceptors: interceptors, transportFactory: .http2( multiplexer: self.multiplexer, authority: self.authority, scheme: self.scheme, errorDelegate: self.configuration.errorDelegate ) ) } } // MARK: - Configuration structures /// A target to connect to. public struct ConnectionTarget { internal enum Wrapped { case hostAndPort(String, Int) case unixDomainSocket(String) case socketAddress(SocketAddress) } internal var wrapped: Wrapped private init(_ wrapped: Wrapped) { self.wrapped = wrapped } /// The host and port. public static func hostAndPort(_ host: String, _ port: Int) -> ConnectionTarget { return ConnectionTarget(.hostAndPort(host, port)) } /// The path of a Unix domain socket. public static func unixDomainSocket(_ path: String) -> ConnectionTarget { return ConnectionTarget(.unixDomainSocket(path)) } /// A NIO socket address. public static func socketAddress(_ address: SocketAddress) -> ConnectionTarget { return ConnectionTarget(.socketAddress(address)) } var host: String { switch self.wrapped { case let .hostAndPort(host, _): return host case let .socketAddress(.v4(address)): return address.host case let .socketAddress(.v6(address)): return address.host case .unixDomainSocket, .socketAddress(.unixDomainSocket): return "localhost" } } } /// The connectivity behavior to use when starting an RPC. public struct CallStartBehavior: Hashable { internal enum Behavior: Hashable { case waitsForConnectivity case fastFailure } internal var wrapped: Behavior private init(_ wrapped: Behavior) { self.wrapped = wrapped } /// Waits for connectivity (that is, the 'ready' connectivity state) before attempting to start /// an RPC. Doing so may involve multiple connection attempts. /// /// This is the preferred, and default, behaviour. public static let waitsForConnectivity = CallStartBehavior(.waitsForConnectivity) /// The 'fast failure' behaviour is intended for cases where users would rather their RPC failed /// quickly rather than waiting for an active connection. The behaviour depends on the current /// connectivity state: /// /// - Idle: a connection attempt will be started and the RPC will fail if that attempt fails. /// - Connecting: a connection attempt is already in progress, the RPC will fail if that attempt /// fails. /// - Ready: a connection is already active: the RPC will be started using that connection. /// - Transient failure: the last connection or connection attempt failed and gRPC is waiting to /// connect again. The RPC will fail immediately. /// - Shutdown: the connection is shutdown, the RPC will fail immediately. public static let fastFailure = CallStartBehavior(.fastFailure) } extension ClientConnection { /// The configuration for a connection. public struct Configuration { /// The target to connect to. public var target: ConnectionTarget /// The event loop group to run the connection on. public var eventLoopGroup: EventLoopGroup /// An error delegate which is called when errors are caught. Provided delegates **must not /// maintain a strong reference to this `ClientConnection`**. Doing so will cause a retain /// cycle. public var errorDelegate: ClientErrorDelegate? /// A delegate which is called when the connectivity state is changed. public var connectivityStateDelegate: ConnectivityStateDelegate? /// The `DispatchQueue` on which to call the connectivity state delegate. If a delegate is /// provided but the queue is `nil` then one will be created by gRPC. public var connectivityStateDelegateQueue: DispatchQueue? /// TLS configuration for this connection. `nil` if TLS is not desired. public var tls: TLS? /// The connection backoff configuration. If no connection retrying is required then this should /// be `nil`. public var connectionBackoff: ConnectionBackoff? /// The connection keepalive configuration. public var connectionKeepalive: ClientConnectionKeepalive /// The amount of time to wait before closing the connection. The idle timeout will start only /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. /// /// If a connection becomes idle, starting a new RPC will automatically create a new connection. public var connectionIdleTimeout: TimeAmount /// The behavior used to determine when an RPC should start. That is, whether it should wait for /// an active connection or fail quickly if no connection is currently available. public var callStartBehavior: CallStartBehavior /// The HTTP/2 flow control target window size. public var httpTargetWindowSize: Int /// The HTTP protocol used for this connection. public var httpProtocol: HTTP2FramePayloadToHTTP1ClientCodec.HTTPProtocol { return self.tls == nil ? .http : .https } /// A logger for background information (such as connectivity state). A separate logger for /// requests may be provided in the `CallOptions`. /// /// Defaults to a no-op logger. public var backgroundActivityLogger: Logger /// A channel initializer which will be run after gRPC has initialized each channel. This may be /// used to add additional handlers to the pipeline and is intended for debugging. /// /// - Warning: The initializer closure may be invoked *multiple times*. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? /// Create a `Configuration` with some pre-defined defaults. Prefer using /// `ClientConnection.secure(group:)` to build a connection secured with TLS or /// `ClientConnection.insecure(group:)` to build a plaintext connection. /// /// - Parameter target: The target to connect to. /// - Parameter eventLoopGroup: The event loop group to run the connection on. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only /// on debug builds. /// - Parameter connectivityStateDelegate: A connectivity state delegate, defaulting to `nil`. /// - Parameter connectivityStateDelegateQueue: A `DispatchQueue` on which to call the /// `connectivityStateDelegate`. /// - Parameter tls: TLS configuration, defaulting to `nil`. /// - Parameter connectionBackoff: The connection backoff configuration to use. /// - Parameter connectionKeepalive: The keepalive configuration to use. /// - Parameter connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 30 minutes. /// - Parameter callStartBehavior: The behavior used to determine when a call should start in /// relation to its underlying connection. Defaults to `waitsForConnectivity`. /// - Parameter httpTargetWindowSize: The HTTP/2 flow control target window size. /// - Parameter backgroundActivityLogger: A logger for background information (such as /// connectivity state). Defaults to a no-op logger. /// - Parameter debugChannelInitializer: A channel initializer will be called after gRPC has /// initialized the channel. Defaults to `nil`. public init( target: ConnectionTarget, eventLoopGroup: EventLoopGroup, errorDelegate: ClientErrorDelegate? = LoggingClientErrorDelegate(), connectivityStateDelegate: ConnectivityStateDelegate? = nil, connectivityStateDelegateQueue: DispatchQueue? = nil, tls: Configuration.TLS? = nil, connectionBackoff: ConnectionBackoff? = ConnectionBackoff(), connectionKeepalive: ClientConnectionKeepalive = ClientConnectionKeepalive(), connectionIdleTimeout: TimeAmount = .minutes(30), callStartBehavior: CallStartBehavior = .waitsForConnectivity, httpTargetWindowSize: Int = 65535, backgroundActivityLogger: Logger = Logger( label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() } ), debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil ) { self.target = target self.eventLoopGroup = eventLoopGroup self.errorDelegate = errorDelegate self.connectivityStateDelegate = connectivityStateDelegate self.connectivityStateDelegateQueue = connectivityStateDelegateQueue self.tls = tls self.connectionBackoff = connectionBackoff self.connectionKeepalive = connectionKeepalive self.connectionIdleTimeout = connectionIdleTimeout self.callStartBehavior = callStartBehavior self.httpTargetWindowSize = httpTargetWindowSize self.backgroundActivityLogger = backgroundActivityLogger self.debugChannelInitializer = debugChannelInitializer } } } // MARK: - Configuration helpers/extensions extension ClientBootstrapProtocol { /// Connect to the given connection target. /// /// - Parameter target: The target to connect to. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> { switch target.wrapped { case let .hostAndPort(host, port): return self.connect(host: host, port: port) case let .unixDomainSocket(path): return self.connect(unixDomainSocketPath: path) case let .socketAddress(address): return self.connect(to: address) } } } extension Channel { /// Configure the channel with TLS. /// /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and /// the `TLSVerificationHandler` which verifies that a successful handshake was completed. /// /// - Parameter configuration: The configuration to configure the channel with. /// - Parameter serverHostname: The server hostname to use if the hostname should be verified. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler. func configureTLS( _ configuration: TLSConfiguration, serverHostname: String?, errorDelegate: ClientErrorDelegate?, logger: Logger ) -> EventLoopFuture<Void> { do { let sslClientHandler = try NIOSSLClientHandler( context: try NIOSSLContext(configuration: configuration), serverHostname: serverHostname ) return self.pipeline.addHandlers(sslClientHandler, TLSVerificationHandler(logger: logger)) } catch { return self.eventLoop.makeFailedFuture(error) } } func configureGRPCClient( httpTargetWindowSize: Int, tlsConfiguration: TLSConfiguration?, tlsServerHostname: String?, connectionManager: ConnectionManager, connectionKeepalive: ClientConnectionKeepalive, connectionIdleTimeout: TimeAmount, errorDelegate: ClientErrorDelegate?, requiresZeroLengthWriteWorkaround: Bool, logger: Logger ) -> EventLoopFuture<Void> { let tlsConfigured = tlsConfiguration.map { self.configureTLS( $0, serverHostname: tlsServerHostname, errorDelegate: errorDelegate, logger: logger ) } let configuration: EventLoopFuture<Void> = ( tlsConfigured ?? self.eventLoop .makeSucceededFuture(()) ).flatMap { self.configureHTTP2Pipeline( mode: .client, targetWindowSize: httpTargetWindowSize, inboundStreamInitializer: nil ) }.flatMap { _ in self.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { http2Handler in self.pipeline.addHandlers( [ GRPCClientKeepaliveHandler(configuration: connectionKeepalive), GRPCIdleHandler( mode: .client(connectionManager), logger: logger, idleTimeout: connectionIdleTimeout ), ], position: .after(http2Handler) ) }.flatMap { let errorHandler = DelegatingErrorHandler( logger: logger, delegate: errorDelegate ) return self.pipeline.addHandler(errorHandler) } } #if canImport(Network) // This availability guard is arguably unnecessary, but we add it anyway. if requiresZeroLengthWriteWorkaround, #available( OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, * ) { return configuration.flatMap { self.pipeline.addHandler(NIOFilterEmptyWritesHandler(), position: .first) } } else { return configuration } #else return configuration #endif } func configureGRPCClient( errorDelegate: ClientErrorDelegate?, logger: Logger ) -> EventLoopFuture<Void> { return self.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).flatMap { _ in self.pipeline.addHandler(DelegatingErrorHandler(logger: logger, delegate: errorDelegate)) } } } extension TimeAmount { /// Creates a new `TimeAmount` from the given time interval in seconds. /// /// - Parameter timeInterval: The amount of time in seconds static func seconds(timeInterval: TimeInterval) -> TimeAmount { return .nanoseconds(Int64(timeInterval * 1_000_000_000)) } } extension String { var isIPAddress: Bool { // We need some scratch space to let inet_pton write into. var ipv4Addr = in_addr() var ipv6Addr = in6_addr() return self.withCString { ptr in inet_pton(AF_INET, ptr, &ipv4Addr) == 1 || inet_pton(AF_INET6, ptr, &ipv6Addr) == 1 } } }
38.337017
126
0.668348
2333129ebcfcc1dc501eb895c3a3d78ff9bea770
1,107
// // AutoSolveConstants.swift // swift-test // // Created by Scott Kapelewski on 22.05.20. // Copyright © 2020 Scott Kapelewski. All rights reserved. // import Foundation public class AutoSolveConstants { static let Hostname = "rabbit.autosolve.io"; static let DirectExchange = "exchanges.direct"; static let FanoutExchange = "exchanges.fanout"; static let TokenResponseQueuePrefix = "queues.response.direct" static let TokenSendRoutingKey = "routes.request.token" static let TokenResponseRoutingKey = "routes.response.token" static let CancelSendRoutingKey = "routes.request.token.cancel" static let CancelResponseRoutingKey = "routes.response.token.cancel" static let Vhost = "oneclick" static let TokenRequest = "TokenRequest" static let CancelRequest = "CancelRequest" static let TokenResponse = "TokenResponse" static let CancelResponse = "CancelResponse" static let SuccessStatusCode = 200 static let InvalidClientKeyStatusCode = 400 static let InvalidCredentialsStatusCode = 401 static let TooManyRequests = 429 }
33.545455
72
0.741644
f7f3bf607467499303081035549295dd7ac1bfde
940
// // WLActionSheetCancelButton.swift // ActionSheet // // Created by lyy on 2018/4/3. // Copyright © 2018年 lyy. All rights reserved. // import UIKit class WLActionSheetCancelButton: UIButton { private var action: WLSheetAction? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { self.backgroundColor = .white self.titleLabel?.font = ActionSheetVisualStyle.sheetItemFont self.setTitleColor(ActionSheetVisualStyle.sheetItemColor, for: .normal) self.setBackgroundImage(UIImage.image(with: ActionSheetVisualStyle.cancelViewSelectedBgColor), for: .highlighted) } func show(with action: WLSheetAction) { self.action = action self.setTitle(action.title, for: .normal) } }
25.405405
121
0.669149
4af0c060a3ee454e56d6ec7e28f9fb78ff29bba7
1,249
// // AppDelegate.swift // Tracy // // Created by Kane Cheshire on 12/05/2020. // Copyright © 2020 Kin and Carta. All rights reserved. // import UIKit @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { private let central = Central() // On Android, this happens in the BluetoothForegroundService. Since there's no Service architecture on iOS, we'll just start everything in the AppDelegate. private let peripheral = Peripheral() func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { print("App will finish launching", launchOptions ?? [:]) return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print("App finished launching", launchOptions ?? [:]) return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
35.685714
190
0.763811
4b2c8fa953ce8856695353b76663571d69a5173d
2,749
// // SceneDelegate.swift // TestSSLPin // // Created by Mac on 04.09.2020. // Copyright © 2020 Lammax. All rights reserved. // import UIKit import SwiftUI 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). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
42.292308
147
0.705347
2f19ec75a496e09553dc39078494ba5cd13ac537
2,450
// // AppDelegate.swift // VCBoss // // Created by Levi Bostian on 12/12/2017. // Copyright (c) 2017 Levi Bostian. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let rootViewController = ParentViewController() rootViewController.view.backgroundColor = UIColor.white window?.rootViewController = rootViewController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
47.115385
285
0.747347
239b9e280bc6e8f626adc0d1c06a7f8ea8eb87f9
2,462
// // NavigationController.swift // PanModal // // Created by Stephen Sowole on 2/26/19. // Copyright © 2019 PanModal. All rights reserved. // import UIKit class NavigationController: UINavigationController, PanModalPresentable { private let navGroups = NavUserGroups() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() pushViewController(navGroups, animated: false) } override func popViewController(animated: Bool) -> UIViewController? { let vc = super.popViewController(animated: animated) panModalSetNeedsLayoutUpdate() return vc } override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: animated) panModalSetNeedsLayoutUpdate() } // MARK: - Pan Modal Presentable var panScrollable: UIScrollView? { return (topViewController as? PanModalPresentable)?.panScrollable } var longFormHeight: PanModalHeight { return .maxHeight } var shortFormHeight: PanModalHeight { return longFormHeight } } private class NavUserGroups: UserGroupViewController { override func viewDidLoad() { super.viewDidLoad() title = "iOS Engineers" navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.titleTextAttributes = [ .font: UIFont(name: "Lato-Bold", size: 17)!, .foregroundColor: #colorLiteral(red: 0.7019607843, green: 0.7058823529, blue: 0.7137254902, alpha: 1) ] navigationController?.navigationBar.tintColor = #colorLiteral(red: 0.7019607843, green: 0.7058823529, blue: 0.7137254902, alpha: 1) navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.1294117647, green: 0.1411764706, blue: 0.1568627451, alpha: 1) navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .plain, target: nil, action: nil) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let presentable = members[indexPath.row] let viewController = ProfileViewController(presentable: presentable) navigationController?.pushViewController(viewController, animated: true) } }
31.564103
142
0.703087
e62f43b9aca6716a0db0c817696b28139cebd6ad
2,182
// // CALayer+KMNameSpace.swift // KMNameSpace // // Created by MAC on 2019/11/18. // Copyright © 2019 KM. All rights reserved. // import QuartzCore import UIKit extension CALayer: KMKitCompatible {} public extension KMKitWrapper where KMKitWrapperType: CALayer { /// 获取截图 var snapshot: UIImage? { UIGraphicsBeginImageContextWithOptions( kmWrappedValue.bounds.size, kmWrappedValue.isOpaque, 0 ) defer { UIGraphicsEndImageContext() } guard let ctx = UIGraphicsGetCurrentContext() else { return nil } kmWrappedValue.render( in: ctx ) let image = UIGraphicsGetImageFromCurrentImageContext() return image } var transformDepth: CGFloat { return kmWrappedValue.transform.m34 } /// 映射UIView中对应的mode var contentMode: UIView.ContentMode { get { return CALayer.CAGravityToUIViewContentMode(gravity: kmWrappedValue.contentsGravity) } } } private extension CALayer { static func CAGravityToUIViewContentMode(gravity: CALayerContentsGravity) -> UIView.ContentMode { switch gravity { case .top: return .top case .left: return .left case .bottom: return .bottom case .right: return .right case .topLeft: return .topLeft case .topRight: return .topRight case .bottomLeft: return .bottomLeft case .bottomRight: return .bottomRight case .center: return .center case .resize: return .scaleToFill case .resizeAspect: return .scaleAspectFit case .resizeAspectFill: return .scaleAspectFill default: return .scaleToFill } } }
22.040404
101
0.510999
91b0ab3d1daadcf80ed4906aa5f4bd304139821a
2,010
// // ViewController.swift // TagViewSample // // Created by JaN on 2017/7/5. // Copyright © 2017年 givingjan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var m_tagViewSingle: SMTagView! @IBOutlet var m_tagViewMultiple: SMTagView! @IBOutlet var m_btnChange: UIButton! var m_bIsMultiple : Bool = true var tags : [String] = ["咖啡Q","聰明奶茶","笑笑乒乓","下雨天的紅茶","明天的綠茶","笨豆漿","過期的茶葉蛋","雲端奶茶","國際的小鳳梨","黑胡椒樹皮"] // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.initView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK:Init private func initMultiple() { self.m_tagViewMultiple.layer.cornerRadius = 15.0 self.m_tagViewMultiple.tagMainColor = UIColor.orange self.m_tagViewMultiple.setTagForMultiple(title: "選幾個喜歡的吧 ! (多選)", tagType: .fill, tags: tags, maximumSelect: 3, minimumSelect: 2) { (indexes) in print("done:\(indexes)") } } private func initSingle() { self.m_tagViewSingle.layer.cornerRadius = 15.0 self.m_tagViewSingle.tagMainColor = UIColor.orange self.m_tagViewSingle.setTagForSingle(title: "你要選哪個呢 ? (單選)", tagType: .border, tags: tags) { (index) in print(index) } } private func initView() { initMultiple() initSingle() updateView() } private func updateView() { self.m_tagViewSingle.isHidden = self.m_bIsMultiple self.m_tagViewMultiple.isHidden = !self.m_bIsMultiple } @IBAction func handleChange(_ sender: Any) { self.m_bIsMultiple = !self.m_bIsMultiple let title = self.m_bIsMultiple == true ? "Change to Single" : "Change to Multiple" self.m_btnChange.setTitle(title, for: .normal) self.updateView() } }
28.714286
152
0.629851
1c6364771841e6e90a866e10162a33442fc0083f
743
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // HybridConnectionPropertiesProtocol is hybridConnection resource specific properties public protocol HybridConnectionPropertiesProtocol : Codable { var serviceBusNamespace: String? { get set } var relayName: String? { get set } var relayArmUri: String? { get set } var hostname: String? { get set } var port: Int32? { get set } var sendKeyName: String? { get set } var sendKeyValue: String? { get set } var serviceBusSuffix: String? { get set } }
43.705882
96
0.709287
39119b631ba71ad91ba069aefad5984f188590b5
753
import Foundation class EmojiMemoryGame { private(set) var model: MemoryGame<String> = EmojiMemoryGame.createMemoryGame() static func createMemoryGame() -> MemoryGame<String> { var emojis: Array<String> = ["👻","🎃","🕷","😈","💀","👽","☠️","👾"] while emojis.count > 5 { emojis.remove(at: emojis.firstIndex(of: emojis.randomElement()!)!) } return MemoryGame<String>(numberOfPairsOfCards: .random(in: 2...4)) { pairIndex in emojis[pairIndex]} } //MARK: -Access to the Model var cards: Array<MemoryGame<String>.Card> { return model.cards } //MARK: - Intent(s) func choose(card: MemoryGame<String>.Card) { model.choose(card: card) } }
27.888889
109
0.586985
bb4935f0aa193c1124ce0392007926c98bb7aace
1,820
// // EnterCommandTests.swift // UPNCalculatorTests // // Created by holgermayer on 13.12.19. // Copyright © 2019 holgermayer. All rights reserved. // import XCTest @testable import UPNCalculator class EnterCommandTests: XCTestCase { var engine : UPNEngine! var display : CalculatorDisplay! var testObject : EnterCommand! override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. engine = UPNEngine() display = CalculatorDisplay() testObject = EnterCommand(calculatorEngine: engine, display: display) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testEnterNumberToStack() { let digit1Command = DigitDotCommand(calculatorEngine: engine, display: display, token: "1") let digit2Command = DigitDotCommand(calculatorEngine: engine, display: display, token: "2") let digit3Command = DigitDotCommand(calculatorEngine: engine, display: display, token: "3") let dotCommand = DigitDotCommand(calculatorEngine: engine, display: display, token: ".") let _ = digit1Command.execute() let _ = digit2Command.execute() let _ = digit3Command.execute() let _ = dotCommand.execute() let _ = digit1Command.execute() let _ = digit2Command.execute() XCTAssertFalse(display.isPushed) XCTAssertEqual(engine.top,123.12) let _ = testObject.execute() XCTAssertTrue(display.isPushed) guard let result = engine.top else { XCTFail() return } XCTAssertTrue(result == 123.12) } }
28
111
0.642308
75760f7ce8901999036a51f35658b7f51d0a8ce3
8,379
// // CommonPoolCell.swift // Cosmostation // // Created by 정용주 on 2021/09/06. // Copyright © 2021 wannabit. All rights reserved. // import UIKit class CommonPoolCell: UITableViewCell { @IBOutlet weak var poolPairLabel: UILabel! @IBOutlet weak var totalLiquidityValueLabel: UILabel! @IBOutlet weak var liquidity1AmountLabel: UILabel! @IBOutlet weak var liquidity1DenomLabel: UILabel! @IBOutlet weak var liquidity2AmountLabel: UILabel! @IBOutlet weak var liquidity2DenomLabel: UILabel! @IBOutlet weak var availableCoin0AmountLabel: UILabel! @IBOutlet weak var availableCoin0DenomLabel: UILabel! @IBOutlet weak var availableCoin1AmountLabel: UILabel! @IBOutlet weak var availableCoin1DenomLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none liquidity1AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote) liquidity2AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote) availableCoin0AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote) availableCoin1AmountLabel.font = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: Font_13_footnote) } func onBindOsmoPoolView(_ pool: Osmosis_Gamm_Poolmodels_Balancer_Pool) { //dp pool info let coin0 = Coin.init(pool.poolAssets[0].token.denom, pool.poolAssets[0].token.amount) let coin1 = Coin.init(pool.poolAssets[1].token.denom, pool.poolAssets[1].token.amount) let coin0BaseDenom = BaseData.instance.getBaseDenom(coin0.denom) let coin1BaseDenom = BaseData.instance.getBaseDenom(coin1.denom) let coin0Symbol = WUtils.getOsmosisTokenName(coin0.denom) let coin1Symbol = WUtils.getOsmosisTokenName(coin1.denom) let coin0Decimal = WUtils.getOsmosisCoinDecimal(coin0.denom) let coin1Decimal = WUtils.getOsmosisCoinDecimal(coin1.denom) poolPairLabel.text = "#" + String(pool.id) + " " + coin0Symbol + " : " + coin1Symbol let coin0Value = WUtils.usdValue(coin0BaseDenom, NSDecimalNumber.init(string: coin0.amount), coin0Decimal) let coin1Value = WUtils.usdValue(coin1BaseDenom, NSDecimalNumber.init(string: coin1.amount), coin1Decimal) let poolValue = coin0Value.adding(coin1Value) let nf = WUtils.getNumberFormatter(2) let formatted = "$ " + nf.string(from: poolValue)! totalLiquidityValueLabel.attributedText = WUtils.getDpAttributedString(formatted, 2, totalLiquidityValueLabel.font) WUtils.DpOsmosisTokenName(liquidity1DenomLabel, coin0.denom) liquidity1DenomLabel.adjustsFontSizeToFitWidth = true WUtils.DpOsmosisTokenName(liquidity2DenomLabel, coin1.denom) liquidity2DenomLabel.adjustsFontSizeToFitWidth = true liquidity1AmountLabel.attributedText = WUtils.displayAmount2(coin0.amount, liquidity1AmountLabel.font, coin0Decimal, 6) liquidity2AmountLabel.attributedText = WUtils.displayAmount2(coin1.amount, liquidity2AmountLabel.font, coin1Decimal, 6) //dp available let availableCoin0 = BaseData.instance.getAvailable_gRPC(coin0.denom) let availableCoin1 = BaseData.instance.getAvailable_gRPC(coin1.denom) WUtils.DpOsmosisTokenName(availableCoin0DenomLabel, coin0.denom) availableCoin0DenomLabel.adjustsFontSizeToFitWidth = true WUtils.DpOsmosisTokenName(availableCoin1DenomLabel, coin1.denom) availableCoin1DenomLabel.adjustsFontSizeToFitWidth = true availableCoin0AmountLabel.attributedText = WUtils.displayAmount2(availableCoin0, availableCoin0AmountLabel.font, coin0Decimal, 6) availableCoin1AmountLabel.attributedText = WUtils.displayAmount2(availableCoin1, availableCoin1AmountLabel.font, coin1Decimal, 6) } func onBindKavaPoolView(_ pool: Kava_Swap_V1beta1_PoolResponse) { //dp pool info let nf = WUtils.getNumberFormatter(2) let coin0 = pool.coins[0] let coin1 = pool.coins[1] let coin0Decimal = WUtils.getKavaCoinDecimal(coin0.denom) let coin1Decimal = WUtils.getKavaCoinDecimal(coin1.denom) let coin0price = WUtils.getKavaOraclePriceWithDenom(coin0.denom) let coin1price = WUtils.getKavaOraclePriceWithDenom(coin1.denom) let coin0Value = NSDecimalNumber.init(string: coin0.amount).multiplying(by: coin0price).multiplying(byPowerOf10: -coin0Decimal, withBehavior: WUtils.handler2) let coin1Value = NSDecimalNumber.init(string: coin1.amount).multiplying(by: coin1price).multiplying(byPowerOf10: -coin1Decimal, withBehavior: WUtils.handler2) poolPairLabel.text = WUtils.getKavaTokenName(coin0.denom).uppercased() + " : " + WUtils.getKavaTokenName(coin1.denom).uppercased() let poolValue = coin0Value.adding(coin1Value) let poolValueFormatted = "$ " + nf.string(from: poolValue)! totalLiquidityValueLabel.attributedText = WUtils.getDpAttributedString(poolValueFormatted, 2, totalLiquidityValueLabel.font) WUtils.DpKavaTokenName(liquidity1DenomLabel, coin0.denom) WUtils.DpKavaTokenName(liquidity2DenomLabel, coin1.denom) liquidity1AmountLabel.attributedText = WUtils.displayAmount2(coin0.amount, liquidity1AmountLabel.font, coin0Decimal, 6) liquidity2AmountLabel.attributedText = WUtils.displayAmount2(coin1.amount, liquidity2AmountLabel.font, coin1Decimal, 6) //dp available let availableCoin0 = BaseData.instance.getAvailableAmount_gRPC(coin0.denom) let availableCoin1 = BaseData.instance.getAvailableAmount_gRPC(coin1.denom) WUtils.DpKavaTokenName(availableCoin0DenomLabel, coin0.denom) WUtils.DpKavaTokenName(availableCoin1DenomLabel, coin1.denom) availableCoin0AmountLabel.attributedText = WUtils.displayAmount2(availableCoin0.stringValue, availableCoin0AmountLabel.font, coin0Decimal, 6) availableCoin1AmountLabel.attributedText = WUtils.displayAmount2(availableCoin1.stringValue, availableCoin1AmountLabel.font, coin1Decimal, 6) } func onBindGdexPoolView(_ pool: Tendermint_Liquidity_V1beta1_Pool) { //dp pool info let nf = WUtils.getNumberFormatter(2) let coin0Denom = pool.reserveCoinDenoms[0] let coin1Denom = pool.reserveCoinDenoms[1] let coin0Amount = WUtils.getGdexLpAmount(pool.reserveAccountAddress, coin0Denom) let coin1Amount = WUtils.getGdexLpAmount(pool.reserveAccountAddress, coin1Denom) let coin0Decimal = WUtils.getCosmosCoinDecimal(coin0Denom) let coin1Decimal = WUtils.getCosmosCoinDecimal(coin1Denom) poolPairLabel.text = "#" + String(pool.id) + " " + WUtils.getCosmosTokenName(coin0Denom) + " : " + WUtils.getCosmosTokenName(coin1Denom) let poolValue = WUtils.getGdexPoolValue(pool) let poolValueFormatted = "$ " + nf.string(from: poolValue)! totalLiquidityValueLabel.attributedText = WUtils.getDpAttributedString(poolValueFormatted, 2, totalLiquidityValueLabel.font) WUtils.DpCosmosTokenName(liquidity1DenomLabel, coin0Denom) WUtils.DpCosmosTokenName(liquidity2DenomLabel, coin1Denom) liquidity1AmountLabel.attributedText = WUtils.displayAmount2(coin0Amount.stringValue, liquidity1AmountLabel.font, coin0Decimal, 6) liquidity2AmountLabel.attributedText = WUtils.displayAmount2(coin1Amount.stringValue, liquidity2AmountLabel.font, coin1Decimal, 6) //dp available let availableCoin0 = BaseData.instance.getAvailable_gRPC(coin0Denom) let availableCoin1 = BaseData.instance.getAvailable_gRPC(coin1Denom) WUtils.DpCosmosTokenName(availableCoin0DenomLabel, coin0Denom) availableCoin0DenomLabel.adjustsFontSizeToFitWidth = true WUtils.DpCosmosTokenName(availableCoin1DenomLabel, coin1Denom) availableCoin1DenomLabel.adjustsFontSizeToFitWidth = true availableCoin0AmountLabel.attributedText = WUtils.displayAmount2(availableCoin0, availableCoin0AmountLabel.font, coin0Decimal, 6) availableCoin1AmountLabel.attributedText = WUtils.displayAmount2(availableCoin1, availableCoin1AmountLabel.font, coin1Decimal, 6) } }
58.1875
166
0.748896
9155ff7a372b945544e09d48749215b369af4f05
1,739
// HEADS UP!: Auto-generated file, changes made directly here will be overwritten by code generators. import blend2d /// 2D matrix operation. public extension BLMatrix2DOp { /// Reset matrix to identity (argument ignored, should be nullptr). static let reset = BL_MATRIX2D_OP_RESET /// Assign (copy) the other matrix. static let assign = BL_MATRIX2D_OP_ASSIGN /// Translate the matrix by [x, y]. static let translate = BL_MATRIX2D_OP_TRANSLATE /// Scale the matrix by [x, y]. static let scale = BL_MATRIX2D_OP_SCALE /// Skew the matrix by [x, y]. static let skew = BL_MATRIX2D_OP_SKEW /// Rotate the matrix by the given angle about [0, 0]. static let rotate = BL_MATRIX2D_OP_ROTATE /// Rotate the matrix by the given angle about [x, y]. static let rotatePt = BL_MATRIX2D_OP_ROTATE_PT /// Transform this matrix by other `BLMatrix2D`. static let transform = BL_MATRIX2D_OP_TRANSFORM /// Post-translate the matrix by [x, y]. static let postTranslate = BL_MATRIX2D_OP_POST_TRANSLATE /// Post-scale the matrix by [x, y]. static let postScale = BL_MATRIX2D_OP_POST_SCALE /// Post-skew the matrix by [x, y]. static let postSkew = BL_MATRIX2D_OP_POST_SKEW /// Post-rotate the matrix about [0, 0]. static let postRotate = BL_MATRIX2D_OP_POST_ROTATE /// Post-rotate the matrix about a reference BLPoint. static let postRotatePt = BL_MATRIX2D_OP_POST_ROTATE_PT /// Post-transform this matrix by other `BLMatrix2D`. static let postTransform = BL_MATRIX2D_OP_POST_TRANSFORM /// Maximum value of `BLMatrix2DOp`. static let maxValue = BL_MATRIX2D_OP_MAX_VALUE }
33.442308
101
0.690052
766a852dfc8a69ef7923c7f999d6bf09b4d41ca5
1,068
// // QuizViewController.swift // ProjectZero // Copyright © 2016 Udacity. All rights reserved. // import UIKit import AVFoundation class QuizViewController: UIViewController, AVSpeechSynthesizerDelegate { @IBOutlet weak var flagButton1: UIButton! @IBOutlet weak var flagButton2: UIButton! @IBOutlet weak var flagButton3: UIButton! @IBOutlet weak var repeatPhraseButton: UIButton! var languageChoices = [Country]() var lastRandomLanguageID = -1 var selectedRow = -1 var correctButtonTag = -1 var currentState: QuizState = .NoQuestionUpYet var spokenText = "" var bcpCode = "" let speechSynth = AVSpeechSynthesizer() @IBAction func flagButtonPressed(sender: UIButton) { if sender.tag == correctButtonTag{ displayAlert("Correct", messageText: "Good choice!") }else{ displayAlert("Incorrect", messageText: "Nope. Try again!") } } }
15.257143
73
0.604869
3a8755c1eef19a18ed4bf9e872006d245d97bfd4
243
import Foundation public protocol SectionViewColorPalette: class { func colorting(section: UIView) func coloring(titleLabel: UILabel, with font: UIFont) func coloring(dot layer: CALayer) func coloring(shadow layer: CALayer) }
27
57
0.757202
5031310a185a1bb22184c47bd50c65fecc11d5d5
1,490
// // TouchViewController.swift // MetalReFresh_Example // // Created by 永田大祐 on 2017/11/29. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import MetalReFresh class TouchViewController: UIViewController { static var intCount = Int() var pull = PullToObject() var timer: Timer! var toucheSet : Set<UITouch>! override func viewDidLoad() { super.viewDidLoad() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { swipeMethod() toucheSet = touches } @objc private func update(tm: Timer) { timer.invalidate() pull.imageCount = TouchViewController.intCount pull.metalPosition(point: toucheSet.first!.location(in: self.view), view: self.view) } private func swipeMethod() { let directions: UISwipeGestureRecognizer.Direction = .up let gesture = UISwipeGestureRecognizer(target: self, action:#selector(handleSwipe(sender:))) gesture.direction = directions gesture.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(gesture) } @objc func handleSwipe(sender: UISwipeGestureRecognizer) { timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } }
29.215686
92
0.608054
296e5bd0d755db46a70c2331980cdafb9e91ee47
2,510
// // Presenter.swift // MVX Patterns In Swift // // Created by Yaroslav Voloshyn on 18/07/2017. // import Foundation protocol Presenter { func loadMoreItems() func startLoadPhoto(for index: Int, width: Int, height: Int) func stopLoadPhoto(for index: Int, width: Int, height: Int) } final class ConcretePresenter { fileprivate weak var view: PhotosView? fileprivate let picsumPhotos = PicsumPhotosManager() fileprivate var lastPageIndex: Int? fileprivate var photos: [(PicsumPhoto, Data?)] = [] fileprivate var isLoading = false { didSet { if isLoading { view?.showNetworkActivityIndicator() } else { view?.hideNetworkActivityIndicator() } } } init(view: PhotosView) { self.view = view } fileprivate func updateView() { let data: [(title: String, data: Data?)] = photos.map { (photo) -> (title: String, data: Data?) in return (title: photo.0.author, data: photo.1) } view?.updateView(with: data) } } extension ConcretePresenter: Presenter { func loadMoreItems() { guard !isLoading else { return } var pageIndex = 1 if let lastPageIndex = lastPageIndex { pageIndex = lastPageIndex + 1 } loadItems(with: pageIndex) } private func loadItems(with pageIndex: Int) { isLoading = true picsumPhotos.getPhotos(pageIndex) { [weak self] (photos, error) in defer { self?.isLoading = false } photos?.forEach { self?.photos.append(($0, nil)) } self?.lastPageIndex = pageIndex self?.updateView() } } } // MARK: - Load Photo extension ConcretePresenter { func stopLoadPhoto(for index: Int, width: Int, height: Int) { let url = photos[index].0.getResizedImageURL(width: width, height: height) DataLoader.shared.stopDownload(with: url) } func startLoadPhoto(for index: Int, width: Int, height: Int) { let url = photos[index].0.getResizedImageURL(width: width, height: height) DataLoader.shared.downloadData(with: url) { [weak self] (data) in self?.photos[index].1 = data if let photo = self?.photos[index] { self?.view?.updateCell(at: index, with: (title: photo.0.author, data: photo.1)) } } } }
25.353535
106
0.578884
62118c8727d6bf3762711d0825624cac0d051ed3
1,877
// // TTARefresherFooter.swift // Pods // // Created by TobyoTenma on 07/05/2017. // // import UIKit open class TTARefresherFooter: TTARefresherComponent { /// If true, the footer will be shown when there are data, otherwise, footer will be hidden public var isAutoHidden = false public var ignoredScrollViewContentInsetBottom: CGFloat = 0 public init(refreshingHandler: @escaping TTARefresherComponentRefreshingHandler) { super.init(frame: .zero) self.refreshingHandler = refreshingHandler } public init(refreshingTarget aTarget: AnyObject, refreshingAction anAction: Selector) { super.init(frame: .zero) setRefreshingTarget(aTarget: aTarget, anAction: anAction) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Override Methods extension TTARefresherFooter { override open func prepare() { super.prepare() bounds.size.height = TTARefresherFrameConst.footerHeight } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) guard newSuperview != nil, let scrollView = scrollView else { return } if scrollView.isKind(of: UITableView.self) || scrollView.isKind(of: UICollectionView.self) { scrollView.ttaRefresher.reloadDataHandler = { [weak self] (totalDataCount) in guard let `self` = self, self.isAutoHidden else { return } self.isHidden = totalDataCount == 0 } } } } // MARK: - Public Methods extension TTARefresherFooter { public func endRefreshWithNoMoreData() { state = .noMoreData } public func resetNoMoreData() { state = .idle } }
27.202899
100
0.64731
8a2a660a3a38b9bfb1f8e44347f1affb8c1051a0
11,030
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Amplify import Combine import Foundation import AWSPluginsCore /// Submits outgoing mutation events to the provisioned API @available(iOS 13.0, *) protocol OutgoingMutationQueueBehavior: class { func pauseSyncingToCloud() func startSyncingToCloud(api: APICategoryGraphQLBehavior, mutationEventPublisher: MutationEventPublisher) var publisher: AnyPublisher<MutationEvent, Never> { get } } @available(iOS 13.0, *) final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { private let stateMachine: StateMachine<State, Action> private var stateMachineSink: AnyCancellable? private let operationQueue: OperationQueue private let workQueue = DispatchQueue(label: "com.amazonaws.OutgoingMutationOperationQueue", target: DispatchQueue.global()) private weak var api: APICategoryGraphQLBehavior? private var subscription: Subscription? private let dataStoreConfiguration: DataStoreConfiguration private let storageAdapter: StorageEngineAdapter private let outgoingMutationQueueSubject: PassthroughSubject<MutationEvent, Never> public var publisher: AnyPublisher<MutationEvent, Never> { return outgoingMutationQueueSubject.eraseToAnyPublisher() } init(_ stateMachine: StateMachine<State, Action>? = nil, storageAdapter: StorageEngineAdapter, dataStoreConfiguration: DataStoreConfiguration) { self.storageAdapter = storageAdapter self.dataStoreConfiguration = dataStoreConfiguration let operationQueue = OperationQueue() operationQueue.name = "com.amazonaws.OutgoingMutationOperationQueue" operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true self.operationQueue = operationQueue self.stateMachine = stateMachine ?? StateMachine(initialState: .notInitialized, resolver: OutgoingMutationQueue.Resolver.resolve(currentState:action:)) self.outgoingMutationQueueSubject = PassthroughSubject<MutationEvent, Never>() self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in guard let self = self else { return } self.log.verbose("New state: \(newState)") self.workQueue.async { self.respond(to: newState) } } log.verbose("Initialized") self.stateMachine.notify(action: .initialized) } // MARK: - Public API func startSyncingToCloud(api: APICategoryGraphQLBehavior, mutationEventPublisher: MutationEventPublisher) { log.verbose(#function) stateMachine.notify(action: .receivedStart(api, mutationEventPublisher)) } func cancel() { log.verbose(#function) // Techncially this should be in a "cancelling" responder, but it's simpler to cancel here and move straight // to .finished. If in the future we need to add more work to the teardown state, move it to a separate method. operationQueue.cancelAllOperations() stateMachine.notify(action: .receivedCancel) } func pauseSyncingToCloud() { log.verbose(#function) operationQueue.isSuspended = true } // MARK: - Responders /// Listens to incoming state changes and invokes the appropriate asynchronous methods in response. private func respond(to newState: State) { log.verbose("\(#function): \(newState)") switch newState { case .starting(let api, let mutationEventPublisher): start(api: api, mutationEventPublisher: mutationEventPublisher) case .requestingEvent: requestEvent() case .resumingMutationQueue: resumeSyncingToCloud() case .inError(let error): // Maybe we have to notify the Hub? log.error(error: error) case .notInitialized, .notStarted, .finished, .waitingForEventToProcess, .resumed: break } } func resumeSyncingToCloud() { log.verbose(#function) operationQueue.isSuspended = false stateMachine.notify(action: .resumedSyncingToCloud) } /// Responder method for `starting`. Starts the operation queue and subscribes to the publisher. Return actions: /// - started private func start(api: APICategoryGraphQLBehavior, mutationEventPublisher: MutationEventPublisher) { log.verbose(#function) self.api = api operationQueue.isSuspended = false // State machine notification to ".receivedSubscription" will be handled in `receive(subscription:)` mutationEventPublisher.publisher.subscribe(self) } // MARK: - Event loop processing /// Responder method for `requestingEvent`. Requests an event from the subscription, and lets the subscription /// handler enqueue it. Return actions: /// - errored private func requestEvent() { log.verbose(#function) guard let subscription = subscription else { let dataStoreError = DataStoreError.unknown( "No subscription when requesting event", """ The outgoing mutation queue attempted to request event without an active subscription. \(AmplifyErrorMessages.reportBugToAWS()) """ ) stateMachine.notify(action: .errored(dataStoreError)) return } subscription.request(.max(1)) } /// Invoked when the subscription receives an event, not as part of the state machine transition private func enqueue(_ mutationEvent: MutationEvent) { log.verbose(#function) guard let api = api else { let dataStoreError = DataStoreError.configuration( "API is unexpectedly nil", """ The reference to api has been released while an ongoing mutation was being processed. \(AmplifyErrorMessages.reportBugToAWS()) """ ) stateMachine.notify(action: .errored(dataStoreError)) return } let syncMutationToCloudOperation = SyncMutationToCloudOperation( mutationEvent: mutationEvent, api: api) { result in self.log.verbose( "[SyncMutationToCloudOperation] mutationEvent finished: \(mutationEvent.id); result: \(result)") self.processSyncMutationToCloudResult(result, mutationEvent: mutationEvent, api: api) } operationQueue.addOperation(syncMutationToCloudOperation) stateMachine.notify(action: .enqueuedEvent) } private func processSyncMutationToCloudResult(_ result: GraphQLOperation<MutationSync<AnyModel>>.OperationResult, mutationEvent: MutationEvent, api: APICategoryGraphQLBehavior) { if case let .success(graphQLResponse) = result, case let .failure(graphQLResponseError) = graphQLResponse { processMutationErrorFromCloud(mutationEvent: mutationEvent, api: api, apiError: nil, graphQLResponseError: graphQLResponseError) } else if case let .failure(apiError) = result { processMutationErrorFromCloud(mutationEvent: mutationEvent, api: api, apiError: apiError, graphQLResponseError: nil) } else { completeProcessingEvent(mutationEvent) } } private func processMutationErrorFromCloud(mutationEvent: MutationEvent, api: APICategoryGraphQLBehavior, apiError: APIError?, graphQLResponseError: GraphQLResponseError<MutationSync<AnyModel>>?) { let processMutationErrorFromCloudOperation = ProcessMutationErrorFromCloudOperation( dataStoreConfiguration: dataStoreConfiguration, mutationEvent: mutationEvent, api: api, storageAdapter: storageAdapter, graphQLResponseError: graphQLResponseError, apiError: apiError) { result in self.log.verbose("[ProcessMutationErrorFromCloudOperation] result: \(result)") if case let .success(mutationEventOptional) = result, let outgoingMutationEvent = mutationEventOptional { self.outgoingMutationQueueSubject.send(outgoingMutationEvent) } self.completeProcessingEvent(mutationEvent) } operationQueue.addOperation(processMutationErrorFromCloudOperation) } private func completeProcessingEvent(_ mutationEvent: MutationEvent) { // This doesn't belong here--need to add a `delete` API to the MutationEventSource and pass a // reference into the mutation queue. Amplify.DataStore.delete(mutationEvent) { result in switch result { case .failure(let dataStoreError): self.log.verbose("mutationEvent failed to delete: error: \(dataStoreError)") case .success: self.log.verbose("mutationEvent deleted successfully") } self.stateMachine.notify(action: .processedEvent) } } } @available(iOS 13.0, *) extension OutgoingMutationQueue: Subscriber { typealias Input = MutationEvent typealias Failure = DataStoreError func receive(subscription: Subscription) { log.verbose(#function) // Technically, saving the subscription should probably be done in a separate method, but it seems overkill // for a lightweight operation, not to mention that the transition from "receiving subscription" to "receiving // event" happens so quickly that state management becomes difficult. self.subscription = subscription stateMachine.notify(action: .receivedSubscription) } func receive(_ mutationEvent: MutationEvent) -> Subscribers.Demand { log.verbose(#function) enqueue(mutationEvent) return .none } // TODO: Resolve with an appropriate state machine notification func receive(completion: Subscribers.Completion<DataStoreError>) { log.verbose(#function) subscription?.cancel() } } @available(iOS 13.0, *) extension OutgoingMutationQueue: DefaultLogger { }
39.53405
119
0.635993
7596bf904fcc79cf103f9ec2af4df6084fc7f7ee
5,706
import UIKit class RightAudioMessageCell: AudioMessageCell { override func create() { super.create() bubbleView.setBackgroundImage(configuration.rightAudioMessageBubbleImageNormal, for: .normal) bubbleView.setBackgroundImage(configuration.rightAudioMessageBubbleImagePressed, for: .selected) bubbleView.setBackgroundImage(configuration.rightAudioMessageBubbleImagePressed, for: .highlighted) animationView.image = configuration.rightAudioMessageWave animationView.animationImages = configuration.rightAudioMessageWaves contentView.addConstraints([ NSLayoutConstraint(item: timeView, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: avatarView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -configuration.messagePaddingHorizontal), NSLayoutConstraint(item: avatarView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: configuration.userAvatarWidth), NSLayoutConstraint(item: avatarView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: configuration.userAvatarHeight), NSLayoutConstraint(item: bubbleView, attribute: .right, relatedBy: .equal, toItem: avatarView, attribute: .left, multiplier: 1, constant: -configuration.rightAudioMessageMarginRight), NSLayoutConstraint(item: bubbleView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: configuration.rightAudioMessageBubbleHeight), NSLayoutConstraint(item: animationView, attribute: .centerY, relatedBy: .equal, toItem: bubbleView, attribute: .centerY, multiplier: 1, constant: 0), NSLayoutConstraint(item: animationView, attribute: .right, relatedBy: .equal, toItem: bubbleView, attribute: .right, multiplier: 1, constant: -configuration.rightAudioMessageWaveMarginRight), NSLayoutConstraint(item: loadingView, attribute: .centerY, relatedBy: .equal, toItem: bubbleView, attribute: .centerY, multiplier: 1, constant: 0), NSLayoutConstraint(item: loadingView, attribute: .right, relatedBy: .equal, toItem: bubbleView, attribute: .right, multiplier: 1, constant: -configuration.rightAudioMessageWaveMarginRight), NSLayoutConstraint(item: unitView, attribute: .bottom, relatedBy: .equal, toItem: bubbleView, attribute: .bottom, multiplier: 1, constant: -configuration.audioMessageUnitBottom), NSLayoutConstraint(item: unitView, attribute: .right, relatedBy: .equal, toItem: bubbleView, attribute: .left, multiplier: 1, constant: -configuration.audioMessageDurationSpacing), NSLayoutConstraint(item: durationView, attribute: .bottom, relatedBy: .equal, toItem: bubbleView, attribute: .bottom, multiplier: 1, constant: -configuration.audioMessageDurationBottom), NSLayoutConstraint(item: durationView, attribute: .right, relatedBy: .equal, toItem: unitView, attribute: .left, multiplier: 1, constant: -configuration.audioMessageUnitSpacing), NSLayoutConstraint(item: spinnerView, attribute: .right, relatedBy: .equal, toItem: bubbleView, attribute: .left, multiplier: 1, constant: -configuration.rightStatusViewMarginRight), NSLayoutConstraint(item: spinnerView, attribute: .bottom, relatedBy: .equal, toItem: bubbleView, attribute: .bottom, multiplier: 1, constant: -configuration.rightStatusViewMarginBottom), NSLayoutConstraint(item: failureView, attribute: .right, relatedBy: .equal, toItem: bubbleView, attribute: .left, multiplier: 1, constant: -configuration.rightStatusViewMarginRight), NSLayoutConstraint(item: failureView, attribute: .bottom, relatedBy: .equal, toItem: bubbleView, attribute: .bottom, multiplier: 1, constant: -configuration.rightStatusViewMarginBottom), ]) if configuration.rightUserNameVisible { nameView.font = configuration.rightUserNameTextFont nameView.textColor = configuration.rightUserNameTextColor nameView.textAlignment = .right contentView.addSubview(nameView) addClickHandler(view: nameView, selector: #selector(onUserNameClick)) contentView.addConstraints([ NSLayoutConstraint(item: nameView, attribute: .top, relatedBy: .equal, toItem: avatarView, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: nameView, attribute: .right, relatedBy: .equal, toItem: avatarView, attribute: .left, multiplier: 1, constant: -configuration.rightUserNameMarginRight), NSLayoutConstraint(item: nameView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: getContentMaxWidth()), NSLayoutConstraint(item: bubbleView, attribute: .top, relatedBy: .equal, toItem: nameView, attribute: .bottom, multiplier: 1, constant: configuration.rightUserNameMarginBottom), ]) } else { contentView.addConstraints([ NSLayoutConstraint(item: bubbleView, attribute: .top, relatedBy: .equal, toItem: avatarView, attribute: .top, multiplier: 1, constant: 0), ]) } } }
72.227848
203
0.691553
1cd1afebefdef2638a2946fc5c23fb20483dfb07
369
public enum WktStepTarget : UInt8 { case Speed = 0 case HeartRate = 1 case Open = 2 case Cadence = 3 case Power = 4 case Grade = 5 case Resistance = 6 case Power3s = 7 case Power10s = 8 case Power30s = 9 case PowerLap = 10 case SwimStroke = 11 case SpeedLap = 12 case HeartRateLap = 13 case Invalid = 0xFF }
19.421053
35
0.604336
f73ad8fb85f7efc96c38cb2e3002f313ef161a9a
4,585
// // Piece.swift // Pods // // Created by Steve Barnegren on 04/09/2016. // // import Foundation public enum Color: String { case white = "White" case black = "Black" public var opposite: Color { return (self == .white) ? .black : .white } public var string: String { return rawValue.lowercased() } public var stringWithCapital: String { return rawValue } } public struct Piece: Equatable { public enum PieceType: Int { case pawn case rook case knight case bishop case queen case king var value: Double { switch self { case .pawn: return 1 case .rook: return 5 case .knight: return 3 case .bishop: return 3 case .queen: return 9 case .king: return 0 // King is always treated as a unique case } } static func possiblePawnPromotionResultingTypes() -> [PieceType] { return [.queen, .knight, .rook, .bishop] } } public let type: PieceType public let color: Color public internal(set) var tag: Int! public internal(set) var hasMoved = false public internal(set) var canBeTakenByEnPassant = false public internal(set) var location = BoardLocation(index: 0) var movement: PieceMovement! { return PieceMovement.pieceMovement(for: self.type) } var withOppositeColor: Piece { return Piece(type: type, color: color.opposite) } var value: Double { return type.value } public init(type: PieceType, color: Color, tag: Int = 0) { self.type = type self.color = color self.tag = tag } func byChangingType(newType: PieceType) -> Piece { let piece = Piece(type: newType, color: color, tag: tag) return piece } func isSameTypeAndColor(asPiece other: Piece) -> Bool { if self.type == other.type && self.color == other.color { return true } else { return false } } } public func == (left: Piece, right: Piece) -> Bool { if left.type == right.type && left.color == right.color && left.tag == right.tag && left .hasMoved == right.hasMoved && left.canBeTakenByEnPassant == right.canBeTakenByEnPassant && left.location == right.location { return true } else { return false } } extension Piece: DictionaryRepresentable { private struct Keys { static let type = "type" static let color = "color" static let tag = "tag" static let hasMoved = "hasMoved" static let canBeTakenByEnPassant = "canBeTakenByEnPassant" static let location = "location" } init?(dictionary: [String: Any]) { // Type if let raw = dictionary[Keys.type] as? Int, let type = PieceType(rawValue: raw) { self.type = type } else { return nil } // Color if let raw = dictionary[Keys.color] as? String, let color = Color(rawValue: raw) { self.color = color } else { return nil } // Tag if let tag = dictionary[Keys.tag] as? Int { self.tag = tag } // Has Moved if let hasMoved = dictionary[Keys.hasMoved] as? Bool { self.hasMoved = hasMoved } else { return nil } // Can be taken by en passent if let canBeTakenByEnPassent = dictionary[Keys.canBeTakenByEnPassant] as? Bool { self.canBeTakenByEnPassant = canBeTakenByEnPassent } else { return nil } // Location if let dict = dictionary[Keys.location] as? [String: Any], let location = BoardLocation(dictionary: dict) { self.location = location } else { return nil } } var dictionaryRepresentation: [String: Any] { var dictionary = [String: Any]() dictionary[Keys.type] = type.rawValue dictionary[Keys.color] = color.rawValue if let tag = self.tag { dictionary[Keys.tag] = tag } dictionary[Keys.hasMoved] = hasMoved dictionary[Keys.canBeTakenByEnPassant] = canBeTakenByEnPassant dictionary[Keys.location] = location.dictionaryRepresentation return dictionary } }
26.2
115
0.551581
0e85c70370206c2a568b8e8ee21f27415ea6c0ee
2,571
// // SettingsTableViewController.swift // exampleWindow // // Created by Remi Robert on 18/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { @IBOutlet weak var switchResetLogs: UISwitch! @IBOutlet weak var switchOverridePrint: UISwitch! @IBOutlet weak var switchDisplayInfoFile: UISwitch! @IBOutlet weak var switchDisplayDate: UISwitch! @IBOutlet weak var switchNetworkEnable: UISwitch! @IBOutlet weak var imageViewLogo: UIImageView! @IBAction func valueDidChange(_ sender: UISwitch) { let tag = sender.tag switch tag { case 0: LogsSettings.shared.resetLogsStart = sender.isOn case 1: LogsSettings.shared.overridePrint = sender.isOn case 2: LogsSettings.shared.fileInfo = sender.isOn LogNotificationApp.settingsChanged.post(Void()) case 3: LogsSettings.shared.date = sender.isOn LogNotificationApp.settingsChanged.post(Void()) case 4: LogsSettings.shared.network = sender.isOn if LogsSettings.shared.network { LoggerNetwork.register() } else { LoggerNetwork.unregister() } default: break } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "logo", in: Bundle(for: LogHeadView.self), compatibleWith: nil) imageViewLogo.image = image?.withRenderingMode(.alwaysTemplate) imageViewLogo.tintColor = Color.mainGreen switchDisplayInfoFile.onTintColor = Color.mainGreen switchOverridePrint.onTintColor = Color.mainGreen switchResetLogs.onTintColor = Color.mainGreen switchDisplayDate.onTintColor = Color.mainGreen switchNetworkEnable.onTintColor = Color.mainGreen UIApplication.shared.statusBarStyle = .lightContent setNeedsStatusBarAppearanceUpdate() switchOverridePrint.tag = 1 switchDisplayInfoFile.tag = 2 switchDisplayDate.tag = 3 switchNetworkEnable.tag = 4 switchResetLogs.isOn = LogsSettings.shared.resetLogsStart switchOverridePrint.isOn = LogsSettings.shared.overridePrint switchDisplayInfoFile.isOn = LogsSettings.shared.fileInfo switchDisplayDate.isOn = LogsSettings.shared.date switchNetworkEnable.isOn = LogsSettings.shared.network } }
34.743243
98
0.686503
e8cc4963148f5845c6452c48d1634644f768bd34
254
// // Entity.swift // VIPER // // Created by Eugenio Barquín on 28/9/17. // Copyright © 2017 Eugenio Barquín. All rights reserved. // import Foundation class Persona { var nombre: String? var apellido: String? init() { } }
14.111111
58
0.606299
2887aae436a59e148de9397a9a14657cdce91add
794
// // Gib.swift // StudyTool3 // // Created by 陈为 on 9/19/15. // Copyright © 2015 David Chen. All rights reserved. // import UIKit import Foundation func ShowAlertMessage (parrent:UIViewController, title:String, message:String) { let alert = UIAlertController (title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(okAction) parrent.presentViewController(alert, animated: true, completion: nil) } class user { var username: String, password: String init () { username = "" password = "" } init (uname: String, pword: String) { username = uname password = pword } } var me: user = user()
26.466667
113
0.673804
460022509beb6aa473346fb9c3cbadaf4bf5c21a
226
// // WeSplitApp.swift // WeSplit // // Created by Carlos David on 07/08/2020. // import SwiftUI @main struct WeSplitApp: App { var body: some Scene { WindowGroup { ContentView() } } }
12.555556
42
0.557522
1e4cd0db655d72a313f0fe0dbe1369e99fc2740c
2,763
// // NetatmoStationProvider.swift // netatmoclient // // Created by Thomas Kluge on 04.10.15. // Copyright © 2015 kSquare.de. All rights reserved. // import Foundation import CoreData struct NetatmoStation: Equatable { var id: String var stationName: String! var type: String! var lastUpgrade : Date! var firmware : Int! var moduleIds : Array<String> = [] var lastStatusStore : Date = Date() } func ==(lhs: NetatmoStation, rhs: NetatmoStation) -> Bool { return lhs.id == rhs.id } extension NetatmoStation { init(managedObject : NSManagedObject) { self.id = managedObject.value(forKey: "stationid") as! String self.stationName = managedObject.value(forKey: "stationname") as! String self.type = managedObject.value(forKey: "stationtype") as! String } var measurementTypes : [NetatmoMeasureType] { switch self.type { case "NAMain": return [.Temperature,.CO2,.Humidity,.Pressure,.Noise] case "NAModule1","NAModule4": return [.Temperature,.Humidity] case "NAModule3": return [.Rain] case "NAModule2": return [.WindStrength,.WindAngle] default: return [] } } } class NetatmoStationProvider { fileprivate let coreDataStore: CoreDataStore! init(coreDataStore : CoreDataStore?) { if (coreDataStore != nil) { self.coreDataStore = coreDataStore } else { self.coreDataStore = CoreDataStore() } } func save() { try! coreDataStore.managedObjectContext.save() } func stations()->Array<NetatmoStation> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Station") fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] return results.map{NetatmoStation(managedObject: $0 )} } func createStation(_ id: String, name: String, type : String)->NSManagedObject { let newStation = NSManagedObject(entity: coreDataStore.managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName["Station"]!, insertInto: coreDataStore.managedObjectContext) newStation.setValue(id, forKey: "stationid") newStation.setValue(name, forKey: "stationname") newStation.setValue(type, forKey: "stationtype") try! coreDataStore.managedObjectContext.save() return newStation } func getStationWithId(_ id: String)->NSManagedObject? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Station") fetchRequest.predicate = NSPredicate(format: "stationid == %@", argumentArray: [id]) fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject] return results.first } }
28.78125
202
0.707202
e03f5504228866ed6d3c3dfc75e6dc7ce5cc5fae
11,994
// // TMURLSessionTests.swift // Orangina // // Created by Kenny Ackerson on 5/24/15. // Copyright (c) 2015 Tumblr. All rights reserved. // import Foundation import TMTumblrSDK import XCTest final class TMURLSessionTests: TMBaseTestCase { let URLSessionManager = TMURLSession(configuration: URLSessionConfiguration.default, applicationCredentials: TMAPIApplicationCredentials(consumerKey: "kenny", consumerSecret: "paul"), userCredentials: TMAPIUserCredentials(token: "token'", tokenSecret: "ht")) static func baseURLString() -> String { return "https://api.tumblr.com/v2/" } let baseURL = URL(string: TMURLSessionTests.baseURLString()) func testURLSessionManagerInvalidation() { let token = "watch" let tokenSecret = "triple" NotificationCenter.default.post(name: Notification.Name(rawValue: TMURLSessionInvalidateApplicationCredentialsNotificationKey), object: TMAPIUserCredentials(token: token, tokenSecret: tokenSecret)) XCTAssert(URLSessionManager.canSignRequests()) let HTTPHeaders = [ "kenny": "is cool!", "try": "hi" ] NotificationCenter.default.post(name: Notification.Name(rawValue: TMURLSessionInvalidateHTTPHeadersNotificationKey), object: HTTPHeaders) let task = URLSessionManager.task(with: TMHTTPRequest.init(urlString: "http://google.com", method: .GET)) { (data, response, error) in } XCTAssert((task.currentRequest?.allHTTPHeaderFields) ?? [String: String]() == HTTPHeaders) } func testGETRequest() { let request = signedRequest(.GET, path: "config", parameters: nil) XCTAssertNotNil(request.allHTTPHeaderFields?["Authorization"], "An authorization header should be included in the signed request.") XCTAssert(request.url?.absoluteString == "https://api.tumblr.com/v2/config", "The URL of the request should consist of the base URL + the path.") XCTAssert(request.httpMethod == "GET", "A TMHTTPRequestMethodGET should result in a GET request.") } func testGETRequestParameters() { let path = "config" let parameters = ["key": "some value", "foo": "bar"] let request = signedRequest(.GET, path: path, parameters: parameters as [String : AnyObject]?) let urlString = TMURLSessionTests.baseURLString() + "config?api_key=kenny&foo=bar&key=some%20value" XCTAssert(request.url == URL(string: urlString), "Parameters passed to a GET request should correctly pass then to the URL via NSURLComponents.") } func testPOSTRequest() { let request = signedRequest(.POST, path: "config", parameters: nil) XCTAssertNotNil(request.allHTTPHeaderFields?["Authorization"], "An authorization header should be included in the signed request.") XCTAssert(request.url?.absoluteString == "https://api.tumblr.com/v2/config", "The URL of the request should consist of the base URL + the path.") XCTAssert(request.httpMethod == "POST", "A TMHTTPRequestMethodPOST should result in a POST request.") } func testPOSTRequestBody() { let parameters = ["key": "some value", "foo": "bar"] let request = signedRequest(.POST, path: "config", parameters: parameters as [String : AnyObject]?) let data = "foo=bar&key=some%20value".data(using: String.Encoding.utf8, allowLossyConversion: false) XCTAssert(request.httpBody == data, "The body of the POST request should include all provided parameters.") } func testDELETERequest() { let request = signedRequest(.DELETE, path: "config", parameters: nil) XCTAssertNotNil(request.allHTTPHeaderFields?["Authorization"], "An authorization header should be included in the signed request.") XCTAssert(request.url?.absoluteString == "https://api.tumblr.com/v2/config", "The URL of the request should consist of the base URL + the path.") XCTAssert(request.httpMethod == "DELETE", "A TMHTTPRequestMethodDELETE should result in a DELETE request.") } func testDELETERequestParameters() { let path = "config" let parameters = ["key": "some value", "foo": "bar"] let request = signedRequest(.DELETE, path: path, parameters: parameters as [String : AnyObject]?) let urlString = TMURLSessionTests.baseURLString() + "config?api_key=kenny&foo=bar&key=some%20value" XCTAssert(request.url == URL(string: urlString), "Parameters passed to a DELETE request should correctly be encoded in the URL.") } func testUploadTaskIsRightType() { let request = TMHTTPRequest(urlString: "http://tumblr.com", method: .POST, additionalHeaders: nil, requestBody: TMMultipartRequestBody(filePaths: [], contentTypes: [], fileNames: [], parameters: ["": ""], keys: [], encodeJSONBody: false), isSigned: true, isUpload: true) let task = URLSessionManager.task(with: request) { (data, response, error) in } XCTAssert(task is URLSessionUploadTask) } func testUploadTaskIsRightTypeWhenAddingIncrementalHandler () { let request = TMHTTPRequest(urlString: "http://tumblr.com", method: .POST, additionalHeaders: nil, requestBody: TMMultipartRequestBody(filePaths: [], contentTypes: [], fileNames: [], parameters: ["": ""], keys: [], encodeJSONBody: false), isSigned: true, isUpload: true) let task = URLSessionManager.task(with: request, incrementalHandler: { (data, task) in }, progressHandler: { (progress, task) in }) { (data, response, error) in } XCTAssert(task is URLSessionUploadTask) } func testUploadTaskIsRightTypeWhenAddingIncrementalHandlerAndNoBody () { let request = TMHTTPRequest(urlString: "http://tumblr.com", method: .POST, additionalHeaders: nil, requestBody: nil, isSigned: true, isUpload: true) let task = URLSessionManager.task(with: request, incrementalHandler: { (data, task) in }, progressHandler: { (progress, task) in }) { (data, response, error) in } XCTAssert(task is URLSessionUploadTask) } func testUploadTaskIsRightTypeWithNoBody () { let request = TMHTTPRequest(urlString: "http://tumblr.com", method: .POST, additionalHeaders: nil, requestBody: nil, isSigned: true, isUpload: true) let task = URLSessionManager.task(with: request) { (data, urlresponse, error) in } XCTAssert(task is URLSessionUploadTask) } func testCopyingWithConfiguration() { if let config = (URLSessionConfiguration.default.copy() as? URLSessionConfiguration) { config.httpAdditionalHeaders = ["h": "ello"] let request = TMHTTPRequest(urlString: "http://tumblr.com", method: .GET, additionalHeaders: nil, requestBody: nil, isSigned: true, isUpload: false) let task = URLSessionManager.copy(withNewConfiguration: config).task(with: request, incrementalHandler: { (data, task) in }, progressHandler: { (progress, task) in }, completionHandler: { (data, response, error) in }) if let value = task.currentRequest?.allHTTPHeaderFields?["h"] { XCTAssert(value == "ello") } else { XCTFail() } } else { XCTFail() } } func testAdditionalHeadersWork() { let URLSessionManager = TMURLSession(configuration: URLSessionConfiguration.default, applicationCredentials: TMAPIApplicationCredentials(consumerKey: "kenny", consumerSecret: "paul"), userCredentials: TMAPIUserCredentials(token: "token", tokenSecret: "ht"), networkActivityManager: nil, sessionTaskUpdateDelegate: nil, sessionMetricsDelegate: nil, requestTransformer:nil, customURLSessionDataDelegate: nil, additionalHeaders: ["kenny": "ios"]) let task = URLSessionManager.task(with: TMHTTPRequest(urlString: "https://tumblr.com", method: .GET), completionHandler: { (data, response, error) in }) if let request = task.currentRequest, let value = request.allHTTPHeaderFields?["kenny"] { XCTAssert(value == "ios") } else { XCTFail() } } func testRequestTransformerCanUpdateHeaders() { class ExampleTransformer: TMRequestTransformer { func transform(_ request: TMRequest) -> TMRequest { return request.addingAdditionalHeaders(["tape": "tumblr"]) } } let transformer = ExampleTransformer() let URLSessionManager = TMURLSession(configuration: URLSessionConfiguration.default, applicationCredentials: TMAPIApplicationCredentials(consumerKey: "kenny", consumerSecret: "paul"), userCredentials: TMAPIUserCredentials(token: "token", tokenSecret: "ht"), networkActivityManager: nil, sessionTaskUpdateDelegate: nil, sessionMetricsDelegate: nil, requestTransformer: transformer, customURLSessionDataDelegate: nil, additionalHeaders: nil) let task = URLSessionManager.task(with: TMHTTPRequest(urlString: "https://tumblr.com", method: .GET), completionHandler: { (data, response, error) in }) guard let request = task.currentRequest, let headers = request.allHTTPHeaderFields else { XCTFail() return } XCTAssertEqual(headers, ["tape": "tumblr"]) } func testUploadBackgroundTaskWithSinglePartRequest() throws { let sessionManager = TMURLSession(configuration: URLSessionConfiguration.default, applicationCredentials: TMAPIApplicationCredentials(consumerKey: "kenny", consumerSecret: "paul"), userCredentials: TMAPIUserCredentials(token: "token", tokenSecret: "ht"), networkActivityManager: nil, sessionTaskUpdateDelegate: nil, sessionMetricsDelegate: nil, requestTransformer: nil, customURLSessionDataDelegate: nil, additionalHeaders: nil) let request = TMAPIRequest(baseURL: try XCTUnwrap(URL(string: "http://test.com")), method: .POST, path: "path", queryParameters: nil, requestBody: TMQueryEncodedRequestBody(queryDictionary: [String: AnyObject]()), additionalHeaders: nil) let task = sessionManager.backgroundUploadTask(with: request) XCTAssertNotNil(task) } // MARK: - fileprivate func signedRequest(_ method: TMHTTPRequestMethod, path: String, parameters: [String: AnyObject]?) -> URLRequest { guard let baseURL = baseURL else { return URLRequest(url: URL(fileURLWithPath: "")) } let APIRequest = TMAPIRequest(baseURL: baseURL, method: method, path: path, queryParameters: method == .GET || method == .DELETE ? parameters : nil, requestBody: method == .POST ? TMQueryEncodedRequestBody(queryDictionary: parameters ?? [String: AnyObject]()) : nil, additionalHeaders: nil) return URLSessionManager.paramaterizedRequest(from: APIRequest) } }
46.669261
451
0.624479
e531edb3464ad388870757a0028a2ab60cfa3f6e
4,286
import Foundation import LocalAuthentication enum BiometricType { case none case touchID case faceID } /// The available states of being logged in or not. enum AuthenticationState { case loggedin, loggedout } class BiometricIDAuth { let context = LAContext() var loginReason = "Logging in with Touch ID" /// The current authentication state. var state = AuthenticationState.loggedout { // Update the UI on a change. didSet { } } func biometricType() -> BiometricType { let _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) switch context.biometryType { case .none: return .none case .touchID: return .touchID case .faceID: return .faceID default: return .none } } func canEvaluateBiometricsPolicy() -> Bool { return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } func canEvaluateOwnerAuthenticationPolicy() -> Bool { return context.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) } func authenticateUser(completion: @escaping (Bool) -> Void) { guard canEvaluateBiometricsPolicy() else { self.authenticateDevicePassCode { (isSuccess) in completion(isSuccess) } return } context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: loginReason) { (success, evaluateError) in if success { DispatchQueue.main.async { // User authenticated successfully, take appropriate action completion(true) } } else { let message: String switch evaluateError { case LAError.authenticationFailed?: message = "There was a problem verifying your identity." case LAError.userCancel?: message = "You pressed cancel." case LAError.userFallback?: message = "You pressed password." case LAError.biometryNotAvailable?: message = "Face ID/Touch ID is not available." case LAError.biometryNotEnrolled?: message = "Face ID/Touch ID is not set up." case LAError.biometryLockout?: message = "Face ID/Touch ID is locked." default: message = "Face ID/Touch ID may not be configured" } FSLogInfo("\(message)") completion(false) } } } func authenticateDevicePassCode(completion: @escaping (Bool) -> Void) { guard canEvaluateOwnerAuthenticationPolicy() else { completion(false) return } // Get a fresh context for each login. If you use the same context on multiple attempts // (by commenting out the next line), then a previously successful authentication // causes the next policy evaluation to succeed without testing biometry again. // That's usually not what you want. context.localizedCancelTitle = "Enter Username/Password" let reason = "Log in to your account" context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) { (success, evaluateError) in if success { DispatchQueue.main.async { // User authenticated successfully, take appropriate action completion(true) } } else { let message: String switch evaluateError { case LAError.authenticationFailed?: message = "There was a problem verifying your identity." case LAError.userCancel?: message = "You pressed cancel." case LAError.userFallback?: message = "You pressed password." case LAError.passcodeNotSet?: message = "You have not set password." case LAError.notInteractive?: message = "Not interactive" default: message = "Face ID/Touch ID may not be configured" } completion(false) FSLogInfo("\(message)") } } } }
33.748031
128
0.597527
09c8f625f366079cce074cc6f9a842b51ff70815
1,505
// // CoreLocation+Extensions.swift // Locatics // // Created by Luke Smith on 07/09/2019. // Copyright © 2019 Luke Smith. All rights reserved. // import CoreLocation typealias Coordinate = CLLocationCoordinate2D extension CLLocationCoordinate2D: Equatable { public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude } } protocol LocationData { var coordinate: Coordinate { get } } extension CLLocation: LocationData {} protocol LocationProviderInterface { var delegate: CLLocationManagerDelegate? {get set} var allowsBackgroundLocationUpdates: Bool {get set} var pausesLocationUpdatesAutomatically: Bool {get set} var monitoredRegions: Set<CLRegion> {get} func requestLocation() func startMonitoringVisits() func startMonitoring(for region: CLRegion) func stopMonitoring(for region: CLRegion) } extension CLLocationManager: LocationProviderInterface {} protocol LocationProviderPermissionsInterface { var delegate: CLLocationManagerDelegate? {get set} static func authorizationStatus() -> CLAuthorizationStatus func requestAlwaysAuthorization() } extension CLLocationManager: LocationProviderPermissionsInterface {} protocol LocationGeocoderInterface { func reverseGeocodeLocation(_ location: CLLocation, completionHandler: @escaping CLGeocodeCompletionHandler) } extension CLGeocoder: LocationGeocoderInterface {}
27.87037
112
0.774751
333a18eae1cb7a8b947d08e22f7b925d716df755
4,498
// // CropViewController.swift // Athlee-ImagePicker // // Created by mac on 15/07/16. // Copyright © 2016 Athlee. All rights reserved. // import UIKit final class CropViewController: UIViewController, FloatingViewLayout, Cropable { // MARK: Outlets @IBOutlet weak var cropContainerView: UIView! // MARK: Properties var _parent: HolderViewController! var floatingView: UIView { return _parent.topContainer } // MARK: Cropable properties var cropView = UIScrollView() var childContainerView = UIView() var childView = UIImageView() var linesView = LinesView() var topOffset: CGFloat { guard let navBar = navigationController?.navigationBar else { return 0 } return !navBar.isHidden ? navBar.frame.height : 0 } lazy var delegate: CropableScrollViewDelegate<CropViewController> = { return CropableScrollViewDelegate(cropable: self) }() // MARK: FloatingViewLayout properties var animationCompletion: ((Bool) -> Void)? var overlayBlurringView: UIView! var topConstraint: NSLayoutConstraint { return _parent.topConstraint } var draggingZone: DraggingZone = .some(50) var visibleArea: CGFloat = 50 var previousPoint: CGPoint? var state: State { if topConstraint.constant == 0 { return .unfolded } else if topConstraint.constant + floatingView.frame.height == visibleArea { return .folded } else { return .moved } } var allowPanOutside = false // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() addCropable(to: cropContainerView) cropView.delegate = delegate } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateContent() } fileprivate var recognizersAdded = false override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateContent() if !recognizersAdded { recognizersAdded = true let pan = UIPanGestureRecognizer(target: self, action: #selector(CropViewController.didRecognizeMainPan(_:))) _parent.view.addGestureRecognizer(pan) pan.delegate = self let checkPan = UIPanGestureRecognizer(target: self, action: #selector(CropViewController.didRecognizeCheckPan(_:))) floatingView.addGestureRecognizer(checkPan) checkPan.delegate = self let tapRec = UITapGestureRecognizer(target: self, action: #selector(CropViewController.didRecognizeTap(_:))) floatingView.addGestureRecognizer(tapRec) } } override var prefersStatusBarHidden : Bool { return true } // MARK: IBActions @IBAction func didRecognizeTap(_ rec: UITapGestureRecognizer) { if state == .folded { restore(view: floatingView, to: .unfolded, animated: true) } } var zooming = false var checking = false var offset: CGFloat = 0 { didSet { if offset < 0 && state == .moved { offset = 0 } } } @IBAction func didRecognizeMainPan(_ rec: UIPanGestureRecognizer) { guard !zooming else { return } if state == .unfolded { allowPanOutside = false } receivePanGesture(recognizer: rec, with: floatingView) updatePhotoCollectionViewScrolling() } @IBAction func didRecognizeCheckPan(_ rec: UIPanGestureRecognizer) { guard !zooming else { return } allowPanOutside = true } // MARK: FloatingViewLayout methods func prepareForMovement() { updateCropViewScrolling() } func didEndMoving() { updateCropViewScrolling() } func updateCropViewScrolling() { if state == .moved { delegate.isEnabled = false } else { delegate.isEnabled = true } } func updatePhotoCollectionViewScrolling() { if state == .moved { _parent.photoViewController.collectionView.contentOffset.y = offset } else { offset = _parent.photoViewController.collectionView.contentOffset.y } } // MARK: Cropable methods func willZoom() { zooming = true } func willEndZooming() { zooming = false } } extension CropViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
23.305699
155
0.680969
fbcf647620b32ad5ac2fbe011de3f3d094625606
673
// // SKFetchProduct.swift // SkarbSDKExample // // Created by Artem Hitrik on 1/18/21. // Copyright © 2021 Prodinfire. All rights reserved. // import Foundation struct SKFetchProduct: SKCodableStruct, Equatable, Hashable { let productId: String let transactionDate: Date? let transactionId: String? init(productId: String, transactionDate: Date?, transactionId: String?) { self.productId = productId self.transactionDate = transactionDate self.transactionId = transactionId } func getData() -> Data? { let encoder = JSONEncoder() if let encoded = try? encoder.encode(self) { return encoded } return nil } }
21.709677
75
0.68945
7a0b4dda2a59239e186a14f303de7df3e5c04127
1,608
// // TypeHolderExample.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif public struct TypeHolderExample: Codable, Hashable { public var stringItem: String public var numberItem: Double public var floatItem: Float public var integerItem: Int public var boolItem: Bool public var arrayItem: [Int] public init(stringItem: String, numberItem: Double, floatItem: Float, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { self.stringItem = stringItem self.numberItem = numberItem self.floatItem = floatItem self.integerItem = integerItem self.boolItem = boolItem self.arrayItem = arrayItem } public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" case floatItem = "float_item" case integerItem = "integer_item" case boolItem = "bool_item" case arrayItem = "array_item" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(stringItem, forKey: .stringItem) try container.encode(numberItem, forKey: .numberItem) try container.encode(floatItem, forKey: .floatItem) try container.encode(integerItem, forKey: .integerItem) try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } }
30.923077
127
0.687811
565452eb36bdb75111a60fffac0593ed46d179fb
908
// // FallPreWorkTests.swift // FallPreWorkTests // // Created by Pablo Pena on 7/26/21. // import XCTest @testable import FallPreWork class FallPreWorkTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.705882
111
0.6663
0e438d5c7464fa0040a380f4c5ff37ebff1395fe
1,233
// // SwiftUIwithUIKitView.swift // SwiftUIKitExample // // Created by Antoine van der Lee on 28/12/2020. // import SwiftUI import SwiftUIKitView struct SwiftUIwithUIKitView: View { var body: some View { NavigationView { UIKitView() // <- This is a `UIKit` view. .swiftUIView(layout: .intrinsic) // <- This is a SwiftUI `View`. .set(\.title, to: "Hello, UIKit!") .set(\.backgroundColor, to: UIColor(named: "swiftlee_orange")) .fixedSize() .navigationTitle("Use UIKit in SwiftUI") } } } struct SwiftUIwithUIKitView_Previews: PreviewProvider { static var previews: some View { SwiftUIwithUIKitView() } } // MARK: - UILabel Preview Example struct UILabelExample_Preview: PreviewProvider { static var previews: some View { UILabel() // <- This is a `UIKit` view. .swiftUIView(layout: .intrinsic) // <- This is a SwiftUI `View`. .set(\.text, to: "Hello, UIKit!") // <- Use key paths for updates. .fixedSize() // <- Make sure the size is set .previewLayout(.sizeThatFits) .previewDisplayName("UILabel Preview Example") } }
29.357143
80
0.595296
7292a49eba3786d1ddebb2fe5eb856ec6832614e
1,809
import Combine import CoreMIDI final class MIDISubscription<S: Subscriber>: Subscription where S.Input == MIDIMessage, S.Failure == Never { let combineIdentifier = CombineIdentifier() private var subscriber: S? private let client: MIDIClient private var port = MIDIPortRef() private var demand: Subscribers.Demand = .none private var portCreated = false init(client: MIDIClient, subscriber: S) { self.client = client self.subscriber = subscriber } func request(_ newDemand: Subscribers.Demand) { guard newDemand > .none else { return } demand += newDemand guard portCreated else { createPort() return } } func cancel() { disposePort() subscriber = nil } private func createPort() { MIDIInputPortCreateWithBlock(client.client, client.generatePortName() as CFString, &port) { pointer, _ in pointer .unsafeSequence() .flatMap { $0.sequence() } .chunked(into: 3) .compactMap(MIDIMessage.init) .forEach { [weak self] message in guard let self = self, let subscriber = self.subscriber else { return } guard self.demand > .none else { self.disposePort() return } self.demand -= .max(1) _ = subscriber.receive(message) } } for i in 0...MIDIGetNumberOfSources() { MIDIPortConnectSource(port, MIDIGetSource(i), nil) } portCreated = true } private func disposePort() { MIDIPortDispose(port) portCreated = false } }
28.265625
113
0.546711
677339c12671e48a6729847d6a34fc729d36ecc3
3,586
// // ClangTranslationUnit.swift // SourceKitten // // Created by JP Simard on 2015-01-12. // Copyright (c) 2015 SourceKitten. All rights reserved. // #if !os(Linux) #if SWIFT_PACKAGE import Clang_C #endif import Foundation extension Sequence where Iterator.Element: Hashable { fileprivate func distinct() -> [Iterator.Element] { return Array(Set(self)) } } extension Sequence { fileprivate func grouped<U: Hashable>(by transform: (Iterator.Element) -> U) -> [U: [Iterator.Element]] { return reduce([:]) { dictionary, element in var dictionary = dictionary let key = transform(element) dictionary[key] = (dictionary[key] ?? []) + [element] return dictionary } } } extension Dictionary { fileprivate init(_ pairs: [Element]) { self.init() for (k, v) in pairs { self[k] = v } } fileprivate func map<OutValue>(transform: (Value) throws -> (OutValue)) rethrows -> [Key: OutValue] { return [Key: OutValue](try map { (k, v) in (k, try transform(v)) }) } } /// Represents a group of CXTranslationUnits. public struct ClangTranslationUnit { /// Array of CXTranslationUnits. private let clangTranslationUnits: [CXTranslationUnit] public let declarations: [String: [SourceDeclaration]] /** Create a ClangTranslationUnit by passing Objective-C header files and clang compiler arguments. - parameter headerFiles: Objective-C header files to document. - parameter compilerArguments: Clang compiler arguments. */ public init(headerFiles: [String], compilerArguments: [String]) { let cStringCompilerArguments = compilerArguments.map { ($0 as NSString).utf8String } let clangIndex = ClangIndex() clangTranslationUnits = headerFiles.map { clangIndex.open(file: $0, args: cStringCompilerArguments) } declarations = clangTranslationUnits .flatMap { $0.cursor().flatMap({ SourceDeclaration(cursor: $0, compilerArguments: compilerArguments) }) } .rejectEmptyDuplicateEnums() .distinct() .sorted() .grouped { $0.location.file } .map { insertMarks(declarations: $0) } } /** Failable initializer to create a ClangTranslationUnit by passing Objective-C header files and `xcodebuild` arguments. Optionally pass in a `path`. - parameter headerFiles: Objective-C header files to document. - parameter xcodeBuildArguments: The arguments necessary pass in to `xcodebuild` to link these header files. - parameter path: Path to run `xcodebuild` from. Uses current path by default. */ public init?(headerFiles: [String], xcodeBuildArguments: [String], inPath path: String = FileManager.default.currentDirectoryPath) { let xcodeBuildOutput = runXcodeBuild(arguments: xcodeBuildArguments + ["-dry-run"], inPath: path) ?? "" guard let clangArguments = parseCompilerArguments(xcodebuildOutput: xcodeBuildOutput as NSString, language: .objc, moduleName: nil) else { fputs("could not parse compiler arguments\n\(xcodeBuildOutput)\n", stderr) return nil } self.init(headerFiles: headerFiles, compilerArguments: clangArguments) } } // MARK: CustomStringConvertible extension ClangTranslationUnit: CustomStringConvertible { /// A textual JSON representation of `ClangTranslationUnit`. public var description: String { return declarationsToJSON(declarations) + "\n" } } #endif
35.86
146
0.668712
7a251dc5a922f347c74d4b0ae6a290fdcbebc2e4
319
// // Array+NumberSequence.swift // Ticker Counter // // Created by Kevin Miller on 3/14/19. // Copyright © 2019 Prolific Interactive. All rights reserved. // import Foundation extension Array where Element == Int { func stringArray() -> [String] { return self.compactMap { String($0) } } }
18.764706
63
0.645768
b9ac3697f39485ca00393d9cd4685ef023c6b46b
915
// // ContentView.swift // SwiftUI-example // // Created by 朱德坤 on 2019/6/4. // Copyright © 2019 DKJone. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { // 创建 文本(Label) let aText = Text("Hello SwiftUI") .color(.yellow) .strikethrough() .font(.system(size: 14.1)) // 创建 按钮(Button) let aButton = Button(action: { print(#function) }) { Text("Hello SwiftUI") } let aView = AnyView(aText) // 创建图片 let anImage = Image("img") .aspectRatio(contentMode: .fit) // 布局各视图 return VStack { anImage aText aButton aView } } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
19.0625
49
0.510383
ccf5032661c47072da1b8ed9ef37de1600267286
1,383
// // BroadcastSetupViewController.swift // UZBroadcastExtensionSetupUI // // Created by Nam Kennic on 9/10/21. // Copyright © 2021 Uiza. All rights reserved. // import ReplayKit class BroadcastSetupViewController: UIViewController { // Call this method when the user has finished interacting with the view controller and a broadcast stream can start func userDidFinishSetup() { // URL of the resource where broadcast can be viewed that will be returned to the application let urlPath = "rtmp://a.rtmp.youtube.com/live2" let broadcastURL = URL(string: urlPath) // Dictionary with setup information that will be provided to broadcast extension when broadcast is started let setupInfo: [String : NSCoding & NSObjectProtocol] = ["urlPath": urlPath as NSCoding & NSObjectProtocol, "streamKey": "ftbg-1rw5-8abs-bkfp-d3ya" as NSCoding & NSObjectProtocol] // Tell ReplayKit that the extension is finished setting up and can begin broadcasting self.extensionContext?.completeRequest(withBroadcast: broadcastURL!, setupInfo: setupInfo) } func userDidCancelSetup() { let error = NSError(domain: "YouAppDomain", code: -1, userInfo: nil) // Tell ReplayKit that the extension was cancelled by the user self.extensionContext?.cancelRequest(withError: error) } }
41.909091
120
0.711497
204ba45a3cdf6580bad06d7183cf49f0fd2a8b6f
1,444
// // Tip_CalculatorUITests.swift // Tip_CalculatorUITests // // Created by Murtaza Ali on 8/26/21. // import XCTest class Tip_CalculatorUITests: 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.581395
182
0.659972
720b2a7be5a3b5c273211744b43d84d89eee236a
4,860
// Tests lookup and mangling of local types // RUN: rm -rf %t && mkdir -p %t // RUN: %target-swiftc_driver -swift-version 3 -v -emit-module -module-name LocalTypes -o %t/LocalTypes.swiftmodule %s // RUN: %target-swift-ide-test -swift-version 3 -print-local-types -I %t -module-to-print LocalTypes -source-filename %s > %t.dump // RUN: %FileCheck %s < %t.dump // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.dump public func singleFunc() { // CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD6StructL_V struct SingleFuncStruct { let sfsi: Int } // CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD5ClassL_C class SingleFuncClass { let sfcs: String init(s: String) { self.sfcs = s } } // CHECK-DAG: 10LocalTypes10singleFuncyyF06SingleD4EnumL_O enum SingleFuncEnum { case SFEI(Int) } // CHECK-DAG: 10LocalTypes10singleFuncyyF13GenericStructL_V struct GenericStruct<T> { let sfgsi: Int } // CHECK-DAG: 10LocalTypes10singleFuncyyF12GenericClassL_C class GenericClass<T> { let sfgci: Int = 0 } // CHECK-DAG: 10LocalTypes10singleFuncyyF11GenericEnumL_O enum GenericEnum<T> { case sfgei(Int) } // We'll need to handle this if we start saving alias types. // NEGATIVE-NOT: AliasAAA typealias SingleFuncAliasAAA = Int // NEGATIVE-NOT: AliasGGG typealias GenericAliasGGG<T> = (T, T) } public func singleFuncWithDuplicates(_ fake: Bool) { if fake { // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL_V struct SingleFuncStruct { let sfsi: Int } // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL_C class SingleFuncClass { let sfcs: String init(s: String) { self.sfcs = s } } // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL_O enum SingleFuncEnum { case SFEI(Int) } } else { // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL0_V struct SingleFuncStruct { let sfsi: Int } // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL0_C class SingleFuncClass { let sfcs: String init(s: String) { self.sfcs = s } } // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL0_O enum SingleFuncEnum { case SFEI(Int) } } } public let singleClosure: () -> () = { // CHECK-DAG: 10LocalTypesyycfU_19SingleClosureStructL_V struct SingleClosureStruct { let scsi: Int } // CHECK-DAG: 10LocalTypesyycfU_18SingleClosureClassL_C class SingleClosureClass { let sccs: String init(s: String) { self.sccs = s } } // CHECK-DAG: 10LocalTypesyycfU_17SingleClosureEnumL_O enum SingleClosureEnum { case SCEI(Int) } } public var singlePattern: Int { // CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD6StructL_V struct SinglePatternStruct { let spsi: Int } // CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD5ClassL_C class SinglePatternClass { let spcs: String init(s: String) { self.spcs = s } } // CHECK-DAG: 10LocalTypes13singlePatternSifg06SingleD4EnumL_O enum SinglePatternEnum { case SPEI(Int) } return 2 } public func singleDefaultArgument(i: Int = { //CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE6StructL_V struct SingleDefaultArgumentStruct { let sdasi: Int } // CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE5ClassL_C class SingleDefaultArgumentClass { let sdacs: String init(s: String) { self.sdacs = s } } // CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE4EnumL_O enum SingleDefaultArgumentEnum { case SDAEI(Int) } return 2 }()){ print(i) } public func doubleFunc() { func innerFunc() { // CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD6StructL_V struct DoubleFuncStruct { let dfsi: Int } // CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD5ClassL_C class DoubleFuncClass { let dfcs: String init(s: String) { self.dfcs = s } } // CHECK-DAG: 10LocalTypes10doubleFuncyyF05innerD0L_yyF06DoubleD4EnumL_O enum DoubleFuncEnum { case DFEI(Int) } } innerFunc() } public let doubleClosure: () -> () = { let singleClosure: () -> () = { // CHECK-DAG: 10LocalTypesyycfU0_yycfU_19DoubleClosureStructL_V struct DoubleClosureStruct { let dcsi: Int } // CHECK-DAG: 10LocalTypesyycfU0_yycfU_18DoubleClosureClassL_C class DoubleClosureClass { let dccs: String init(s: String) { self.dccs = s } } // CHECK-DAG: 10LocalTypesyycfU0_yycfU_17DoubleClosureEnumL_O enum DoubleClosureEnum { case DCEI(Int) } } singleClosure() }
26.27027
130
0.702469
1cee04dfc01528d4dd76b88d120550aaf0f5a7fa
4,875
// // GameViewController.swift // MGDYZB // // Created by ming on 16/10/25. // Copyright © 2016年 ming. All rights reserved. // import UIKit private let kEdgeMargin : CGFloat = 10 private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3 private let kItemH : CGFloat = kItemW * 6 / 5 //private let kHeaderViewH : CGFloat = 50 private let kGameCellID = "kGameCellID" //private let kHeaderViewID = "kHeaderViewID" class GameViewController: BaseViewController { // MARK: 懒加载属性 fileprivate lazy var gameVM : GameViewModel = GameViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.dataSource = self return collectionView }() fileprivate lazy var topHeaderView : CollectionHeaderView = { let headerView = CollectionHeaderView.collectionHeaderView() headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH) headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.titleLabel.text = "常见" headerView.moreBtn.isHidden = true return headerView }() fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() override func viewDidLoad() { super.viewDidLoad() setUpMainView() loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK:- 设置UI界面 extension GameViewController { override func setUpMainView() { // 0.给ContentView进行赋值 contentView = collectionView // 1.添加UICollectionView view.addSubview(collectionView) // 2.添加顶部的HeaderView collectionView.addSubview(topHeaderView) // 3.将常用游戏的View,添加到collectionView中 collectionView.addSubview(gameView) // 4.设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0) super.setUpMainView() } } // MARK:- 请求数据 extension GameViewController { func loadData() { gameVM.loadAllGameData { // 1.展示全部游戏 self.collectionView.reloadData() // 2.展示常用游戏 self.gameView.groups = Array(self.gameVM.games[0..<10]) // 3.数据请求完成 self.loadDataFinished() } } } // MARK:- 遵守UICollectionView的数据源&代理 extension GameViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.games.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.lineView.isHidden = false cell.baseGame = gameVM.games[(indexPath as NSIndexPath).item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给HeaderView设置属性 headerView.titleLabel.text = "全部" headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.moreBtn.isHidden = true return headerView } }
35.071942
186
0.677949
218d0c77f649a2e5ac3326216a268b8fb17f3ca3
1,058
// // Alamofire_SwiftyJSONTests.swift // Alamofire-SwiftyJSONTests // // Created by Pinglin Tang on 14-9-23. // Copyright (c) 2014年 SwiftJSON. All rights reserved. // import UIKit import XCTest import Alamofire import SwiftyJSON import AlamofireSwiftyJSON class Alamofire_SwiftyJSONTests: XCTestCase { func testJSONResponse() { let URL = "http://httpbin.org/get" let expectation = expectationWithDescription("\(URL)") Alamofire.request(.GET, URL, parameters: ["foo": "bar"]).responseSwiftyJSON({(request, response, responseJSON, error) in expectation.fulfill() XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(responseJSON["args"], SwiftyJSON.JSON(["foo": "bar"] as NSDictionary), "args should be equal") }) waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } } }
31.117647
128
0.659735
167da5b6e2c714c11ed3b2d212d5a9e218db0c37
420
import Routing import Vapor /// Register your application's routes here. /// /// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#routesswift) public func routes(_ router: Router) throws { let acronymsController = AcronymController() try router.register(collection: acronymsController) let userController = UserController() try router.register(collection: userController) }
28
87
0.742857
208a2a407d85ecc9fcf9b7ab4d6ed6e88996a901
2,555
// // NameCallbackTableViewCell.swift // FRUI // // Copyright (c) 2019 ForgeRock. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // import UIKit import FRAuth class NameCallbackTableViewCell: UITableViewCell { // MARK: - Properties public static let cellIdentifier = "NameCallbackTableViewCellId" public static let cellHeight:CGFloat = 100.0 @IBOutlet weak var textField:FRTextField? var callback:SingleValueCallback? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.textField?.tintColor = FRUI.shared.primaryColor self.textField?.normalColor = FRUI.shared.primaryColor } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - Public public func updateCellData(authCallback: SingleValueCallback) { self.callback = authCallback self.textField?.placeholder = authCallback.prompt if authCallback is AbstractValidatedCallback, let validatedCallback = authCallback as? AbstractValidatedCallback { self.textField?.text = validatedCallback.value as? String if let failedPolicies = validatedCallback.failedPolicies { var failedMessage = "" for (index, failedPolicy) in failedPolicies.enumerated() { if index >= 1 { failedMessage = ", " } failedMessage = failedPolicy.failedDescription() } textField?.errorMessage = failedMessage } } } } // MARK: - UITextFieldDelegate extension NameCallbackTableViewCell: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if self.textField?.errorMessage != nil { self.textField?.errorMessage = nil } return true } func textFieldDidEndEditing(_ textField: UITextField) { callback?.value = textField.text if callback is AttributeInputCallback, let inputCallback = callback as? AttributeInputCallback, inputCallback.required { if textField.text == nil || textField.text?.count == 0 { self.textField?.errorMessage = "Value must not be empty" } } } }
33.618421
129
0.639922
8f36a15df0b9a79beff7644d69f998c335734a40
11,294
// The MIT License (MIT) // // Copyright (c) 2017 - present zqqf16 // // 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 Cocoa import Combine protocol DsymTableCellViewDelegate: AnyObject { func didClickSelectButton(_ cell: DsymTableCellView, sender: NSButton) func didClickRevealButton(_ cell: DsymTableCellView, sender: NSButton) } class DsymTableCellView: NSTableCellView { @IBOutlet weak var image: NSImageView! @IBOutlet weak var title: NSTextField! @IBOutlet weak var uuid: NSTextField! @IBOutlet weak var path: NSTextField! @IBOutlet weak var actionButton: NSButton! var deleteButton: NSButton! weak var delegate: DsymTableCellViewDelegate? var binary: Binary! var dsym: DsymFile? required init?(coder: NSCoder) { super.init(coder: coder) deleteButton = NSButton.init(title: "删除", target: self, action: #selector(didClickDelete(_:))) deleteButton.font = NSFont.systemFont(ofSize: 10) self.addSubview(deleteButton) } override func layout() { self.deleteButton.frame = NSRect.init(x: self.actionButton.frame.origin.x + self.actionButton.frame.size.width + 12, y: self.actionButton.frame.origin.y, width: 55, height: 20) } func updateUI() { self.title.stringValue = self.binary.name self.uuid.stringValue = self.binary.uuid ?? "" if let path = self.dsym?.path { self.path.stringValue = path self.actionButton.title = NSLocalizedString("Reveal", comment: "Reveal in Finder") self.deleteButton.isHidden = false self.deleteButton.title = "删除" } else { self.path.stringValue = NSLocalizedString("dsym_file_not_found", comment: "Dsym file not found") self.actionButton.title = NSLocalizedString("Import", comment: "Import a dSYM file") self.deleteButton.isHidden = true } } @IBAction func didClickDelete(_ sender: Any) { self.dsym?.path = nil updateUI() } @IBAction func didClickActionButton(_ sender: NSButton) { if self.dsym?.path != nil { self.delegate?.didClickRevealButton(self, sender: sender) } else { self.delegate?.didClickSelectButton(self, sender: sender) } } } class DsymViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var tableViewHeight: NSLayoutConstraint! @IBOutlet weak var downloadButton: NSButton! @IBOutlet weak var progressBar: NSProgressIndicator! var importButton: NSButton! override func loadView() { super.loadView() importButton = NSButton.init(title: "一键导入", target: self, action: #selector(importAction)) self.view.addSubview(importButton) } override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { super.init(coder: coder) } @objc func importAction() { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = true openPanel.canChooseDirectories = true openPanel.canCreateDirectories = false openPanel.canChooseFiles = true openPanel.begin { [weak openPanel] (result) in guard result == .OK, let url = openPanel?.url else { return } if (url.absoluteString.hasSuffix("dSYM")) { let element = url.absoluteString self.dsymManager?.binaries.forEach({ binary in if element.hasSuffix("dSYM") { if element.contains(binary.name) { print("111", binary.name) self.dsymFile(forBinary: binary)?.path = element } } }) self.tableView.reloadData() return } var filePath = url.absoluteString if (filePath.hasPrefix("file://")) { filePath = filePath.substring(from: filePath.index(filePath.startIndex, offsetBy: 7)) } let enumerator = FileManager.default.enumerator(atPath: filePath) while let element = enumerator?.nextObject() as? String { self.dsymManager?.binaries.forEach({ binary in if element.hasSuffix("dSYM") { if element.contains(binary.name) { let elementFilePath = filePath + element self.dsymManager?.assign(binary, dsymFileURL: URL.init(fileURLWithPath: elementFilePath)) } } }) } self.tableView.reloadData() } } override func viewDidLayout() { self.importButton.frame = NSRect.init(x: self.downloadButton.frame.origin.x - 80 - 5, y: self.downloadButton.frame.origin.y + 5 , width: 80, height: 20) } private var binaries: [Binary] = [] { didSet { self.reloadData() } } private var dsymFiles: [String: DsymFile] = [:] { didSet { self.reloadData() } } private var dsymStorage = Set<AnyCancellable>() private var taskCancellable: AnyCancellable? var dsymManager: DsymManager? { didSet { self.dsymStorage.forEach { (cancellable) in cancellable.cancel() } dsymManager?.$binaries .receive(on: DispatchQueue.main) .assign(to: \.binaries, on: self) .store(in: &dsymStorage) dsymManager?.$dsymFiles .receive(on: DispatchQueue.main) .assign(to: \.dsymFiles, on: self) .store(in: &dsymStorage) } } private func reloadData() { guard self.tableView != nil else { return } self.tableView.reloadData() self.updateViewHeight() } private func dsymFile(forBinary binary: Binary) -> DsymFile? { if let uuid = binary.uuid { return self.dsymManager?.dsymFile(withUuid: uuid) } return nil } override func viewDidLoad() { super.viewDidLoad() self.updateViewHeight() self.downloadButton.isEnabled = self.dsymManager?.crash != nil } override func viewDidDisappear() { super.viewDidDisappear() self.taskCancellable?.cancel() self.dsymStorage.forEach { (cancellable) in cancellable.cancel() } } func bind(task: DsymDownloadTask?) { self.taskCancellable?.cancel() guard let downloadTask = task else { return } self.taskCancellable = Publishers .CombineLatest(downloadTask.$status, downloadTask.$progress) .receive(on: DispatchQueue.main) .sink { (status, progress) in self.update(status: status, progress: progress) } } //MARK: UI private func updateViewHeight() { self.tableViewHeight.constant = min(CGFloat(70 * self.binaries.count), 520.0) } @IBAction func didClickDownloadButton(_ sender: NSButton) { if let crashInfo = self.dsymManager?.crash { DsymDownloader.shared.download(crashInfo: crashInfo, fileURL: nil) } } } extension DsymViewController: NSTableViewDelegate, NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return self.binaries.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: nil) as? DsymTableCellView cell?.delegate = self let binary = self.binaries[row] cell?.binary = binary cell?.dsym = self.dsymFile(forBinary: binary) cell?.updateUI() return cell } func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return false } } extension DsymViewController: DsymTableCellViewDelegate { func didClickSelectButton(_ cell: DsymTableCellView, sender: NSButton) { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.canChooseFiles = true openPanel.begin { [weak openPanel] (result) in guard result == .OK, let url = openPanel?.url else { return } self.dsymManager?.assign(cell.binary!, dsymFileURL: url) } } func didClickRevealButton(_ cell: DsymTableCellView, sender: NSButton) { if let path = cell.dsym?.path { let url = URL(fileURLWithPath: path) NSWorkspace.shared.activateFileViewerSelecting([url]) } } } extension DsymViewController { func update(status: DsymDownloadTask.Status, progress: DsymDownloadTask.Progress) { switch status { case .running: self.downloadButton.isEnabled = false self.progressBar.isHidden = false case .canceled: self.progressBar.isHidden = true self.downloadButton.isEnabled = true case .failed(_, _): self.progressBar.isHidden = true self.downloadButton.isEnabled = true case .success: self.progressBar.isHidden = true case .waiting: self.progressBar.isHidden = false self.progressBar.isIndeterminate = true self.progressBar.startAnimation(nil) self.downloadButton.isEnabled = false } if progress.percentage == 0 { self.progressBar.isIndeterminate = true } else { self.progressBar.isIndeterminate = false self.progressBar.doubleValue = Double(progress.percentage) } } }
35.968153
184
0.612892
61c514dffdbc508526459868804362b496db1ac1
5,589
// // // import Foundation import SwiftUI class PartycakeEventController { func play(secretId: String?) { // Connection オブイェクトを生成 let myUserId = appState.account.loginUser.id appState.partycakeConnection = PartycakeConnection(url: "test", userId: myUserId) Task { // 自身を observer に設定してから接続 appState.partycakeConnection.observer = self await appState.partycakeConnection.connect() if let secretId = secretId { // すでにプレイ中のゲームがある時 resumePlay(secretId: secretId) { fatalError("resume play でエラーが発生しました") } } else { // まだプレイ中のゲームがない時 // マッチングから appState.matching = MatchingState(gameId: .partycake, seatCount: 4, message: "プレイヤーを募集しています...") Router().pushBasePage(pageId: .matching) } } } func onExit() { // observer 解除してから切断 appState.partycakeConnection.observer = nil appState.partycakeConnection.disconnect() } func resumePlay(secretId: String, onError: @escaping (()->Void)) { let userId = appState.account.loginUser.id let req = PartycakeLoadRoom.Request(user_id: userId, secret_id: secretId) print("\(PartycakeLoadRoom.urlPath) にリクエストを送信します") CenterClient.forLocal.send( req, to: PartycakeLoadRoom.API, onReceive: { res in DispatchQueue.main.async { // Stateの作成 let partycakeSystemState = PartycakeSystemState( partycakeState: res.state, players: res.players ) appState.partycakeSystem = partycakeSystemState // UIStateの作成 let partycakePlayUiState = PartycakePlayUiStateBuilder().playUiState(from: partycakeSystemState) appState.partycakePlayUi = partycakePlayUiState Router().setBasePages(stack: [.partycakePlay]) } }, onCatch: {_ in fatalError("LoadGameに失敗") } ) } // score list まで終了 func didShowdown() { PartycakeBetController().enableBet() DispatchQueue.main.async { appState.partycakePlayUi.canExit = true } } func didShuffle() { PartycakePutController().enablePut() } } extension PartycakeEventController: PartycakeConnectionObserver { var userID: String { return appState.account.loginUser.id } // Push通知を受け取る func onReceive(announce: PartycakeAnnounce) { let type = PartycakeAnnounceId(rawValue: announce.announce_type)! switch type { case .matchComplete: PartycakeMatchingController().onMatchComplete(announce: announce) case .betStart: let myUserId = appState.account.loginUser.id let mySeat = announce.players!.first(where: {$0.user_id == myUserId})!.seat let myStep = announce.masked_state!.sides.first(where: {$0.seat.rawValue == mySeat})!.playerStep DispatchQueue.main.async { switch myStep { case .bet: appState.partycakePlayUi.waitingOthers = false case .waitingShuffle: appState.partycakePlayUi.waitingOthers = true case .put: appState.partycakePlayUi.waitingOthers = false case .waitingShowdown: appState.partycakePlayUi.waitingOthers = true } } // MARK: - Bet開始だが、UIではショーダウンアニメーションから実施 // システムStateを保存 appState.partycakeSystem.partycakeState = announce.masked_state! appState.partycakeSystem.players = announce.players! // ショーダウン開始 PartycakeShowdownController().startShowdown( animationList: announce.showdown_list!, scoreList: announce.score_list! ) case .putStart: // システムStateを保存 appState.partycakeSystem.partycakeState = announce.masked_state! appState.partycakeSystem.players = announce.players! let myUserId = appState.account.loginUser.id let mySeat = announce.players!.first(where: {$0.user_id == myUserId})!.seat let myStep = announce.masked_state!.sides.first(where: {$0.seat.rawValue == mySeat})!.playerStep DispatchQueue.main.async { switch myStep { case .bet: appState.partycakePlayUi.waitingOthers = false case .waitingShuffle: appState.partycakePlayUi.waitingOthers = true case .put: appState.partycakePlayUi.waitingOthers = false case .waitingShowdown: appState.partycakePlayUi.waitingOthers = true } } // Put開始だが、UIではシャッフルから実施 PartycakeShaffleController().startShuffle(with: announce) case .playerPut: let seat = PartycakeSeat(rawValue: announce.trigger_seat!)! PartycakePutController().onPlayerPut(at: seat) case .playerEnter: print("誰かが参加しました") case .playerExit: print("誰かが退出しました") } } }
36.529412
116
0.560744
de83724a36abb4f4c7010ad3b0eefe3353e9afa9
2,431
// // RxKingfisher.swift // RxKingfisher // // Created by Shai Mishali on 5/5/18. // Copyright © 2018 RxSwift Community. All rights reserved. // import Kingfisher import RxCocoa import RxSwift public extension KingfisherWrapper { struct Rx { private let wrapper: KingfisherWrapper<KFCrossPlatformImageView> init(_ base: KingfisherWrapper<KFCrossPlatformImageView>) { wrapper = base } public func image( placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil ) -> Binder<Resource?> { // `base.base` is the `Kingfisher` class' associated `ImageView`. return Binder(wrapper.base) { imageView, image in imageView.kf.setImage( with: image, placeholder: placeholder, options: options ) } } public func setImage( with source: Source?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil ) -> Single<KFCrossPlatformImage> { Single.create { [wrapper] single in let task = wrapper.setImage( with: source, placeholder: placeholder, options: options, completionHandler: { result in switch result { case .success(let value): single(.success(value.image)) case .failure(let error): single(.failure(error)) } } ) return Disposables.create { task?.cancel() } } } public func setImage( with resource: Resource?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil ) -> Single<KFCrossPlatformImage> { let source: Source? if let resource = resource { source = Source.network(resource) } else { source = nil } return setImage(with: source, placeholder: placeholder, options: options) } } } public extension KingfisherWrapper where Base == KFCrossPlatformImageView { var rx: KingfisherWrapper.Rx { .init(self) } }
30.3875
85
0.514192
0ea3d4a1083f46680b3e4b5c684ccb608802ac7f
3,531
import Cocoa final class HistorySplitController: NSSplitViewController { var historyController: HistoryViewController! private var savedHistorySize: CGFloat? var historyHidden: Bool { splitViewItems[0].isCollapsed } var detailsHidden: Bool { splitViewItems[1].isCollapsed } override func viewDidLoad() { super.viewDidLoad() historyController = splitViewItems[0].viewController as? HistoryViewController historyController.splitController = self // TODO: Convert FileViewController.xib to a storyboard that can be loaded // by reference. let fileController = FileViewController(nibName: .fileViewControllerNib, bundle: nil) let fileViewItem = NSSplitViewItem(viewController: fileController) historyController.fileViewController = fileController fileViewItem.canCollapse = true fileViewItem.minimumThickness = FileViewController.minDetailHeight + FileViewController.minHeaderHeight fileViewItem.holdingPriority = .init(NSLayoutConstraint.Priority .dragThatCannotResizeWindow.rawValue - 1) insertSplitViewItem(fileViewItem, at: 1) splitViewItems[0].minimumThickness = 60 // Thick divider crashes if there is only one split item splitView.dividerStyle = .thick } @IBAction func toggleHistory(_: Any?) { if historyHidden { // Go back to the un-collapsed size. if let size = savedHistorySize { splitView.setPosition(size, ofDividerAt: 0) splitView.subviews[0].isHidden = false } } else { if detailsHidden { // Details pane is collapsed, so swap them. let minSize = splitView.minPossiblePositionOfDivider(at: 0) splitView.setPosition(minSize, ofDividerAt: 0) splitView.subviews[1].isHidden = false } else { // Both panes are showing, so just collapse history. let newSize = splitView.minPossiblePositionOfDivider(at: 0) saveHistorySize() splitView.setPosition(newSize, ofDividerAt: 0) } splitView.subviews[0].isHidden = true } } @IBAction func toggleDetails(_: Any?) { if detailsHidden { // Go back to the un-collapsed size. if let size = savedHistorySize { splitView.setPosition(size, ofDividerAt: 0) splitView.subviews[1].isHidden = false } historyController.fileViewController.restoreSplit() } else { if historyHidden { // History pane is collapsed, so swap them. let maxSize = splitView.maxPossiblePositionOfDivider(at: 0) historyController.fileViewController.saveSplit() splitView.setPosition(maxSize, ofDividerAt: 0) splitView.subviews[0].isHidden = false } else { // Both panes are showing, so just collapse details. // Save the history pane size in both cases because it's the same divider // restored to the same position in both cases. let newSize = splitView.maxPossiblePositionOfDivider(at: 0) saveHistorySize() historyController.fileViewController.saveSplit() splitView.setPosition(newSize, ofDividerAt: 0) } splitView.subviews[1].isHidden = true } } func saveHistorySize() { let historySize = splitView.subviews[0].bounds.size savedHistorySize = splitView.isVertical ? historySize.width : historySize.height } }
32.394495
82
0.666383
0ec0b12f886f41bc3efc8aedd2b6ac2b3e1b3718
455
// // GitHubManager.swift // iOS-Redux-study // // Created by AtsuyaSato on 2018/01/31. // Copyright © 2018年 Atsuya Sato. All rights reserved. // import Foundation import RxSwift import APIKit class GitHubManager { static let shared = GitHubManager() private init() { } func repositories(userName: String) -> Observable<[Repository]> { return Session.rx_response(request: FetchRepositoryRequest(userName: userName)) } }
20.681818
87
0.698901
e0fe6844777b7e6f1388c3a27d07313932220e17
10,769
// // EthereumPrivateKey.swift // Web3 // // Created by Koray Koska on 06.02.18. // Copyright © 2018 Boilertalk. All rights reserved. // import Foundation import secp256k1 public final class EthereumPrivateKey { // MARK: - Properties /// The raw private key bytes public let rawPrivateKey: Bytes /// The public key associated with this private key public let publicKey: EthereumPublicKey /// Returns the ethereum address representing the public key associated with this private key. public var address: EthereumAddress { return publicKey.address } /// True iff ctx should not be freed on deinit private let ctxSelfManaged: Bool /// Internal context for secp256k1 library calls private let ctx: OpaquePointer // MARK: - Initialization /** * Initializes a new cryptographically secure `EthereumPrivateKey` from random noise. * * The process of generating the new private key is as follows: * * - Generate a secure random number between 55 and 65.590. Call it `rand`. * - Read `rand` bytes from `/dev/urandom` and call it `bytes`. * - Create the keccak256 hash of `bytes` and initialize this private key with the generated hash. */ public convenience init() throws { guard var rand = Bytes.secureRandom(count: 2)?.bigEndianUInt else { throw Error.internalError } rand += 55 guard let bytes = Bytes.secureRandom(count: Int(rand)) else { throw Error.internalError } let bytesHash = Data(bytes).sha3_keccak256.bytes try self.init(privateKey: bytesHash) } /** * Convenient initializer for `init(privateKey:)` */ public required convenience init(_ bytes: Bytes) throws { try self.init(privateKey: bytes) } /** * Initializes a new instance of `EthereumPrivateKey` with the given `privateKey` Bytes. * * `privateKey` must be exactly a big endian 32 Byte array representing the private key. * * The number must be in the secp256k1 range as described in: https://en.bitcoin.it/wiki/Private_key * * So any number between * * 0x0000000000000000000000000000000000000000000000000000000000000001 * * and * * 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140 * * is considered to be a valid secp256k1 private key. * * - parameter privateKey: The private key bytes. * * - parameter ctx: An optional self managed context. If you have specific requirements and * your app performs not as fast as you want it to, you can manage the * `secp256k1_context` yourself with the public methods * `secp256k1_default_ctx_create` and `secp256k1_default_ctx_destroy`. * If you do this, we will not be able to free memory automatically and you * __have__ to destroy the context yourself once your app is closed or * you are sure it will not be used any longer. Only use this optional * context management if you know exactly what you are doing and you really * need it. * * - throws: EthereumPrivateKey.Error.keyMalformed if the restrictions described above are not met. * EthereumPrivateKey.Error.internalError if a secp256k1 library call or another internal call fails. * EthereumPrivateKey.Error.pubKeyGenerationFailed if the public key extraction from the private key fails. */ public init(privateKey: Bytes, ctx: OpaquePointer? = nil) throws { guard privateKey.count == 32 else { throw Error.keyMalformed } self.rawPrivateKey = privateKey let finalCtx: OpaquePointer if let ctx = ctx { finalCtx = ctx self.ctxSelfManaged = true } else { let ctx = try secp256k1_default_ctx_create(errorThrowable: Error.internalError) finalCtx = ctx self.ctxSelfManaged = false } self.ctx = finalCtx // *** Generate public key *** guard let pubKey = malloc(MemoryLayout<secp256k1_pubkey>.size)?.assumingMemoryBound(to: secp256k1_pubkey.self) else { throw Error.internalError } // Cleanup defer { free(pubKey) } var secret = privateKey if secp256k1_ec_pubkey_create(finalCtx, pubKey, &secret) != 1 { throw Error.pubKeyGenerationFailed } var pubOut = Bytes(repeating: 0, count: 65) var pubOutLen = 65 _ = secp256k1_ec_pubkey_serialize(finalCtx, &pubOut, &pubOutLen, pubKey, UInt32(SECP256K1_EC_UNCOMPRESSED)) guard pubOutLen == 65 else { throw Error.pubKeyGenerationFailed } // First byte is header byte 0x04 pubOut.remove(at: 0) self.publicKey = try EthereumPublicKey(publicKey: pubOut, ctx: ctx) // *** End Generate public key *** // Verify private key try verifyPrivateKey() } /** * Initializes a new instance of `EthereumPrivateKey` with the given `hexPrivateKey` hex string. * * `hexPrivateKey` must be either 64 characters long or 66 characters (with the hex prefix 0x). * * The number must be in the secp256k1 range as described in: https://en.bitcoin.it/wiki/Private_key * * So any number between * * 0x0000000000000000000000000000000000000000000000000000000000000001 * * and * * 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140 * * is considered to be a valid secp256k1 private key. * * - parameter hexPrivateKey: The private key bytes. * * - parameter ctx: An optional self managed context. If you have specific requirements and * your app performs not as fast as you want it to, you can manage the * `secp256k1_context` yourself with the public methods * `secp256k1_default_ctx_create` and `secp256k1_default_ctx_destroy`. * If you do this, we will not be able to free memory automatically and you * __have__ to destroy the context yourself once your app is closed or * you are sure it will not be used any longer. Only use this optional * context management if you know exactly what you are doing and you really * need it. * * - throws: EthereumPrivateKey.Error.keyMalformed if the restrictions described above are not met. * EthereumPrivateKey.Error.internalError if a secp256k1 library call or another internal call fails. * EthereumPrivateKey.Error.pubKeyGenerationFailed if the public key extraction from the private key fails. */ public convenience init(hexPrivateKey: String, ctx: OpaquePointer? = nil) throws { guard hexPrivateKey.count == 64 || hexPrivateKey.count == 66 else { throw Error.keyMalformed } var hexPrivateKey = hexPrivateKey if hexPrivateKey.count == 66 { let s = hexPrivateKey.index(hexPrivateKey.startIndex, offsetBy: 0) let e = hexPrivateKey.index(hexPrivateKey.startIndex, offsetBy: 2) let prefix = String(hexPrivateKey[s..<e]) guard prefix == "0x" else { throw Error.keyMalformed } // Remove prefix hexPrivateKey = String(hexPrivateKey[e...]) } var raw = Bytes() for i in stride(from: 0, to: hexPrivateKey.count, by: 2) { let s = hexPrivateKey.index(hexPrivateKey.startIndex, offsetBy: i) let e = hexPrivateKey.index(hexPrivateKey.startIndex, offsetBy: i + 2) guard let b = Byte(String(hexPrivateKey[s..<e]), radix: 16) else { throw Error.keyMalformed } raw.append(b) } try self.init(privateKey: raw, ctx: ctx) } // MARK: - Convenient functions public func sign(message: Bytes) throws -> (v: UInt, r: Bytes, s: Bytes) { let hash = Data(message).sha3_keccak256.bytes return try sign(hash: hash) } public func sign(hash _hash: Array<UInt8>) throws -> (v: UInt, r: Bytes, s: Bytes) { var hash = _hash guard hash.count == 32 else { throw Error.internalError } guard let sig = malloc(MemoryLayout<secp256k1_ecdsa_recoverable_signature>.size)?.assumingMemoryBound(to: secp256k1_ecdsa_recoverable_signature.self) else { throw Error.internalError } defer { free(sig) } var seckey = rawPrivateKey guard secp256k1_ecdsa_sign_recoverable(ctx, sig, &hash, &seckey, nil, nil) == 1 else { throw Error.internalError } var output64 = Bytes(repeating: 0, count: 64) var recid: Int32 = 0 secp256k1_ecdsa_recoverable_signature_serialize_compact(ctx, &output64, &recid, sig) guard recid == 0 || recid == 1 else { // Well I guess this one should never happen but to avoid bigger problems... throw Error.internalError } return (v: UInt(recid), r: Array(output64[0..<32]), s: Array(output64[32..<64])) } /** * Returns this private key serialized as a hex string. */ public func hex() -> String { var h = "0x" for b in rawPrivateKey { h += String(format: "%02x", b) } return h } // MARK: - Helper functions private func verifyPrivateKey() throws { var secret = rawPrivateKey guard secp256k1_ec_seckey_verify(ctx, &secret) == 1 else { throw Error.keyMalformed } } // MARK: - Errors public enum Error: Swift.Error { case internalError case keyMalformed case pubKeyGenerationFailed } // MARK: - Deinitialization deinit { if !ctxSelfManaged { secp256k1_context_destroy(ctx) } } } // MARK: - Equatable extension EthereumPrivateKey: Equatable { public static func ==(_ lhs: EthereumPrivateKey, _ rhs: EthereumPrivateKey) -> Bool { return lhs.rawPrivateKey == rhs.rawPrivateKey } } // MARK: - BytesConvertible extension EthereumPrivateKey: BytesConvertible { public func makeBytes() -> Bytes { return rawPrivateKey } } // MARK: - Hashable extension EthereumPrivateKey: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(rawPrivateKey) } }
34.187302
164
0.624663
281021c9b1e3d4ad7cb8ac4e98ab0fb373e3f62e
237
// // Array.swift // AlphaWallet // // Created by Vladyslav Shepitko on 04.03.2021. // import Foundation func -<T: Equatable>(left: [T], right: [T]) -> [T] { return left.filter { l in !right.contains { $0 == l } } }
15.8
52
0.561181
20aaed5294cd4ef69e60edcc6b13cd8dcd5bf868
682
// // ApiResponse.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class ApiResponse: JSONEncodable { public var code: Int32? public var type: String? public var message: String? public init() {} // MARK: JSONEncodable open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["code"] = self.code?.encodeToJSON() nillableDictionary["type"] = self.type nillableDictionary["message"] = self.message let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } }
24.357143
85
0.658358
721235fe5d3fc090e0def2ceab418178317e9697
17,518
// // DiscoveryWebViewHelper.swift // edX // // Created by Akiva Leffert on 11/9/15. // Copyright © 2015-2016 edX. All rights reserved. // import UIKit import WebKit fileprivate enum QueryParameterKeys { static let searchQuery = "q" static let subject = "subject" } @objc enum DiscoveryType: Int { case course case program case degree } class DiscoveryWebViewHelper: NSObject { typealias Environment = OEXConfigProvider & OEXSessionProvider & OEXStylesProvider & OEXRouterProvider & OEXAnalyticsProvider & OEXSessionProvider fileprivate let environment: Environment weak var delegate: WebViewNavigationDelegate? fileprivate let contentView = UIView() fileprivate let webView: WKWebView fileprivate let searchBar = UISearchBar() fileprivate lazy var subjectsController: PopularSubjectsViewController = { let controller = PopularSubjectsViewController() controller.delegate = self return controller }() fileprivate var loadController = LoadStateViewController() fileprivate let discoveryType: DiscoveryType fileprivate var request: URLRequest? = nil @objc var baseURL: URL? fileprivate let searchQuery:String? let bottomBar: UIView? private let searchBarEnabled: Bool private let showSubjects: Bool private var urlObservation: NSKeyValueObservation? private var subjectDiscoveryEnabled: Bool = false private var subjectsViewHeight: CGFloat { return UIDevice.current.userInterfaceIdiom == .pad ? 145 : 125 } fileprivate var params: [String: String]? { return (webView.url as NSURL?)?.oex_queryParameters() as? [String : String] } private var bottomSpace: CGFloat { //TODO: this should be the height of bottomBar but for now giving it static value as the NSCopying making new object's frame as zero return 90 } @objc convenience init(environment: Environment, delegate: WebViewNavigationDelegate?, bottomBar: UIView?, discoveryType: DiscoveryType = .course) { self.init(environment: environment, delegate: delegate, bottomBar: bottomBar, showSearch: false, searchQuery: nil, showSubjects: false, discoveryType: discoveryType) } @objc init(environment: Environment, delegate: WebViewNavigationDelegate?, bottomBar: UIView?, showSearch: Bool, searchQuery: String?, showSubjects: Bool = false, discoveryType: DiscoveryType = .course) { self.environment = environment self.webView = WKWebView(frame: .zero, configuration: environment.config.webViewConfiguration()) self.delegate = delegate self.bottomBar = bottomBar self.searchQuery = searchQuery self.showSubjects = showSubjects self.discoveryType = discoveryType let discoveryConfig = discoveryType == .program ? environment.config.discovery.program : environment.config.discovery.course searchBarEnabled = discoveryConfig.webview.searchEnabled && showSearch super.init() searchBarPlaceholder() webView.disableZoom() webView.navigationDelegate = self webView.scrollView.decelerationRate = UIScrollView.DecelerationRate.normal webView.accessibilityIdentifier = discoveryType == .course ? "find-courses-webview" : "find-programs-webview" guard let container = delegate?.webViewContainingController() else { return } container.view.addSubview(contentView) contentView.snp.makeConstraints { make in make.edges.equalTo(container.safeEdges) } loadController.setupInController(controller: container, contentView: contentView) refreshView() } @objc func refreshView() { guard let container = delegate?.webViewContainingController() else { return } contentView.subviews.forEach { $0.removeFromSuperview() } let isUserLoggedIn = environment.session.currentUser != nil subjectDiscoveryEnabled = (environment.config.discovery.course.webview.subjectFilterEnabled) && isUserLoggedIn && showSubjects && discoveryType == .course var topConstraintItem: ConstraintItem = contentView.snp.top if searchBarEnabled { searchBar.delegate = self contentView.addSubview(searchBar) searchBar.snp.makeConstraints{ make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.top.equalTo(contentView) } topConstraintItem = searchBar.snp.bottom } if subjectDiscoveryEnabled { container.addChild(subjectsController) contentView.addSubview(subjectsController.view) subjectsController.didMove(toParent: container) subjectsController.view.snp.makeConstraints { make in make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView) make.top.equalTo(topConstraintItem) make.height.equalTo(subjectsViewHeight) } topConstraintItem = subjectsController.view.snp.bottom } contentView.addSubview(webView) if let bar = bottomBar, !isUserLoggedIn { contentView.addSubview(bar) bar.snp.makeConstraints { make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.bottom.equalTo(contentView) } } webView.snp.makeConstraints { make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.bottom.equalTo(contentView) make.top.equalTo(topConstraintItem) if !isUserLoggedIn { make.bottom.equalTo(contentView).offset(-bottomSpace) } else { make.bottom.equalTo(contentView) } } addObserver() } private func searchBarPlaceholder() { switch discoveryType { case .course: searchBar.placeholder = Strings.searchCoursesPlaceholderText break case .program: searchBar.placeholder = Strings.searchProgramsPlaceholderText break case .degree: searchBar.placeholder = Strings.searchDegreesPlaceholderText break default: break } } private func addObserver() { // Add URL change oberver on webview, so URL change of webview can be tracked and handled. urlObservation = webView.observe(\.url, changeHandler: { [weak self] (webView, change) in self?.handleURLChangeNotification() }) NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_DYNAMIC_TEXT_TYPE_UPDATE) { (_, observer, _) in observer.reload() } } private func handleURLChangeNotification() { switch discoveryType { case .course: if subjectDiscoveryEnabled { updateSubjectsVisibility() } break case .program: if !URLHasSearchFilter { searchBar.text = nil } break default: break } } private var URLHasSearchFilter: Bool { guard let URL = webView.url?.absoluteString else { return false } return URL.contains(find: QueryParameterKeys.searchQuery) } private func reload() { guard let URL = webView.url, !webView.isLoading else { return } loadController.state = .Initial loadRequest(withURL: URL) } @objc func updateSubjectsVisibility() { if contentView.subviews.contains(subjectsController.view) { let hideSubjectsView = isiPhoneAndVerticallyCompact || isWebViewQueriedSubject let height: CGFloat = hideSubjectsView ? 0 : subjectsViewHeight subjectsController.view.snp.remakeConstraints { make in make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView) make.top.equalTo(searchBarEnabled ? searchBar.snp.bottom : contentView) make.height.equalTo(height) } subjectsController.view.isHidden = hideSubjectsView } } private var isiPhoneAndVerticallyCompact: Bool { guard let container = delegate?.webViewContainingController() else { return false } return container.isVerticallyCompact() && UIDevice.current.userInterfaceIdiom == .phone } private var isWebViewQueriedSubject: Bool { guard let url = webView.url?.absoluteString else { return false } return url.contains(find: "\(QueryParameterKeys.subject)=") } private var courseInfoTemplate : String { return environment.config.discovery.course.webview.detailTemplate ?? "" } var isWebViewLoaded : Bool { return self.loadController.state.isLoaded } @objc public func load(withURL url: URL) { var discoveryURL = url if let baseURL = baseURL, let searchQuery = searchQuery { searchBar.text = searchQuery var params = self.params ?? [:] set(value: searchQuery, for: QueryParameterKeys.searchQuery, in: &params) if let url = DiscoveryWebViewHelper.buildQuery(baseURL: baseURL.URLString, params: params) { discoveryURL = url } } loadRequest(withURL: discoveryURL) } fileprivate func set(value: String, for key: String, in params: inout [String: String]) { params[key] = value.addingPercentEncodingForRFC3986 } fileprivate func loadRequest(withURL url: URL) { let request = URLRequest(url: url) webView.load(request) self.request = request } fileprivate func showError(error : NSError) { let buttonInfo = MessageButtonInfo(title: Strings.reload) {[weak self] in if let request = self?.request { self?.webView.load(request as URLRequest) self?.loadController.state = .Initial } } self.loadController.state = LoadState.failed(error: error, buttonInfo: buttonInfo) } deinit { urlObservation?.invalidate() NotificationCenter.default.removeObserver(self) } } extension DiscoveryWebViewHelper: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let request = navigationAction.request let isWebViewDelegateHandled = !(delegate?.webView(webView, shouldLoad: request) ?? true) if isWebViewDelegateHandled { decisionHandler(.cancel) } else { let capturedLink = navigationAction.navigationType == .linkActivated let outsideLink = (request.mainDocumentURL?.host != self.request?.url?.host) if let url = request.url, outsideLink || capturedLink { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } decisionHandler(.cancel) } else { decisionHandler(.allow) } } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loadController.state = .Loaded if let bar = bottomBar { bar.superview?.bringSubviewToFront(bar) } } private var discovryAccessibilityValue: String { switch discoveryType { case .course: return "findCoursesLoaded" case .program: return "findProgramsLoaded" case .degree: return "findDegreeLoaded" } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { showError(error: error as NSError) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showError(error: error as NSError) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host as NSString) { completionHandler(.useCredential, credential) } else { completionHandler(.performDefaultHandling, nil) } } } extension DiscoveryWebViewHelper: SubjectsViewControllerDelegate, PopularSubjectsViewControllerDelegate { private func filterCourses(with subject: Subject) { guard let baseURL = baseURL, var params = params else { return } set(value: subject.filter, for: QueryParameterKeys.subject, in: &params) environment.analytics.trackSubjectDiscovery(subjectID: subject.filter) if let url = DiscoveryWebViewHelper.buildQuery(baseURL: baseURL.URLString, params: params) { searchBar.resignFirstResponder() loadController.state = .Initial loadRequest(withURL: url) } } private func viewAllSubjects() { guard let container = delegate?.webViewContainingController() else { return } environment.analytics.trackSubjectDiscovery(subjectID: "View All Subjects") environment.router?.showAllSubjects(from: container, delegate: self) } func popularSubjectsViewController(_ controller: PopularSubjectsViewController, didSelect subject: Subject) { filterCourses(with: subject) } func didSelectViewAllSubjects(_ controller: PopularSubjectsViewController) { viewAllSubjects() } func subjectsViewController(_ controller: SubjectsViewController, didSelect subject: Subject) { filterCourses(with: subject) } } extension DiscoveryWebViewHelper: UISearchBarDelegate { func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return true } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard searchText.isEmpty, webView.url != baseURL, let baseURL = baseURL, var params = params, params[QueryParameterKeys.searchQuery] != nil else { return } removeParam(for: QueryParameterKeys.searchQuery, in: &params) if let URL = DiscoveryWebViewHelper.buildQuery(baseURL: baseURL.URLString, params: params) { loadRequest(withURL: URL) } } private func removeParam(for key: String, in params: inout [String: String]) { params.removeValue(forKey: key) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() var action = "landing_screen" if let _ = environment.session.currentUser { action = "discovery_tab" } environment.analytics.trackCourseSearch(search: searchBar.text ?? "", action: action) guard let searchText = searchBar.text, let baseURL = baseURL, var params = params else { return } set(value: searchText, for: QueryParameterKeys.searchQuery, in: &params) if let URL = DiscoveryWebViewHelper.buildQuery(baseURL: baseURL.URLString, params: params) { loadController.state = .Initial loadRequest(withURL: URL) } } static func buildQuery(baseURL: String, params: [String: String]) -> URL? { var query = baseURL for param in params { let join = query.contains("?") ? "&" : "?" let value = param.key + "=" + param.value if !query.contains(find: value) { query = query + join + value } } return URL(string: query) } } extension DiscoveryWebViewHelper { @objc var t_webView: WKWebView { return webView } } extension String { // Section 2.3 of RFC 3986 lists the characters that you should not percent encode as they have no special meaning in a URL: // // ALPHA / DIGIT / “-” / “.” / “_” / “~” // // Section 3.4 also explains that since a query will often itself include a URL it is preferable to not percent encode the slash (“/”) and question mark (“?”) var addingPercentEncodingForRFC3986: String { let unreserved = "-._~/?" var allowed: CharacterSet = .alphanumerics allowed.insert(charactersIn: unreserved) return addingPercentEncoding(withAllowedCharacters: allowed) ?? "" } } extension WKWebView { func disableZoom() { let source: String = "var meta = document.createElement('meta');" + "meta.name = 'viewport';" + "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" + "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);" let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) configuration.userContentController.addUserScript(script) } }
38.165577
208
0.650074
efbacec15af48452bc886e1ac5d5e2810e3b86f6
154
// // CGRect-Extension.swift // DouYuSwift // // Created by hoomsun on 2019/3/26. // Copyright © 2019年 hoomsun. All rights reserved. // import UIKit
15.4
51
0.675325
fbb2cf391a73287a7e56ee5a08322038b14edf92
523
// // UIColor-Extension.swift // DouYuProject // // Created by li king on 2017/11/6. // Copyright © 2017年 li king. All rights reserved. // import UIKit extension UIColor{ convenience init(r:CGFloat ,g :CGFloat ,b: CGFloat) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0) } //类方法 class func randomColor() -> UIColor{ return UIColor(r :CGFloat(arc4random_uniform(256)) , g : CGFloat(arc4random_uniform(256)), b : CGFloat(arc4random_uniform(256))) } }
24.904762
136
0.634799
761c51feaf1f5d326d569098dd008baa644236bd
2,668
// // KANavigationDrawerHelper.swift // KANavigationDrawerController // // Created by Kristoffer Arlefur on 04/19/2016. // Copyright (c) 2016 Kristoffer Arlefur. All rights reserved. // public enum Direction { case Up case Down case Left case Right } public struct KANavigationDrawerHelper { static let menuWidth: CGFloat = 300 static let animationDuration: NSTimeInterval = 0.4 static let percentThreshold: CGFloat = 0.3 static let snapshotTagNumber = 12345 static let shadowTagNumber = 123456 public static func calculateProgress(translationInView: CGPoint, viewBounds: CGRect, direction: Direction) -> CGFloat { let pointOnAxis: CGFloat let axisLength: CGFloat switch direction { case .Up, .Down: pointOnAxis = translationInView.y axisLength = viewBounds.height case .Left, .Right: pointOnAxis = translationInView.x axisLength = viewBounds.width } let movementOnAxis = pointOnAxis / axisLength let positiveMovementOnAxis: Float let positiveMovementOnAxisPercent: Float switch direction { case .Right, .Down: // positive positiveMovementOnAxis = fmaxf(Float(movementOnAxis), 0.0) positiveMovementOnAxisPercent = fminf(positiveMovementOnAxis, 1.0) return CGFloat(positiveMovementOnAxisPercent) case .Up, .Left: // negative positiveMovementOnAxis = fminf(Float(movementOnAxis), 0.0) positiveMovementOnAxisPercent = fmaxf(positiveMovementOnAxis, -1.0) return CGFloat(-positiveMovementOnAxisPercent) } } public static func mapGestureStateToInteractor(gestureState: UIGestureRecognizerState, progress: CGFloat, interactor: KANavigationDrawerInteractor?, triggerSegue: () -> ()) { guard let interactor = interactor else { return } switch gestureState { case .Began: interactor.hasStarted = true triggerSegue() case .Changed: interactor.shouldFinish = progress > percentThreshold interactor.updateInteractiveTransition(progress) case .Cancelled: interactor.hasStarted = false interactor.cancelInteractiveTransition() case .Ended: interactor.hasStarted = false interactor.shouldFinish ? interactor.finishInteractiveTransition() : interactor.cancelInteractiveTransition() default: break } } }
35.573333
119
0.636057
e8f49c012e2599c657738d37ed74d7d86ce969d3
2,165
// // AppDelegate.swift // SKKeyValueStore // // Created by ljk on 05/13/2021. // Copyright (c) 2021 ljk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
47.065217
285
0.753811
3a7c11f0b49f2d862184ef545d8073a7760fdd04
41,966
// // DefaultRouterRoutingTests.swift // VISPER-Wireframe_Tests // // Created by bartel on 21.11.17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import VISPER_Wireframe import VISPER_Wireframe_Core class DefaultWireframeTests: XCTestCase { func testAddsRoutePatternToRouter() throws { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let pattern = "/das/ist/ein/pattern" //Act try wireframe.add(routePattern:pattern) //Assert XCTAssert(router.invokedAdd) XCTAssertEqual(router.invokedAddParameters?.routePattern, pattern) } func testAddRoutingOptionProviderCallsComposedOptionProvider() throws { //Arrange let mockProvider = MockRoutingOptionProvider() let composedRoutingOptionProvider = MockComposedOptionProvider() let wireframe = DefaultWireframe(composedOptionProvider: composedRoutingOptionProvider) let priority = 10 //Act wireframe.add(optionProvider: mockProvider, priority: priority) //Assert AssertThat(composedRoutingOptionProvider.invokedAddParameters?.optionProvider, isOfType: MockRoutingOptionProvider.self, andEquals: mockProvider) XCTAssertEqual(composedRoutingOptionProvider.invokedAddParameters?.priority, priority) } func testAddHandlerCallsHandlerContainer(){ //Arrange let container = MockRoutingHandlerContainer() let wireframe = DefaultWireframe(routingHandlerContainer: container) let routeResult = DefaultRouteResult(routePattern: "/some/pattern", parameters: [:]) var didCallResponsibleHandler = false let responsibleHandler = { (routeResult: RouteResult) -> Bool in didCallResponsibleHandler = true return true } var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } let priority = 42 //Act XCTAssertNoThrow(try wireframe.add(priority: priority, responsibleFor: responsibleHandler, handler: handler)) //Assert XCTAssertTrue(container.invokedAdd) XCTAssertEqual(container.invokedAddParameters?.priority, priority) guard let responsibleHandlerParam = container.invokedAddResponsibleForParam else { XCTFail("responsibleHandler was not forwarded to handler container") return } XCTAssertFalse(didCallResponsibleHandler) _ = responsibleHandlerParam(routeResult) XCTAssertTrue(didCallResponsibleHandler) guard let handlerParam = container.invokedAddHandlerParam else { XCTFail("handler was not forwarded to handler container") return } XCTAssertFalse(didCallHandler) handlerParam(routeResult) XCTAssertTrue(didCallHandler) } func testAddControllerProviderCallsComposedControllerProvider() { //Arrange let mockProvider = MockControllerProvider() let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(composedControllerProvider: composedControllerProvider) let priority = 10 //Act wireframe.add(controllerProvider: mockProvider, priority: priority) //Assert AssertThat(composedControllerProvider.invokedAddParameters?.controllerProvider, isOfType: MockControllerProvider.self, andEquals: mockProvider) XCTAssertEqual(composedControllerProvider.invokedAddParameters?.priority, priority) } func testAddRoutingObserverCallsRoutingDelegate() { //Arrange let mockObserver = MockRoutingObserver() let routingDelegate = MockRoutingDelegate() let wireframe = DefaultWireframe(routingDelegate: routingDelegate) let priority = 10 let routePattern = "/test/pattern" //Act wireframe.add(routingObserver: mockObserver, priority: priority, routePattern: routePattern) //Assert AssertThat(routingDelegate.invokedAddParameters?.routingObserver, isOfType: MockRoutingObserver.self, andEquals: mockObserver) XCTAssertEqual(routingDelegate.invokedAddParameters?.routePattern, routePattern) XCTAssertEqual(routingDelegate.invokedAddParameters?.priority, priority) } func testAddRoutingPresenterCallsComposedRoutingPresenter() { //Arrange let mockPresenter = MockRoutingPresenter() let composedRoutingPresenter = MockComposedRoutingPresenter() let wireframe = DefaultWireframe(composedRoutingPresenter: composedRoutingPresenter) let priority = 10 //Act wireframe.add(routingPresenter: mockPresenter, priority: priority) //Assert AssertThat(composedRoutingPresenter.invokedAddParameters?.routingPresenter, isOfType: MockRoutingPresenter.self, andEquals: mockPresenter) XCTAssertEqual(composedRoutingPresenter.invokedAddParameters?.priority, priority) } func testCallsRouterOnRoute() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //Act //throws error since mock router does not give a result XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) let invokedParams = NSDictionary(dictionary:(router.invokedRouteUrlRoutingOptionParametersParameters?.parameters)!) XCTAssertEqual(invokedParams, NSDictionary(dictionary:parameters)) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: MockRoutingOption.self, andEquals: option) } func testCallsRouterOnController() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] //Act //throws error since mock router does not give a result XCTAssertThrowsError( try wireframe.controller(url: url, parameters: parameters) ) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) let invokedParams = NSDictionary(dictionary:(router.invokedRouteUrlRoutingOptionParametersParameters?.parameters)!) XCTAssertEqual(invokedParams, NSDictionary(dictionary:parameters)) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: GetControllerRoutingOption.self) } func testCanRouteCallsRouterForRouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //let routeResult = DefaultRouteResult(routePattern: url.absoluteURL, parameters: parameters, routingOption: option) let router = MockRouter() let wireframe = DefaultWireframe(router: router) //Act XCTAssertNoThrow(try wireframe.canRoute(url: url, parameters: parameters, option: option)) //Assert XCTAssertTrue(router.invokedRouteUrlRoutingOptionParameters) XCTAssertEqual(router.invokedRouteUrlRoutingOptionParametersParameters?.url, url) guard let invokedParams = router.invokedRouteUrlRoutingOptionParametersParameters?.parameters else { XCTFail("parameter psrameters should be invoked in routers route function") return } let invokedParamsDict = NSDictionary(dictionary: invokedParams) let paramsDict = NSDictionary(dictionary: parameters) XCTAssertEqual(invokedParamsDict, paramsDict) AssertThat(router.invokedRouteUrlRoutingOptionParametersParameters?.routingOption, isOfType: MockRoutingOption.self, andEquals: option) } func testCanRouteReturnsFalseIfRouterResolvesNoRouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let router = MockRouter() router.stubbedRouteResult = nil let wireframe = DefaultWireframe(router: router) //Act var canRoute = false XCTAssertNoThrow(canRoute = try wireframe.canRoute(url: url, parameters: parameters, option: option)) //Assert XCTAssertFalse(canRoute) } func testCanRouteReturnsTrueIfRouterResolvesARouteResult(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let routeResult = DefaultRouteResult(routePattern: url.absoluteString, parameters: parameters, routingOption: option) let router = MockRouter() router.stubbedRouteUrlRoutingOptionParametersResult = routeResult let wireframe = DefaultWireframe(router: router) //Act var canRoute = false XCTAssertNoThrow( canRoute = try wireframe.canRoute(url: url, parameters: parameters, option: option) ) //Assert XCTAssertTrue(canRoute) } func testRouteThrowsErrorWhenNoRoutePatternWasFound() { //Arrange let router = MockRouter() let wireframe = DefaultWireframe(router: router) let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //Act + Assert //throws error since mock router does not give a result XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw DefaultWireframeError.noRoutePatternFoundFor") { error in switch error { case DefaultWireframeError.noRoutePatternFoundFor(let errorUrl, let errorParameters): XCTAssertEqual(errorUrl, url) XCTAssertEqual(NSDictionary(dictionary: errorParameters), NSDictionary(dictionary:parameters)) default: XCTFail("should throw DefaultWireframeError.noRoutePatternFoundFor") } } } func testRouteCallsComposedRoutingOptionProviderWithRoutersRoutingResult() { //Arrange let router = MockRouter() let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedOptionProvider = MockComposedOptionProvider() let wireframe = DefaultWireframe(router: router,composedOptionProvider:composedOptionProvider) //Act //throws error since no controller can be provided afterwards, not important for this test XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedOptionProvider.invokedOption) AssertThat(composedOptionProvider.invokedOptionParameters?.routeResult, isOfType: DefaultRouteResult.self, andEquals: stubbedRouteResult) } func testRouteModifiesOptionByComposedRoutingObserver() { //Arrange let router = MockRouter() let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedOptionProvider = MockComposedOptionProvider() let optionProvidersOption = MockRoutingOption() composedOptionProvider.stubbedOptionResult = optionProvidersOption let wireframe = DefaultWireframe(router: router,composedOptionProvider:composedOptionProvider) // Act // throws error since no controller can be provided // the error should contain our modified routing option, // since it is called after modifing the route result by our option providers XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw DefaultWireframeError.canNotHandleRoute ") { error in switch error { case DefaultWireframeError.canNotHandleRoute(let result): //Assert AssertThat(result.routingOption, isOfType: MockRoutingOption.self, andEquals: optionProvidersOption) default: XCTFail("should throw DefaultWireframeError.canNotHandleRoute") } } } func testRouteCallsHandlerFromRoutingHandlerContainer() { //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false var handlerResult : RouteResult? let handler = { (routeResult: RouteResult) -> Void in handlerResult = routeResult didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer) //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertTrue(didCallHandler) XCTAssertTrue(handlerContainer.invokedPriorityOfHighestResponsibleProvider) XCTAssertTrue(handlerContainer.invokedHandler) guard let routeResult = handlerResult else { XCTFail("since the handler should be called there should be a result") return } XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) } func testRouteCallsCompletionWhenRoutingToHandler(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() handlerContainer.stubbedHandlerResult = { (routeResult: RouteResult) -> Void in } handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer) var didCallCompletion = false let completion = { didCallCompletion = true } //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: completion)) //Assert XCTAssertTrue(didCallCompletion) } func testRouteChecksIfComposedControllerProviderIsResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure composed controller provider let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testRouteDoesNotCallComposedControllerProviderIfItIsNotResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertFalse(composedControllerProvider.invokedMakeController) } func testRouteDoesThrowErrorIfComposedControllerProviderIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "should throw an error") { error in //Assert switch error { case DefaultWireframeError.canNotHandleRoute(let routeResult): XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) default: XCTFail("should throw a DefaultWireframeError.canNotHandleRoute error") } } } func testRouteDoesCallComposedControllerProviderIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertTrue(composedControllerProvider.invokedMakeController) } func testRouteChecksIfComposedRoutingPresenterIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() let wireframe = DefaultWireframe(router: router, composedRoutingPresenter: composedRoutingPresenter, composedControllerProvider:composedControllerProvider) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {})) //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) } func testRouteThrowsErrorIfComposedRoutingPresenterIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() composedRoutingPresenter.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router, composedRoutingPresenter: composedRoutingPresenter, composedControllerProvider:composedControllerProvider) // Act // throws error since no routing presenter is responsible XCTAssertThrowsError(try wireframe.route(url: url, parameters: parameters, option: option, completion: {}), "Should throw an DefaultWireframeError.noRoutingPresenterFoundFor error") { error in switch error { case DefaultWireframeError.noRoutingPresenterFoundFor(let routeResult): XCTAssertTrue(routeResult.isEqual(routeResult: stubbedRouteResult)) default: XCTFail("Should throw an DefaultWireframeError.noRoutingPresenterFoundFor error") } } //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) } func testRouteCallsComposedRoutingPresenterIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //configure mock routing presenter let composedRoutingPresenter = MockComposedRoutingPresenter() composedRoutingPresenter.stubbedIsResponsibleResult = true //configure mock routing delegate let routingDelegate = MockRoutingDelegate() let wireframe = DefaultWireframe(router: router, composedRoutingPresenter: composedRoutingPresenter, routingDelegate: routingDelegate, composedControllerProvider: composedControllerProvider) var didCallCompletion = false let completion = { didCallCompletion = true } // Act XCTAssertNoThrow(try wireframe.route(url: url, parameters: parameters, option: option, completion: completion)) //Assert XCTAssertTrue(composedRoutingPresenter.invokedIsResponsible) XCTAssertTrue(composedRoutingPresenter.invokedPresent) //assert params XCTAssertEqual(composedRoutingPresenter.invokedPresentParameters?.controller, composedControllerProvider.stubbedMakeControllerResult) AssertThat(composedRoutingPresenter.invokedPresentParameters?.routeResult, isOfType: DefaultRouteResult.self, andEquals: stubbedRouteResult) guard let wireframeParam = composedRoutingPresenter.invokedPresentParameters?.wireframe as? DefaultWireframe else { XCTFail("diden't foward wireframe to presenter") return } XCTAssertTrue(wireframe === wireframeParam) AssertThat(composedRoutingPresenter.invokedPresentParameters?.delegate, isOfType: MockRoutingDelegate.self, andEquals: routingDelegate) guard let complete = composedRoutingPresenter.invokedPresentParametersCompletion else { XCTFail("didn't forward completion to presenter") return } XCTAssertFalse(didCallCompletion) complete() XCTAssertTrue(didCallCompletion) } func testRouteChoosesHandlerIfItHasAHigherPriorityThanTheController(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 42 //configure composed controller provider to return a lower priority for the controller let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedPriorityOfHighestResponsibleProviderResult = 21 //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer, composedControllerProvider: composedControllerProvider) //Act XCTAssertNoThrow(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertTrue(didCallHandler) XCTAssertFalse(composedControllerProvider.invokedIsResponsible) } func testRouteChoosesControllerIfItHasAHigherPriorityThanAHandler(){ //Arrange //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: [:], routingOption: MockRoutingOption()) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure handler container to return a handler and a priority let handlerContainer = MockRoutingHandlerContainer() var didCallHandler = false let handler = { (routeResult: RouteResult) -> Void in didCallHandler = true } handlerContainer.stubbedHandlerResult = handler handlerContainer.stubbedPriorityOfHighestResponsibleProviderResult = 21 //configure composed controller provider to return a lower priority for the controller let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedPriorityOfHighestResponsibleProviderResult = 42 composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() //create wireframe with mock dependencies let wireframe = DefaultWireframe(router: router,routingHandlerContainer: handlerContainer, composedControllerProvider: composedControllerProvider) //Act // throws error since no presenter is available XCTAssertThrowsError(try wireframe.route(url: URL(string: stubbedRouteResult.routePattern)!, parameters: stubbedRouteResult.parameters, option: stubbedRouteResult.routingOption!, completion: {})) //Assert XCTAssertFalse(didCallHandler) XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testControllerChecksIfComposedControllerProviderIsResponsible() { let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure composed controller provider let composedControllerProvider = MockComposedControllerProvider() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) XCTAssertNoThrow(try wireframe.controller(url: url, parameters: parameters)) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) } func testControllerDoesNotCallComposedControllerProviderIfItIsNotResponsible(){ let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) XCTAssertNoThrow( try wireframe.controller(url: url,parameters: parameters) ) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertFalse(composedControllerProvider.invokedMakeController) } func testControllerReturnsNilIfComposedControllerProviderIsNotResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = false let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) // Act // throws error since no controller or handler can be provided var controller : UIViewController? XCTAssertNoThrow( controller = try wireframe.controller(url: url, parameters: parameters) ) XCTAssertNil(controller) } func testControllerDoesCallComposedControllerProviderIfItIsResponsible(){ //Arrange let url = URL(string: "/a/nice/path")! let parameters = ["id" : "42"] let option = MockRoutingOption() //configure router to return a result let router = MockRouter() let stubbedRouteResult = DefaultRouteResult(routePattern: "/a/nice/path", parameters: parameters, routingOption: option) router.stubbedRouteUrlRoutingOptionParametersResult = stubbedRouteResult //configure mock controller provider let composedControllerProvider = MockComposedControllerProvider() composedControllerProvider.stubbedIsResponsibleResult = true composedControllerProvider.stubbedMakeControllerResult = UIViewController() let wireframe = DefaultWireframe(router: router,composedControllerProvider:composedControllerProvider) var controller : UIViewController? XCTAssertNoThrow( controller = try wireframe.controller(url: url, parameters: parameters) ) //Assert XCTAssertTrue(composedControllerProvider.invokedIsResponsible) XCTAssertTrue(composedControllerProvider.invokedMakeController) XCTAssertEqual(controller,composedControllerProvider.stubbedMakeControllerResult) } }
42.43276
154
0.591574
0aa7cdd6225978b8c020db19376e0ba0c52fccb8
420
// // UIStackView.swift // OpenFoodFacts // // Created by Andrés Pizá Bückmann on 08/06/2017. // Copyright © 2017 Andrés Pizá Bückmann. All rights reserved. // import UIKit extension UIStackView { /// Remove all views in the stack view func removeAllViews() { for view in self.arrangedSubviews { self.removeArrangedSubview(view) view.removeFromSuperview() } } }
21
63
0.647619
46bb0a8a5a55f2ddde4619e6fd030c279af6e29b
12,996
// // ResponeBodyController.swift // NetKnot // // Created by Harry on 2020/12/8. // Copyright © 2020 Harry. All rights reserved. // // Mail: [email protected] // TEL : +85253054612 // import UIKit import TunnelServices import Highlightr class ResponeBodyController: IDEAViewController { @IBOutlet weak var imageView : YYAnimatedImageView!; @IBOutlet weak var textView : UITextView!; var currentFormatter : AFormatter!; var highlightr : Highlightr!; let textStorage : CodeAttributedString = CodeAttributedString(); var type : String = "" var encoding : String = "" var session : Session? = nil; override func viewDidLoad() { super.viewDidLoad(); // Do any additional setup after loading the view. self.type = self.session!.rspType.getRealType(); self.encoding = self.session!.rspEncoding; self.textStorage.language = "Tex"; var szFilePath = "\(self.session!.fileFolder ?? "error")/\(self.session!.rspBody)"; if TunnelService.DEBUG { TunnelService.Debug("RequestBodyController::viewDidLoad() : FilePath : \(szFilePath)"); } szFilePath = "\(MitmService.getStoreFolder())\(szFilePath)" if TunnelService.DEBUG { TunnelService.Debug("RequestBodyController::viewDidLoad() : FilePath : \(szFilePath)"); } if FileManager.default.fileExists(atPath: szFilePath) { do { var stData = try Data(contentsOf: URL(fileURLWithPath: "\(szFilePath)")); if CompressTypes.contains(self.encoding) { // 解码数据,解压之类 if self.encoding != "gzip" { if TunnelService.DEBUG { TunnelService.Debug("非gzip编码格式:\(encoding)"); } } /* End if () */ } /* End if () */ if stData.isGzipped { var stUnZipData = try stData.gunzipped(); if stUnZipData.count == 0 { stUnZipData = stData.gunzip() ?? stData.unzip() ?? stData.gunzip() ?? stData.inflate() ?? Data(); } /* End if () */ if stUnZipData.count > 0 { stData = stUnZipData; } /* End if () */ // stData = try stData.gunzipped() } /* End if () */ if ImageTypes.contains(self.type) { let stYYImage = YYImage(data: stData); // show image self.imageView.image = stYYImage; self.imageView.setImageWith(NSURL.fileURL(withPath: szFilePath), options: YYWebImageOptions(rawValue: 0)); self.title = "\(self.type) (\(Int(stYYImage?.size.width ?? 0)) × \(Int(stYYImage?.size.height ?? 0)))"; self.textView.isHidden = true; } /* End if () */ else { if let szFileContent = String(data: stData, encoding: .utf8) ,szFileContent != "" { self.title = "\(self.type) (\(Int(szFileContent.count)))"; // 文本展示 let stLayoutManager = NSLayoutManager(); self.textStorage.addLayoutManager(stLayoutManager); let stTextContainer = NSTextContainer(size: CGSize(width: self.view.width, height: 999999999)); stLayoutManager.addTextContainer(stTextContainer); // self.textView.textContainer = stTextContainer; self.textView.autocorrectionType = UITextAutocorrectionType.no; self.textView.autocapitalizationType = UITextAutocapitalizationType.none; self.textView.isEditable = false self.textView.textColorPicker = DKColorTable.shared()?.picker(withKey: APPColor.label()); self.textView.setFontWithName(APPFont.appFontRegular()); self.textView.backgroundColor = UIColor.clear var szShowText : String = szFileContent; // 甭管什么,先转换了再说 if let stJson = try? JSONSerialization.jsonObject(with: stData, options: JSONSerialization.ReadingOptions()) { if let stJsonData = try? JSONSerialization.data(withJSONObject: stJson, options: .prettyPrinted) { if let szJsonString = String(data: stJsonData, encoding: .utf8) { szShowText = szJsonString; textStorage.language = "json"; } /* End if () */ } /* End if () */ } /* End if () */ if self.type == "json" { self.textStorage.language = "json"; do { let stJson = try JSONSerialization.jsonObject(with: stData, options: JSONSerialization.ReadingOptions()) let stJsonData = try JSONSerialization.data(withJSONObject: stJson, options: .prettyPrinted) if let szJsonString = String(data: stJsonData, encoding: .utf8) { szShowText = szJsonString } else { if TunnelService.DEBUG { TunnelService.Debug("Parsing Json null "); } } } catch { if TunnelService.DEBUG { TunnelService.Debug("Parsing Json error: \(error)"); } } } else if JSTypes.contains(self.type) { self.textStorage.language = "javascript" } else if type == "html" { self.textStorage.language = "html" } else if CSSTypes.contains(type) { self.textStorage.language = "css" } else if urlEncodedTypes.contains(type) { szShowText = szFileContent.urlDecoded(); } if type == "" { self.title = "Text (\(Int(szFileContent.count)))"; } /* End if () */ self.textView.text = szShowText; } else { // 非文本内容,展示原始十六进制数据 self.textView.autocorrectionType = UITextAutocorrectionType.no; self.textView.autocapitalizationType = UITextAutocapitalizationType.none; self.textView.isEditable = false self.textView.textColorPicker = DKColorTable.shared()?.picker(withKey: APPColor.label()); self.textView.backgroundColor = UIColor.clear; self.textView.setFontWithName(APPFont.appFontRegular()); currentFormatter = AFormatter() currentFormatter.numberOfCharactersPerLine = 16 + (16 * 3) + (12) + 1 currentFormatter.currentDisplaySize = FORMATTER_DISPLAY_SIZE_WORD let stOriginalData = try Data(contentsOf: URL(fileURLWithPath: "\(szFilePath)")) self.title = "Hex (\(Float(stOriginalData.count).bytesFormatting())))" self.currentFormatter.data = stOriginalData; self.textView.text = currentFormatter.formattedString; self.title = "Hex \(stOriginalData.count)"; } /* End else */ self.imageView.isHidden = true; } /* End else */ } catch { if TunnelService.DEBUG { TunnelService.Debug("读取失败:\(error)"); } self.title = "Read failure".localized; } /* End catch */ } /* End if () */ return; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); // Dispose of any resources that can be recreated. return; } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); return; } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); return; } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated); return; } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated); return; } } // MARK: - Navigation extension ResponeBodyController { // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. return; } } // MARK: - UIStatusBarStyle extension ResponeBodyController { /// 状态栏样式 override var preferredStatusBarStyle : UIStatusBarStyle { if DKNightVersionManager.themeManager()?.themeVersion == DKThemeVersionNight { return UIStatusBarStyle.lightContent; } /* End if () */ else { if #available(iOS 13, *) { return UIStatusBarStyle.darkContent; } /* End if () */ return UIStatusBarStyle.default; } /* End else */ } /// 状态栏是否隐藏 override var prefersStatusBarHidden: Bool { return false; } /// 状态栏的隐藏与显示动画样式 override var preferredStatusBarUpdateAnimation : UIStatusBarAnimation { return UIStatusBarAnimation.fade; } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait; } override var shouldAutorotate : Bool { return false; } override var prefersHomeIndicatorAutoHidden : Bool { return true; } // MARK: - 模态样式 open override var modalPresentationStyle : UIModalPresentationStyle { get { return UIModalPresentationStyle.fullScreen; } set { super.modalPresentationStyle = newValue; } } } // MARK: - Data extension ResponeBodyController { func setSession(_ aSession : Session) -> Void { self.session = aSession; return; } } // MARK: - UITheme extension ResponeBodyController { @objc override func onThemeUpdate(_ aNotification : Notification) -> Void { if TunnelService.DEBUG {TunnelService.Debug("ResponeBodyController::onThemeUpdate(notification:)");} if super.responds(to: #selector(onThemeUpdate(_:))) { super.onThemeUpdate(aNotification); } /* End if () */ var stTitleAttributes : Dictionary<NSAttributedString.Key, Any>; if nil == self.navigationController?.navigationBar.titleTextAttributes { stTitleAttributes = NSMutableDictionary() as! [NSAttributedString.Key : Any]; } /* End if () */ else { stTitleAttributes = (self.navigationController?.navigationBar.titleTextAttributes)!; } /* End else */ stTitleAttributes.updateValue(IDEAColor.color(withKey: IDEAColor.label()), forKey: NSAttributedString.Key.foregroundColor); self.navigationController?.navigationBar.titleTextAttributes = stTitleAttributes; if DKThemeVersionNight == DKNightVersionManager.shared().themeVersion { } /* End if () */ else { } /* End else */ return; } }
34.56383
129
0.499769
50d60ccaeb1f06f81b353961df3a8da35e56add1
2,343
// // ViewStateSubscribingProxy.swift // ViewStateCore // // Created by NGUYEN CHI CONG on 7/25/19. // import Foundation public protocol DedicatedViewStateSubscriber: ViewStateSubscriber { associatedtype State: ViewState func dedicatedViewStateDidChange(newState: State) func dedicatedViewStateDidSubscribe(_ state: State) func dedicatedViewStateDidChange(newState: State, keyPath: String, oldValue: Any?, newValue: Any?) func dedicatedViewStateWillUnsubscribe(_ state: State) } // Optionals extension DedicatedViewStateSubscriber { public func dedicatedViewStateDidChange(newState: State, keyPath: String, oldValue: Any?, newValue: Any?) {} public func dedicatedViewStateWillUnsubscribe(_ state: State) {} } extension DedicatedViewStateSubscriber { public func viewStateDidChange(newState: ViewState) { guard let state = newState as? State else { return } dedicatedViewStateDidChange(newState: state) } public func viewStateDidChange(newState: ViewState, keyPath: String, oldValue: Any?, newValue: Any?) { guard let state = newState as? State else { return } dedicatedViewStateDidChange(newState: state, keyPath: keyPath, oldValue: oldValue, newValue: newValue) } public func viewStateDidSubscribe(_ state: ViewState) { guard let state = state as? State else { return } dedicatedViewStateDidSubscribe(state) } public func viewStateWillUnsubscribe(_ state: ViewState) { guard let state = state as? State else { return } dedicatedViewStateWillUnsubscribe(state) } } public protocol DedicatedViewStateFillable: ViewStateFillable { associatedtype State: ViewState func dedicatedFillingOptions(_ state: State) -> [FillingOption] } extension DedicatedViewStateFillable { public func fillingOptions(_ state: ViewState) -> [FillingOption] { guard let state = state as? State else { return [] } return dedicatedFillingOptions(state) } } public protocol DedicatedViewStateRenderable: ViewStateRenderable { associatedtype State: ViewState func dedicatedRender(state: State) } extension DedicatedViewStateRenderable { public func render(state: ViewState) { guard let state = state as? State else { return } return dedicatedRender(state: state) } }
32.09589
112
0.735382
39b6349a9964d1fcb7f9bef12d644ad2f4d4a672
108
// // MultiPager.swift // Created by ctslin on 3/3/16. import UIKit class MultiPager: DefaultView { }
9.818182
32
0.675926
fc3d5af47ed5e8fb3e8719b293117fca8f3f6c84
463
// // MockTimeProvider.swift // MarvelApiClient // // Created by Pedro Vicente on 14/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation @testable import MarvelApiClient class MockTimeProvider: TimeProvider { var time: Int init(time: Int) { self.time = time } override convenience init() { self.init(time: 0) } override func currentTimeMillis() -> Int { return time } }
16.535714
55
0.634989
e883b6531cb11ffe4567700557698bd3d1272b1f
1,530
// // ViewController.swift // wemo_widget // // Created by Chris Kuburlis on 28/09/2014. // Copyright (c) 2014 Chris Kuburlis. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { // NSUserDefaults share to store settings (shared with widget) let sharedDefaults = NSUserDefaults(suiteName: "group.k-dev.WemoWidgetSharingDefaults") @IBOutlet weak var IPAddressTextBox: UITextField! @IBOutlet weak var saveButtonOutlet: UIButton! @IBAction func saveButton(sender: AnyObject?) { // hides keyboard IPAddressTextBox.resignFirstResponder() // Puts string in NSUserDefaults and synchronises to save changes sharedDefaults?.setObject(IPAddressTextBox.text, forKey: "IPAddress") sharedDefaults?.synchronize() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Fills textbox with previously set IP or an empty string IPAddressTextBox.text = sharedDefaults?.stringForKey("IPAddress") ?? "" IPAddressTextBox.delegate = self } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() saveButton(nil) return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
28.333333
91
0.670588
e484f333feb879b8fb4ce67772becedf87b4d6cd
48,594
// // Copyright © 2019 MBition GmbH. All rights reserved. // import Foundation import SwiftProtobuf import MBCommonKit // swiftlint:disable function_body_length // swiftlint:disable type_body_length class ProtoMessageParser { // MARK: Typealias typealias CommandRequestTriple = (data: Data?, requestId: String, vin: String) typealias ParseCompletion = (MessageType) -> Void // MARK: Enum enum MessageType { case assignedVehicles(model: AssignedVehiclesModel) case vehicleCommandStatusUpdate(model: VehicleCommandStatusUpdateModel) case debugMessage(message: String) case pendingCommands(data: Data) case serviceUpdate(model: VehicleServicesStatusUpdateModel) case serviceUpdates(models: [VehicleServicesStatusUpdateModel]) case vehicleUpdate(model: VehicleUpdatedModel) case vepUpdate(model: VehicleStatusDTO) case vepUpdates(models: [VehicleStatusDTO]) } // MARK: Properties private var parseCompletion: ParseCompletion? // MARK: - Public func createLogoutMessage() -> Data? { let clientMessage = Proto_ClientMessage.with { $0.logout = Proto_Logout() } return ProtoMessageParser.serialized(clientMessage: clientMessage) } func parse(data: Data, completion: ParseCompletion?) { self.parseCompletion = completion self.handle(message: try? Proto_PushMessage(serializedData: data)) } // MARK: - Helper private func createAcknowledgeAbilityToGetVehicleMasterDataFromRestAPI(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeAbilityToGetVehicleMasterDataFromRestAPI.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeAbilityToGetVehicleMasterDataFromRestApi = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeAppTwinCommandStatusUpdatesClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeAppTwinCommandStatusUpdatesByVIN.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeApptwinCommandStatusUpdateByVin = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeAssignedVehicles() -> Data? { let acknowledge = Proto_AcknowledgeAssignedVehicles() let clientMessage = Proto_ClientMessage.with { $0.acknowledgeAssignedVehicles = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgePreferredDealerChangeClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgePreferredDealerChange.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgePreferredDealerChange = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeServiceStatusUpdateClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeServiceStatusUpdate.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeServiceStatusUpdate = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeServiceStatusUpdatesClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeServiceStatusUpdatesByVIN.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeServiceStatusUpdatesByVin = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeVehicleUpdateClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeVehicleUpdated.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeVehicleUpdated = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeVEPClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeVEPRequest.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeVepRequest = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createAcknowledgeVEPByVINClientMessage(with sequenceNumber: Int32) -> Data? { let acknowledge = Proto_AcknowledgeVEPUpdatesByVIN.with { $0.sequenceNumber = sequenceNumber } let clientMessage = Proto_ClientMessage.with { $0.acknowledgeVepUpdatesByVin = acknowledge } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private func createDTO(clientMessageData: Data?, vepUpdate: Proto_VEPUpdate) -> VehicleStatusDTO { let statusUpdateModel = self.map(vepUpdate: vepUpdate, clientMessageData: clientMessageData) if CarKit.selectedFinOrVin == vepUpdate.vin { LOG.D(vepUpdate.attributes) LOG.D(statusUpdateModel) } return statusUpdateModel } private func createEmptyDTO(clientMessageData: Data?, vepUpdate: Proto_VEPUpdate) -> VehicleStatusDTO { let vehicleStatusDTO = VehicleStatusDTO(fullUpdate: vepUpdate.fullUpdate, sequenceNumber: vepUpdate.sequenceNumber, vin: vepUpdate.vin) vehicleStatusDTO.clientMessageData = clientMessageData return vehicleStatusDTO } private func handle(assignedVehicles: Proto_AssignedVehicles) { LOG.D("assigned vehicles message: \(assignedVehicles.vins.joined(separator: ", "))") let clientMessageData = self.createAcknowledgeAssignedVehicles() let assignedVehicles = AssignedVehiclesModel(clientMessageData: clientMessageData, vins: assignedVehicles.vins) self.parseCompletion?(.assignedVehicles(model: assignedVehicles)) } private func handle(debugMessage: Proto_DebugMessage) { LOG.D("debug message: \(debugMessage.message)") self.parseCompletion?(.debugMessage(message: debugMessage.message)) } private func handle(message: Proto_PushMessage?) { guard let msg = message?.msg else { LOG.D("no valid message type...") return } LOG.D("receive message...") switch msg { case .apptwinCommandStatusUpdatesByVin(let commandStatusUpdates): self.handle(commandStatusUpdates: commandStatusUpdates) case .apptwinPendingCommandRequest(let pendingCommandsRequest): self.handle(pendingCommandsRequest: pendingCommandsRequest) case .assignedVehicles(let assignedVehicles): self.handle(assignedVehicles: assignedVehicles) case .debugMessage(let debugMessage): self.handle(debugMessage: debugMessage) case .preferredDealerChange(let preferredDealerChange): self.handle(preferredDealerChange: preferredDealerChange) case .serviceStatusUpdate(let serviceStatusUpdate): self.handle(serviceStatusUpdate: serviceStatusUpdate) case .serviceStatusUpdates(let serviceStatusUpdates): self.handle(serviceStatusUpdates: serviceStatusUpdates) case .userDataUpdate: break case .userPictureUpdate: break case .userPinUpdate: break case .userVehicleAuthChangedUpdate(let userVehicleAuthChangedUpdate): self.handle(userVehicleAuthChangedUpdate: userVehicleAuthChangedUpdate) case .vehicleUpdated(let vehicleUpdate): self.handle(vehicleUpdate: vehicleUpdate) case .vepUpdate(let vepUpdate): self.handle(vepUpdate: vepUpdate) case .vepUpdates(let vepUpdates): self.handle(vepUpdates: vepUpdates) } } private func handle(commandStatusUpdates: Proto_AppTwinCommandStatusUpdatesByPID, clientMessageData: Data?, sequenceNumber: Int32) { guard commandStatusUpdates.updatesByPid.isEmpty == false else { LOG.D("no vehicle api command status updates for vin \(commandStatusUpdates.vin)") return } LOG.D("vehicle api command status update") // updates that were triggered by the new commands API var newUpdates = Proto_AppTwinCommandStatusUpdatesByPID() commandStatusUpdates.updatesByPid.forEach { (pid, commandStatus: Proto_AppTwinCommandStatus) in self.track(commandStatus: commandStatus, finOrVin: commandStatusUpdates.vin) if commandStatus.requestID.isEmpty { return } // New commands API if let savedRequestModel = VehicleCommandRequestService.commandRequestModelFor(uuid: commandStatus.requestID) { let newRequestModel = savedRequestModel.updateFullStatus(with: commandStatus) VehicleCommandRequestService.set(commandRequestModel: newRequestModel) newUpdates.updatesByPid[pid] = commandStatus } } // New commands API if newUpdates.updatesByPid.count > 0 { let commandStatusUpdateModel = VehicleCommandStatusUpdateModel(requestIDs: newUpdates.updatesByPid.map { $1.requestID }, clientMessageData: clientMessageData, sequenceNumber: sequenceNumber, vin: commandStatusUpdates.vin) if CarKit.selectedFinOrVin == commandStatusUpdates.vin { LOG.D(commandStatusUpdateModel) } self.parseCompletion?(.vehicleCommandStatusUpdate(model: commandStatusUpdateModel)) } if CarKit.selectedFinOrVin == commandStatusUpdates.vin { LOG.D(commandStatusUpdates.updatesByPid) } } private func handle(commandStatusUpdates: Proto_AppTwinCommandStatusUpdatesByVIN) { LOG.D("vehicle api command status updates: \(commandStatusUpdates)") let clientMessageData = self.createAcknowledgeAppTwinCommandStatusUpdatesClientMessage(with: commandStatusUpdates.sequenceNumber) commandStatusUpdates.updatesByVin.forEach { (vin, updatesByPid) in if vin.isEmpty == false { self.handle(commandStatusUpdates: updatesByPid, clientMessageData: clientMessageData, sequenceNumber: commandStatusUpdates.sequenceNumber) } } } private func handle(pendingCommandsRequest: Proto_AppTwinPendingCommandsRequest) { LOG.D("pending commands request") let pendingCommands = VehicleCommandRequestService.all().map { (commandRequestModel) -> Proto_PendingCommand in return Proto_PendingCommand.with { $0.processID = commandRequestModel.processId $0.requestID = commandRequestModel.requestId $0.type = commandRequestModel.commandType $0.vin = commandRequestModel.vin } } let message = Proto_AppTwinPendingCommandsResponse.with { $0.pendingCommands = pendingCommands } let clientMessage = Proto_ClientMessage.with { $0.apptwinPendingCommandsResponse = message } guard let data = ProtoMessageParser.serialized(clientMessage: clientMessage) else { return } self.parseCompletion?(.pendingCommands(data: data)) } private func handle(preferredDealerChange: Proto_PreferredDealerChange) { LOG.D("preferred dealer change") let clientMessageData = self.createAcknowledgePreferredDealerChangeClientMessage(with: preferredDealerChange.sequenceNumber) let vehicleUpdatedModel = VehicleUpdatedModel(clientMessageData: clientMessageData, eventTimestamp: preferredDealerChange.emitTimestampInMs, sequenceNumber: preferredDealerChange.sequenceNumber) self.parseCompletion?(.vehicleUpdate(model: vehicleUpdatedModel)) } private func handle(serviceStatusUpdate: Proto_ServiceStatusUpdate) { guard serviceStatusUpdate.updates.isEmpty == false else { LOG.D("no service status update attributes") return } LOG.D("service status update") let clientMessageData = self.createAcknowledgeServiceStatusUpdateClientMessage(with: serviceStatusUpdate.sequenceNumber) let serviceUpdateGroupModel = self.map(serviceStatusUpdate: serviceStatusUpdate, clientMessageData: clientMessageData) LOG.D(serviceStatusUpdate.updates) LOG.D(serviceUpdateGroupModel) self.parseCompletion?(.serviceUpdate(model: serviceUpdateGroupModel)) } private func handle(serviceStatusUpdates: Proto_ServiceStatusUpdatesByVIN) { LOG.D("service status updates by vin") let clientMessageData = self.createAcknowledgeServiceStatusUpdatesClientMessage(with: serviceStatusUpdates.sequenceNumber) let serviceUpdateGroupModels = serviceStatusUpdates.updates.map { (arg) -> VehicleServicesStatusUpdateModel in let (_, serviceStatusUpdate) = arg return self.map(serviceStatusUpdate: serviceStatusUpdate, clientMessageData: clientMessageData) } LOG.D(serviceStatusUpdates.updates) LOG.D(serviceUpdateGroupModels) self.parseCompletion?(.serviceUpdates(models: serviceUpdateGroupModels)) } private func handle(userVehicleAuthChangedUpdate: Proto_UserVehicleAuthChangedUpdate) { LOG.D("user vehicle auth changed update") let clientMessageData = self.createAcknowledgeAbilityToGetVehicleMasterDataFromRestAPI(with: userVehicleAuthChangedUpdate.sequenceNumber) let vehicleUpdatedModel = VehicleUpdatedModel(clientMessageData: clientMessageData, eventTimestamp: userVehicleAuthChangedUpdate.emitTimestampInMs, sequenceNumber: userVehicleAuthChangedUpdate.sequenceNumber) self.parseCompletion?(.vehicleUpdate(model: vehicleUpdatedModel)) } private func handle(vehicleUpdate: Proto_VehicleUpdated) { LOG.D("vehicle update") let clientMessageData = self.createAcknowledgeVehicleUpdateClientMessage(with: vehicleUpdate.sequenceNumber) let vehicleUpdatedModel = VehicleUpdatedModel(clientMessageData: clientMessageData, eventTimestamp: vehicleUpdate.emitTimestampInMs, sequenceNumber: vehicleUpdate.sequenceNumber) self.parseCompletion?(.vehicleUpdate(model: vehicleUpdatedModel)) } private func handle(vepUpdate: Proto_VEPUpdate) { LOG.D("vep update") let clientMessageData = self.createAcknowledgeVEPClientMessage(with: vepUpdate.sequenceNumber) let statusUpdateModel: VehicleStatusDTO = { guard vepUpdate.attributes.isEmpty == false else { LOG.D("no vep update attributes") return self.createEmptyDTO(clientMessageData: clientMessageData, vepUpdate: vepUpdate) } return self.createDTO(clientMessageData: clientMessageData, vepUpdate: vepUpdate) }() self.parseCompletion?(.vepUpdate(model: statusUpdateModel)) } private func handle(vepUpdates: Proto_VEPUpdatesByVIN) { LOG.D("vep updates: \(vepUpdates)") let clientMessageData = self.createAcknowledgeVEPByVINClientMessage(with: vepUpdates.sequenceNumber) let statusUpdateModels: [VehicleStatusDTO] = vepUpdates.updates.compactMap { (vin, vepUpdate) -> VehicleStatusDTO? in guard vin.isEmpty == false, vepUpdate.attributes.isEmpty == false else { return self.createEmptyDTO(clientMessageData: clientMessageData, vepUpdate: vepUpdate) } return self.createDTO(clientMessageData: clientMessageData, vepUpdate: vepUpdate) } self.parseCompletion?(.vepUpdates(models: statusUpdateModels)) } private class func serialized(commandRequest: Proto_CommandRequest) -> Data? { let clientMessage = Proto_ClientMessage.with { $0.commandRequest = commandRequest } return ProtoMessageParser.serialized(clientMessage: clientMessage) } private class func serialized(clientMessage: Proto_ClientMessage) -> Data? { do { return try clientMessage.serializedData() } catch { LOG.E("error: serialized client message") } return nil } private func track(commandStatus: Proto_AppTwinCommandStatus, finOrVin: String) { let myCarTrackingEvent: MyCarTrackingEvent? = { switch commandStatus.type { case .auxheatConfigure: return .configureAuxHeat(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .auxheatStart: return .startAuxHeat(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .auxheatStop: return .stopAuxHeat(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .doorsLock: return .doorLock(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .doorsUnlock: return .doorUnlock(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .engineStart: return .engineStart(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .engineStop: return .engineStop(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .roofclose: return .closeSunroof(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .rooflift: return .liftSunroof(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .roofopen: return .openSunroof(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .windowclose: return .closeWindow(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") case .windowopen: return .openWindow(fin: finOrVin, state: self.map(commandState: commandStatus.state), condition: "") default: return nil } }() guard let trackingEvent = myCarTrackingEvent else { return } MBTrackingManager.track(event: trackingEvent) } // MARK: - BusinessModel private func dayTime<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<[DayTimeModel], T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let dayTimeArray: [DayTimeModel] = attribute.weeklySettingsHeadUnitValue.weeklySettings.compactMap { guard let day = Day(rawValue: Int($0.day)) else { return nil } return DayTimeModel(day: day, time: Int($0.minutesSinceMidnight)) } return VehicleStatusAttributeModel<[DayTimeModel], T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: nil, value: dayTimeArray) } private func map(commandState: Proto_VehicleAPI.CommandState) -> CommandState { switch commandState { case .enqueued: return .enqueued case .failed: return .failed case .finished: return .finished case .initiation: return .initiation case .processing: return .processing case .unknownCommandState: return .unknown case .UNRECOGNIZED: return .unknown case .waiting: return .waiting } } private func map(serviceStatusUpdate: Proto_ServiceStatusUpdate, clientMessageData: Data?) -> VehicleServicesStatusUpdateModel { let services = serviceStatusUpdate.updates.map { (arg) -> VehicleServiceStatusUpdateModel in let (key, value) = arg return VehicleServiceStatusUpdateModel(id: Int(key), status: self.map(status: value)) } return VehicleServicesStatusUpdateModel(clientMessageData: clientMessageData, finOrVin: serviceStatusUpdate.vin, sequenceNumber: serviceStatusUpdate.sequenceNumber, services: services) } private func map(status: Proto_ServiceStatus) -> ServiceActivationStatus { switch status { case .activationPending: return .activationPending case .active: return .active case .deactivationPending: return .deactivationPending case .inactive: return .inactive case .unknown: return .unknown case .UNRECOGNIZED: return .unknown } } private func map(vepUpdate: Proto_VEPUpdate, clientMessageData: Data?) -> VehicleStatusDTO { let dto = VehicleStatusDTO(fullUpdate: vepUpdate.fullUpdate, sequenceNumber: vepUpdate.sequenceNumber, vin: vepUpdate.vin) dto.auxheatActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatActive]) dto.auxheatRuntime = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatRuntime]) dto.auxheatState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatStatus]) dto.auxheatTime1 = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatTime1]) dto.auxheatTime2 = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatTime2]) dto.auxheatTime3 = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatTime3]) dto.auxheatTimeSelection = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatTimeSelection]) dto.auxheatWarnings = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.auxheatWarnings]) dto.averageSpeedReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.averageSpeedReset]) dto.averageSpeedStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.averageSpeedStart]) dto.chargePrograms = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargePrograms]) dto.chargingActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargingActive]) dto.chargingError = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargingErrorDetails]) dto.chargingMode = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargingMode]) dto.chargingPower = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargingPower]) dto.chargingStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.chargingStatus]) dto.clientMessageData = clientMessageData dto.decklidLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusDecklid]) dto.decklidState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.decklidStatus]) dto.departureTime = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.departureTime]) dto.departureTimeMode = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.departureTimeMode]) dto.departureTimeSoc = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.departureTimeSoc]) dto.departureTimeWeekday = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.departureTimeWeekday]) dto.distanceElectricalReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceElectricalReset]) dto.distanceElectricalStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceElectricalStart]) dto.distanceGasReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceGasReset]) dto.distanceGasStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceGasStart]) dto.distanceReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceReset]) dto.distanceStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceStart]) dto.distanceZEReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceZEReset]) dto.distanceZEStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.distanceZEStart]) dto.doorFrontLeftLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusFrontLeft]) dto.doorFrontLeftState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorStatusFrontLeft]) dto.doorFrontRightLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusFrontRight]) dto.doorFrontRightState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorStatusFrontRight]) dto.doorLockStatusGas = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusGas]) dto.doorLockStatusOverall = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusOverall]) dto.doorLockStatusVehicle = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusVehicle]) dto.doorRearLeftLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusRearLeft]) dto.doorRearLeftState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorStatusRearLeft]) dto.doorRearRightLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorLockStatusRearRight]) dto.doorRearRightState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorStatusRearRight]) dto.doorStatusOverall = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.doorStatusOverall]) dto.drivenTimeReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.drivenTimeReset]) dto.drivenTimeStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.drivenTimeStart]) dto.drivenTimeZEReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.drivenTimeZEReset]) dto.drivenTimeZEStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.drivenTimeZEStart]) dto.ecoScoreAccel = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ecoScoreAccel]) dto.ecoScoreBonusRange = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ecoScoreBonusRange]) dto.ecoScoreConst = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ecoScoreConst]) dto.ecoScoreFreeWhl = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ecoScoreFreeWhl]) dto.ecoScoreTotal = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ecoScoreTotal]) dto.electricConsumptionReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.electricConsumptionReset]) dto.electricConsumptionStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.electricConsumptionStart]) dto.electricalRangeSkipIndication = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.electricalRangeSkipIndication]) dto.endOfChargeTime = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.endOfChargeTime]) dto.endOfChargeTimeRelative = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.endOfChargeTimeRelative]) dto.endOfChargeTimeWeekday = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.endOfChargeTimeWeekday]) dto.engineHoodStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.engineHoodStatus]) dto.engineState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.engineState]) dto.eventTimestamp = vepUpdate.emitTimestampInMs dto.filterParticleLoading = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.filterParticleLoading]) dto.gasConsumptionReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.gasConsumptionReset]) dto.gasConsumptionStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.gasConsumptionStart]) dto.hybridWarnings = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.hybridWarnings]) dto.ignitionState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.ignitionState]) dto.interiorProtectionSensorStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.interiorProtectionSensorStatus]) dto.keyActivationState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.keyActivationState]) dto.languageHU = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.languageHU]) dto.lastParkEvent = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.lastParkEvent]) dto.lastTheftWarning = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.lastTheftWarning]) dto.lastTheftWarningReason = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.lastTheftWarningReason]) dto.liquidConsumptionReset = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.liquidConsumptionReset]) dto.liquidConsumptionStart = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.liquidConsumptionStart]) dto.liquidRangeSkipIndication = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.liquidRangeSkipIndication]) dto.maxRange = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.maxRange]) dto.maxSoc = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.maxSoc]) dto.maxSocLowerLimit = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.maxSocLowerLimit]) dto.odo = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.odo]) dto.parkBrakeStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.parkBrakeStatus]) dto.parkEventLevel = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.parkEventLevel]) dto.parkEventSensorStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.parkEventSensorStatus]) dto.parkEventType = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.parkEventType]) dto.positionErrorCode = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.positionErrorCode]) dto.positionHeading = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.positionHeading]) dto.positionLat = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.positionLat]) dto.positionLong = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.positionLong]) dto.precondActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondActive]) dto.precondAtDeparture = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondAtDeparture]) dto.precondAtDepartureDisable = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondAtDepartureDisable]) dto.precondDuration = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondDuration]) dto.precondError = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondError]) dto.precondNow = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondNow]) dto.precondNowError = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondNowError]) dto.precondSeatFrontLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondSeatFrontLeft]) dto.precondSeatFrontRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondSeatFrontRight]) dto.precondSeatRearLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondSeatRearLeft]) dto.precondSeatRearRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.precondSeatRearRight]) dto.proximityCalculationForVehiclePositionRequired = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.proximityCalculationForVehiclePositionRequired]) dto.remoteStartActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.remoteStartActive]) dto.remoteStartEndtime = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.remoteStartEndtime]) dto.remoteStartTemperature = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.remoteStartTemperature]) dto.roofTopStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.roofTopStatus]) dto.selectedChargeProgram = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.selectedChargeProgram]) dto.serviceIntervalDays = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.serviceIntervalDays]) dto.serviceIntervalDistance = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.serviceIntervalDistance]) dto.smartCharging = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.smartCharging]) dto.smartChargingAtDeparture = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.smartChargingAtDeparture]) dto.smartChargingAtDeparture2 = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.smartChargingAtDeparture2]) dto.speedAlert = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.speedAlert]) dto.soc = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.soc]) dto.socProfile = self.socProfile(for: vepUpdate.attributes[ProtoMessageKey.socProfile]) dto.speedUnitFromIC = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.speedUnitFromIC]) dto.starterBatteryState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.starterBatteryState]) dto.sunroofEventState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.sunroofEvent]) dto.sunroofEventActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.sunroofEventActive]) dto.sunnroofState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.sunroofStatus]) dto.tankAdBlueLevel = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tankLevelAdBlue]) dto.tankElectricRange = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.rangeElectric]) dto.tankGasLevel = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.gasTankLevel]) dto.tankGasRange = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.gasTankRange]) dto.tankLiquidLevel = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tankLevelPercent]) dto.tankLiquidRange = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.rangeLiquid]) dto.temperaturePointFrontCenter = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .frontCenter) dto.temperaturePointFrontLeft = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .frontLeft) dto.temperaturePointFrontRight = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .frontRight) dto.temperaturePointRearCenter = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .rearCenter) dto.temperaturePointRearCenter2 = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .rear2center) dto.temperaturePointRearLeft = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .rearLeft) dto.temperaturePointRearRight = self.temperaturePoints(for: vepUpdate.attributes[ProtoMessageKey.temperaturePoints], zone: .rearRight) dto.temperatureUnitHU = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.temperatureUnitHU]) dto.theftSystemArmed = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.theftSystemArmed]) dto.theftAlarmActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.theftAlarmActive]) dto.timeFormatHU = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.timeFormatHU]) dto.tireMarkerFrontLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireMarkerFrontLeft]) dto.tireMarkerFrontRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireMarkerFrontRight]) dto.tireMarkerRearLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireMarkerRearLeft]) dto.tireMarkerRearRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireMarkerRearRight]) dto.tirePressureFrontLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tirePressureFrontLeft]) dto.tirePressureFrontRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tirePressureFrontRight]) dto.tirePressureMeasTimestamp = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tirePressMeasTimestamp]) dto.tirePressureRearLeft = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tirePressureRearLeft]) dto.tirePressureRearRight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tirePressureRearRight]) dto.tireSensorAvailable = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireSensorAvailable]) dto.towProtectionSensorStatus = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.towProtectionSensorStatus]) dto.trackingStateHU = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.trackingStateHU]) dto.vehicleDataConnectionState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.vehicleDataConnectionState]) dto.vehicleLockState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.vehicleLockState]) dto.vTime = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.vTime]) dto.warningBreakFluid = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.warningBrakeFluid]) dto.warningBrakeLiningWear = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.warningBrakeLiningWear]) dto.warningCoolantLevelLow = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.warningCoolantLevelLow]) dto.warningEngineLight = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.warningEngineLight]) dto.warningTireLamp = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireWarningLamp]) dto.warningTireLevelPrw = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireWarningLevelPrw]) dto.warningTireSprw = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireWarningSprw]) dto.warningTireSrdk = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.tireWarningSrdk]) dto.warningWashWater = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.warningWashWater]) dto.weekdaytariff = self.tariff(for: vepUpdate.attributes[ProtoMessageKey.weekdaytariff], type: .weekday) dto.weekendtariff = self.tariff(for: vepUpdate.attributes[ProtoMessageKey.weekendtariff], type: .weekend) dto.weeklyProfile = self.weeklyProfile(for: vepUpdate.attributes[ProtoMessageKey.weeklyProfile]) dto.weeklySetHU = self.dayTime(for: vepUpdate.attributes[ProtoMessageKey.weeklySetHU]) dto.windowFrontLeftState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.windowStatusFrontLeft]) dto.windowFrontRightState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.windowStatusFrontRight]) dto.windowRearLeftState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.windowStatusRearLeft]) dto.windowRearRightState = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.windowStatusRearRight]) dto.windowStatusOverall = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.windowStatusOverall]) dto.zevActive = self.vehicleStatusUpdate(for: vepUpdate.attributes[ProtoMessageKey.active]) return dto } private func attributeUnit<T: RawRepresentable>(for attribute: Proto_VehicleAttributeStatus) -> VehicleAttributeUnitModel<T>? where T.RawValue == Int { guard let displayUnit = attribute.displayUnit else { return nil } switch displayUnit { case .clockHourUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .combustionConsumptionUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .distanceUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .electricityConsumptionUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .gasConsumptionUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .pressureUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .ratioUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .speedDistanceUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .speedUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) case .temperatureUnit(let unit): return VehicleAttributeUnitModel<T>(value: attribute.displayValue, unit: T(rawValue: unit.rawValue)) } } private func weeklyProfile<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<WeeklyProfileModel, T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let weeklyProfileValue = attribute.weeklyProfileValue let timeProfiles = weeklyProfileValue.timeProfiles.map { return TimeProfile(identifier: Int($0.identifier), hour: Int($0.hour), minute: Int($0.minute), active: $0.active, days: Set.init($0.days.compactMap(Day.fromTimeProfileDay))) } let value = WeeklyProfileModel(singleEntriesActivatable: weeklyProfileValue.singleTimeProfileEntriesActivatable, maxSlots: Int(weeklyProfileValue.maxNumberOfWeeklyTimeProfileSlots), maxTimeProfiles: Int(weeklyProfileValue.maxNumberOfTimeProfiles), currentSlots: Int(weeklyProfileValue.currentNumberOfTimeProfileSlots), currentTimeProfiles: Int(weeklyProfileValue.currentNumberOfTimeProfiles), allTimeProfiles: timeProfiles) return VehicleStatusAttributeModel<WeeklyProfileModel, T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: nil, value: value) } private func socProfile<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<[VehicleZEVSocProfileModel], T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let value = attribute.stateOfChargeProfileValue.statesOfCharge.map { VehicleZEVSocProfileModel(soc: $0.stateOfCharge, time: $0.timestampInS)} return VehicleStatusAttributeModel<[VehicleZEVSocProfileModel], T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: nil, value: value) } private func tariff<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?, type: TariffType) -> VehicleStatusAttributeModel<[VehicleZEVTariffModel], T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let value: [VehicleZEVTariffModel] = { switch type { case .weekday: return attribute.weekdayTariffValue.tariffs.map { VehicleZEVTariffModel(rate: $0.rate, time: $0.time) } case .weekend: return attribute.weekendTariffValue.tariffs.map { VehicleZEVTariffModel(rate: $0.rate, time: $0.time) } } }() return VehicleStatusAttributeModel<[VehicleZEVTariffModel], T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: nil, value: value) } private func vehicleStatusUpdate<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<[VehicleChargeProgramModel], T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let chargePrograms: [VehicleChargeProgramModel] = attribute.chargeProgramsValue.chargeProgramParameters.compactMap { guard let chargeProgram = ChargingProgram(rawValue: $0.chargeProgram.rawValue) else { return nil } return VehicleChargeProgramModel(autoUnlock: $0.autoUnlock, chargeProgram: chargeProgram, clockTimer: $0.clockTimer, ecoCharging: $0.ecoCharging, locationBasedCharging: $0.locationBasedCharging, maxChargingCurrent: Int($0.maxSoc), maxSoc: Int($0.maxSoc), weeklyProfile: $0.weeklyProfile) } return VehicleStatusAttributeModel<[VehicleChargeProgramModel], T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: nil, value: chargePrograms) } private func vehicleStatusUpdate<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<[VehicleSpeedAlertModel], T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } var value = [VehicleSpeedAlertModel]() let attributeUnit: VehicleAttributeUnitModel<T>? = self.attributeUnit(for: attribute) for element in attribute.speedAlertConfigurationValue.speedAlertConfigurations { value.append(VehicleSpeedAlertModel(endtime: Int(element.endTimestampInS), threshold: Int(element.thresholdInKph), thresholdDisplayValue: element.thresholdDisplayValue)) } return VehicleStatusAttributeModel<[VehicleSpeedAlertModel], T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: attributeUnit, value: value) } private func temperaturePoints<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?, zone: TemperatureZone) -> VehicleStatusAttributeModel<Double, T>? where T.RawValue == Int { guard let attribute = attributeStatus, let temperaturePoint = attribute.temperaturePointsValue.temperaturePoints.first(where: { $0.zone == zone.rawValue }) else { return nil } let attributeUnit: VehicleAttributeUnitModel<T>? = self.attributeUnit(for: attribute) return VehicleStatusAttributeModel<Double, T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: attributeUnit, value: temperaturePoint.temperature) } private func vehicleStatusUpdate<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<Bool, T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let attributeUnit: VehicleAttributeUnitModel<T>? = self.attributeUnit(for: attribute) return VehicleStatusAttributeModel<Bool, T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: attributeUnit, value: attribute.boolValue) } private func vehicleStatusUpdate<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<Double, T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let attributeUnit: VehicleAttributeUnitModel<T>? = self.attributeUnit(for: attribute) return VehicleStatusAttributeModel<Double, T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: attributeUnit, value: attribute.doubleValue) } private func vehicleStatusUpdate<T: RawRepresentable>(for attributeStatus: Proto_VehicleAttributeStatus?) -> VehicleStatusAttributeModel<Int, T>? where T.RawValue == Int { guard let attribute = attributeStatus else { return nil } let attributeUnit: VehicleAttributeUnitModel<T>? = self.attributeUnit(for: attribute) let value: Int = { guard attribute.intValue == 0 else { return Int(attribute.intValue) } return Int(attribute.doubleValue) }() return VehicleStatusAttributeModel<Int, T>(status: attribute.status, timestampInMs: attribute.timestampInMs, unit: attributeUnit, value: value) } } // swiftlint:enable function_body_length // swiftlint:enable type_body_length
52.590909
199
0.778244
281f955ef062cf13eedc5f29eba3134143ec3848
1,962
// // ContentView.swift // QRewards // // Created by Dustin Tran on 5/31/20. // Copyright © 2020 Q Rewards. All rights reserved. // import SwiftUI private let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .medium return dateFormatter }() struct ContentView: View { @State private var dates = [Date]() var body: some View { NavigationView { MasterView(dates: $dates) .navigationBarTitle(Text("Master")) .navigationBarItems( leading: EditButton(), trailing: Button( action: { withAnimation { self.dates.insert(Date(), at: 0) } } ) { Image(systemName: "plus") } ) DetailView() }.navigationViewStyle(DoubleColumnNavigationViewStyle()) } } struct MasterView: View { @Binding var dates: [Date] var body: some View { List { ForEach(dates, id: \.self) { date in NavigationLink( destination: DetailView(selectedDate: date) ) { Text("\(date, formatter: dateFormatter)") } }.onDelete { indices in indices.forEach { self.dates.remove(at: $0) } } } } } struct DetailView: View { var selectedDate: Date? var body: some View { Group { if selectedDate != nil { Text("\(selectedDate!, formatter: dateFormatter)") } else { Text("Detail view content goes here") } }.navigationBarTitle(Text("Detail")) } } struct ContentView_Previews: PreviewProvider { var previews: some View { ContentView("dustintran") } }
25.153846
78
0.509684
f9cab9616aa3ce53165a7fda37719d2518a041ae
5,042
// // TweetCell.swift // twitter_alamofire_demo // // Created by Charles Hieger on 6/18/17. // Copyright © 2017 Charles Hieger. All rights reserved. // import UIKit import AlamofireImage class TweetCell: UITableViewCell { @IBOutlet weak var favoriteImage: UIImageView! @IBOutlet weak var retweetImage: UIImageView! @IBOutlet weak var retweetCount: UILabel! @IBOutlet weak var favoriteCount: UILabel! @IBOutlet weak var created_at: UILabel! @IBOutlet weak var screenName: UILabel! @IBOutlet weak var userName: UILabel! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var tweetTextLabel: UILabel! var tweet: Tweet! { didSet { tweetTextLabel.text = tweet.text retweetCount.text = "\(tweet.retweetCount)" favoriteCount.text = "\(tweet.favoriteCount!)" created_at.text = "\(tweet.createdAtString)" screenName.text = "@\(tweet.screenName)" userName.text = "\(tweet.name)" profileImage.layer.cornerRadius = 8.0 profileImage.clipsToBounds = true profileImage.af_setImage(withURL: URL(string: tweet.imageUrl)!) if let favorited = tweet.favorited{ if favorited{ favoriteImage.image = UIImage(imageLiteralResourceName: "favor-icon-red") } else{ favoriteImage.image = UIImage(imageLiteralResourceName: "favor-icon") } } else{ favoriteImage.image = UIImage(imageLiteralResourceName: "favor-icon") } if tweet.retweeted { retweetImage.image = UIImage(imageLiteralResourceName: "retweet-icon-green") } else{ retweetImage.image = UIImage(imageLiteralResourceName: "retweet-icon") } let favoriteRecognizer = UITapGestureRecognizer(target: self, action: #selector(favoriteTapped(tapGestureRecognizer:))) let retweetTapped = UITapGestureRecognizer(target: self, action: #selector(retweetTapped(tapGestureRecognizer:))) retweetImage.addGestureRecognizer(retweetTapped) favoriteImage.addGestureRecognizer(favoriteRecognizer) } } @objc func favoriteTapped(tapGestureRecognizer: UITapGestureRecognizer) { favoriteImage.isUserInteractionEnabled = false if tweet.favorited! { APIManager.shared.favoriteTweet(self.tweet, completion: { (tweet, error) in if tweet != nil { self.favoriteImage.image = UIImage(imageLiteralResourceName: "favor-icon-red") self.favoriteCount.text = "\(self.tweet.favoriteCount! + 1)" } else if let error = error { print(error.localizedDescription) } self.favoriteImage.isUserInteractionEnabled = true }) } else{ APIManager.shared.unFavoriteTweet(self.tweet, completion: { (tweet, error) in if tweet != nil { self.favoriteImage.image = UIImage(imageLiteralResourceName: "favor-icon") self.favoriteCount.text = "\(self.tweet.favoriteCount! - 1)" } else if let error = error{ print(error.localizedDescription) } self.favoriteImage.isUserInteractionEnabled = true }) } } @objc func retweetTapped(tapGestureRecognizer: UITapGestureRecognizer) { retweetImage.isUserInteractionEnabled = false if !tweet.retweeted { APIManager.shared.retweet(self.tweet, completion: {(tweet, error) in if tweet != nil { self.retweetImage.image = UIImage(imageLiteralResourceName: "retweet-icon-green") self.retweetCount.text = "\(self.tweet.retweetCount + 1)" } else if let error = error{ print(error.localizedDescription) } self.retweetImage.isUserInteractionEnabled = true }) } else{ APIManager.shared.unRetweet(self.tweet, completion: {(tweet, error) in if tweet != nil { self.retweetImage.image = UIImage(imageLiteralResourceName: "retweet-icon") self.retweetCount.text = "\(self.tweet.retweetCount - 1)" } else if let error = error{ print(error.localizedDescription) } self.retweetImage.isUserInteractionEnabled = true }) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
41.327869
131
0.58687
1db03f5e74161d8ec1cea7814ab1e0260e4c1f77
6,778
// // ProcessIndicatorContainer.swift // Inchworm // // Created by Echo on 10/16/19. // Copyright © 2019 Echo. All rights reserved. // import UIKit class ProcessIndicatorContainer: UIView { var progressIndicatorViewList: [ProcessIndicatorView] = [] var backgroundSlideView = UIScrollView() var activeIndicatorIndex = 0 let span: CGFloat = 20 var pageWidth: CGFloat = 0 var iconLength: CGFloat = 0 var didActive: (Float) -> Void = { _ in } var didTempReset = {} var didRemoveTempReset: (Float) -> Void = { _ in } var orientation: SliderOrientation = .horizontal override var bounds: CGRect { didSet { handleBoundsChange() } } init(orientation: SliderOrientation = .horizontal, frame: CGRect) { super.init(frame: frame) self.orientation = orientation backgroundSlideView.showsVerticalScrollIndicator = false backgroundSlideView.showsHorizontalScrollIndicator = false backgroundSlideView.delegate = self addSubview(backgroundSlideView) // iF you want a customized page width, comment this one // backgroundSlideView.isPagingEnabled = true setupUIFrames() } required init?(coder: NSCoder) { super.init(coder: coder) } func handleBoundsChange() { setupUIFrames() progressIndicatorViewList.forEach { [weak self] in $0.frame = CGRect(x: 0, y: 0, width: iconLength, height: iconLength) self?.setOrientations(for: $0) } rerangeIndicators() setActiveIndicatorIndex(activeIndicatorIndex) } func setupUIFrames() { iconLength = min(frame.width, frame.height) pageWidth = iconLength + span backgroundSlideView.frame = bounds } func rerangeIndicators() { let slideContentSize = getSlideContentSize() backgroundSlideView.contentSize = CGSize(width: backgroundSlideView.frame.width + slideContentSize.width - iconLength, height: backgroundSlideView.frame.height) let startX = backgroundSlideView.contentSize.width / 2 - slideContentSize.width / 2 for i in 0..<progressIndicatorViewList.count { let progressView = progressIndicatorViewList[i] progressView.center = CGPoint(x: startX + CGFloat(i) * (progressView.frame.width + span) + progressView.frame.width / 2, y: backgroundSlideView.frame.height / 2) } } func addIndicatorWith(limitNumber: Int, normalIconImage: CGImage?, dimmedIconImage: CGImage?) { let indicatorView = ProcessIndicatorView(frame: CGRect(x: 0, y: 0, width: iconLength, height: iconLength), limitNumber: limitNumber, normalIconImage: normalIconImage, dimmedIconImage: dimmedIconImage) indicatorView.delegate = self indicatorView.index = progressIndicatorViewList.count progressIndicatorViewList.append(indicatorView) backgroundSlideView.addSubview(indicatorView) setOrientations(for: indicatorView) rerangeIndicators() } func setOrientations(for indicatorView: ProcessIndicatorView) { if orientation == .horizontal { indicatorView.transform = CGAffineTransform(rotationAngle: 0) } else { indicatorView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) } } func getSlideContentSize() -> CGSize { guard progressIndicatorViewList.count > 0 else { return backgroundSlideView.contentSize } let width = progressIndicatorViewList.map{ $0.frame.width }.reduce(0, +) + span * CGFloat(progressIndicatorViewList.count - 1) let height = backgroundSlideView.contentSize.height return CGSize(width: width, height: height) } func setActiveIndicatorIndex(_ index: Int = 0, animated: Bool = false) { if index < 0 { activeIndicatorIndex = 0 } else if index > progressIndicatorViewList.count - 1 { activeIndicatorIndex = progressIndicatorViewList.count - 1 } else { activeIndicatorIndex = index } guard let indicator = getActiveIndicator() else { return } indicator.active = true let slideContentSize = getSlideContentSize() let currentPositon = indicator.center let targetPosition = CGPoint(x: (backgroundSlideView.contentSize.width - slideContentSize.width) / 2 + iconLength / 2, y: 0) let offset = CGPoint(x: currentPositon.x - targetPosition.x, y: 0) backgroundSlideView.setContentOffset(offset, animated: animated) } func getActiveIndicator() -> ProcessIndicatorView? { guard 0..<progressIndicatorViewList.count ~= activeIndicatorIndex else { return nil } return progressIndicatorViewList[activeIndicatorIndex] } } extension ProcessIndicatorContainer: UIScrollViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let kMaxIndex = progressIndicatorViewList.count let targetX = scrollView.contentOffset.x + velocity.x * 60.0 var targetIndex = 0 if (velocity.x > 0) { targetIndex = Int(ceil(targetX / pageWidth)) } else if (velocity.x == 0) { targetIndex = Int(round(targetX / pageWidth)) } else if (velocity.x < 0) { targetIndex = Int(floor(targetX / pageWidth)) } if (targetIndex < 0) { targetIndex = 0 } if (targetIndex > kMaxIndex) { targetIndex = kMaxIndex } targetContentOffset.pointee.x = CGFloat(targetIndex) * pageWidth; setActiveIndicatorIndex(targetIndex) guard let processIndicatorView = getActiveIndicator() else { return } if processIndicatorView.status == .editing { self.didActive(processIndicatorView.progress) } } } extension ProcessIndicatorContainer: ProcessIndicatorViewDelegate { func didActive(_ processIndicatorView: ProcessIndicatorView) { setActiveIndicatorIndex(processIndicatorView.index, animated: true) self.didActive(processIndicatorView.progress) } func didTempReset(_ processIndicatorView: ProcessIndicatorView) { self.didTempReset() } func didRemoveTempReset(_ processIndicatorView: ProcessIndicatorView) { self.didRemoveTempReset(processIndicatorView.progress) } }
35.302083
208
0.647094
4b0612ec8cf5160d57bea43ee3fd97dfc9c73502
26,448
import Swift import Darwin import StdlibUnittest import Foundation func convertDictionaryToNSDictionary<Key, Value>( _ d: [Key : Value] ) -> NSDictionary { return d._bridgeToObjectiveC() } public func convertNSDictionaryToDictionary< Key : Hashable, Value >(_ d: NSDictionary?) -> [Key : Value] { if _slowPath(d == nil) { return [:] } var result: [Key : Value]? Dictionary._forceBridgeFromObjectiveC(d!, result: &result) return result! } func isNativeDictionary<KeyTy : Hashable, ValueTy>( _ d: Dictionary<KeyTy, ValueTy>) -> Bool { switch d._variantStorage { case .native: return true case .cocoa: return false } } func isCocoaDictionary<KeyTy : Hashable, ValueTy>( _ d: Dictionary<KeyTy, ValueTy>) -> Bool { return !isNativeDictionary(d) } func isNativeNSDictionary(_ d: NSDictionary) -> Bool { let className: NSString = NSStringFromClass(type(of: d)) as NSString return className.range(of: "_NativeDictionaryStorageOwner").length > 0 } func isCocoaNSDictionary(_ d: NSDictionary) -> Bool { let className: NSString = NSStringFromClass(type(of: d)) as NSString return className.range(of: "NSDictionary").length > 0 || className.range(of: "NSCFDictionary").length > 0 } func isNativeNSArray(_ d: NSArray) -> Bool { let className: NSString = NSStringFromClass(type(of: d)) as NSString return ["_SwiftDeferredNSArray", "_ContiguousArray", "_EmptyArray"].contains { className.range(of: $0).length > 0 } } var _objcKeyCount = _stdlib_AtomicInt(0) var _objcKeySerial = _stdlib_AtomicInt(0) class TestObjCKeyTy : NSObject, NSCopying { class var objectCount: Int { get { return _objcKeyCount.load() } set { _objcKeyCount.store(newValue) } } init(_ value: Int) { _objcKeyCount.fetchAndAdd(1) serial = _objcKeySerial.addAndFetch(1) self.value = value self._hashValue = value super.init() } convenience init(value: Int, hashValue: Int) { self.init(value) self._hashValue = hashValue } deinit { assert(serial > 0, "double destruction") _objcKeyCount.fetchAndAdd(-1) serial = -serial } @objc(copyWithZone:) func copy(with zone: NSZone?) -> Any { return TestObjCKeyTy(value) } override var description: String { assert(serial > 0, "dead TestObjCKeyTy") return value.description } override func isEqual(_ object: Any!) -> Bool { if let other = object { if let otherObjcKey = other as? TestObjCKeyTy { return self.value == otherObjcKey.value } } return false } override var hash : Int { return _hashValue } func _bridgeToObjectiveC() -> TestObjCKeyTy { return self } var value: Int var _hashValue: Int var serial: Int } // A type that satisfies the requirements of an NSDictionary key (or an NSSet // member), but traps when any of its methods are called. class TestObjCInvalidKeyTy { init() { _objcKeyCount.fetchAndAdd(1) serial = _objcKeySerial.addAndFetch(1) } deinit { assert(serial > 0, "double destruction") _objcKeyCount.fetchAndAdd(-1) serial = -serial } @objc var description: String { assert(serial > 0, "dead TestObjCInvalidKeyTy") fatalError() } @objc func isEqual(_ object: Any!) -> Bool { fatalError() } @objc var hash : Int { fatalError() } var serial: Int } var _objcValueCount = _stdlib_AtomicInt(0) var _objcValueSerial = _stdlib_AtomicInt(0) class TestObjCValueTy : NSObject { class var objectCount: Int { get { return _objcValueCount.load() } set { _objcValueCount.store(newValue) } } init(_ value: Int) { _objcValueCount.fetchAndAdd(1) serial = _objcValueSerial.addAndFetch(1) self.value = value } deinit { assert(serial > 0, "double destruction") _objcValueCount.fetchAndAdd(-1) serial = -serial } override var description: String { assert(serial > 0, "dead TestObjCValueTy") return value.description } var value: Int var serial: Int } var _objcEquatableValueCount = _stdlib_AtomicInt(0) var _objcEquatableValueSerial = _stdlib_AtomicInt(0) class TestObjCEquatableValueTy : NSObject { class var objectCount: Int { get { return _objcEquatableValueCount.load() } set { _objcEquatableValueCount.store(newValue) } } init(_ value: Int) { _objcEquatableValueCount.fetchAndAdd(1) serial = _objcEquatableValueSerial.addAndFetch(1) self.value = value } deinit { assert(serial > 0, "double destruction") _objcEquatableValueCount.fetchAndAdd(-1) serial = -serial } override func isEqual(_ object: Any!) -> Bool { if let other = object { if let otherObjcKey = other as? TestObjCEquatableValueTy { return self.value == otherObjcKey.value } } return false } override var description: String { assert(serial > 0, "dead TestObjCValueTy") return value.description } var value: Int var serial: Int } func == (lhs: TestObjCEquatableValueTy, rhs: TestObjCEquatableValueTy) -> Bool { return lhs.value == rhs.value } var _bridgedKeySerial = _stdlib_AtomicInt(0) var _bridgedKeyBridgeOperations = _stdlib_AtomicInt(0) struct TestBridgedKeyTy : Equatable, Hashable, CustomStringConvertible, _ObjectiveCBridgeable { static var bridgeOperations: Int { get { return _bridgedKeyBridgeOperations.load() } set { _bridgedKeyBridgeOperations.store(newValue) } } init(_ value: Int) { serial = _bridgedKeySerial.addAndFetch(1) self.value = value self._hashValue = value } var description: String { assert(serial > 0, "dead TestBridgedKeyTy") return value.description } var hashValue: Int { return _hashValue } func _bridgeToObjectiveC() -> TestObjCKeyTy { _bridgedKeyBridgeOperations.fetchAndAdd(1) return TestObjCKeyTy(value) } static func _forceBridgeFromObjectiveC( _ x: TestObjCKeyTy, result: inout TestBridgedKeyTy? ) { _bridgedKeyBridgeOperations.fetchAndAdd(1) result = TestBridgedKeyTy(x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: TestObjCKeyTy, result: inout TestBridgedKeyTy? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } static func _unconditionallyBridgeFromObjectiveC(_ source: TestObjCKeyTy?) -> TestBridgedKeyTy { var result: TestBridgedKeyTy? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var _hashValue: Int var serial: Int } func == (lhs: TestBridgedKeyTy, rhs: TestBridgedKeyTy) -> Bool { return lhs.value == rhs.value } func == (lhs: TestBridgedKeyTy, rhs: TestKeyTy) -> Bool { return lhs.value == rhs.value } var _bridgedValueSerial = _stdlib_AtomicInt(0) var _bridgedValueBridgeOperations = _stdlib_AtomicInt(0) struct TestBridgedValueTy : CustomStringConvertible, _ObjectiveCBridgeable { static var bridgeOperations: Int { get { return _bridgedValueBridgeOperations.load() } set { _bridgedValueBridgeOperations.store(newValue) } } init(_ value: Int) { serial = _bridgedValueSerial.fetchAndAdd(1) self.value = value } var description: String { assert(serial > 0, "dead TestBridgedValueTy") return value.description } func _bridgeToObjectiveC() -> TestObjCValueTy { TestBridgedValueTy.bridgeOperations += 1 return TestObjCValueTy(value) } static func _forceBridgeFromObjectiveC( _ x: TestObjCValueTy, result: inout TestBridgedValueTy? ) { TestBridgedValueTy.bridgeOperations += 1 result = TestBridgedValueTy(x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: TestObjCValueTy, result: inout TestBridgedValueTy? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } static func _unconditionallyBridgeFromObjectiveC(_ source: TestObjCValueTy?) -> TestBridgedValueTy { var result: TestBridgedValueTy? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var serial: Int } var _bridgedEquatableValueSerial = _stdlib_AtomicInt(0) var _bridgedEquatableValueBridgeOperations = _stdlib_AtomicInt(0) struct TestBridgedEquatableValueTy : Equatable, CustomStringConvertible, _ObjectiveCBridgeable { static var bridgeOperations: Int { get { return _bridgedEquatableValueBridgeOperations.load() } set { _bridgedEquatableValueBridgeOperations.store(newValue) } } init(_ value: Int) { serial = _bridgedEquatableValueSerial.addAndFetch(1) self.value = value } var description: String { assert(serial > 0, "dead TestBridgedValueTy") return value.description } func _bridgeToObjectiveC() -> TestObjCEquatableValueTy { _bridgedEquatableValueBridgeOperations.fetchAndAdd(1) return TestObjCEquatableValueTy(value) } static func _forceBridgeFromObjectiveC( _ x: TestObjCEquatableValueTy, result: inout TestBridgedEquatableValueTy? ) { _bridgedEquatableValueBridgeOperations.fetchAndAdd(1) result = TestBridgedEquatableValueTy(x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: TestObjCEquatableValueTy, result: inout TestBridgedEquatableValueTy? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } static func _unconditionallyBridgeFromObjectiveC( _ source: TestObjCEquatableValueTy? ) -> TestBridgedEquatableValueTy { var result: TestBridgedEquatableValueTy? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var serial: Int } func == (lhs: TestBridgedEquatableValueTy, rhs: TestBridgedEquatableValueTy) -> Bool { return lhs.value == rhs.value } /// Expect some number of autoreleased key and value objects. /// /// - parameter opt: applies to platforms that have the return-autoreleased /// optimization. /// /// - parameter unopt: applies to platforms that don't. /// /// FIXME: Some non-zero `opt` might be cases of missed return-autorelease. func expectAutoreleasedKeysAndValues( opt: (Int, Int) = (0, 0), unopt: (Int, Int) = (0, 0)) { var expectedKeys = 0 var expectedValues = 0 #if arch(i386) (expectedKeys, expectedValues) = unopt #else (expectedKeys, expectedValues) = opt #endif TestObjCKeyTy.objectCount -= expectedKeys TestObjCValueTy.objectCount -= expectedValues } /// Expect some number of autoreleased value objects. /// /// - parameter opt: applies to platforms that have the return-autoreleased /// optimization. /// /// - parameter unopt: applies to platforms that don't. /// /// FIXME: Some non-zero `opt` might be cases of missed return-autorelease. func expectAutoreleasedValues( opt: Int = 0, unopt: Int = 0) { expectAutoreleasedKeysAndValues(opt: (0, opt), unopt: (0, unopt)) } func resetLeaksOfObjCDictionaryKeysValues() { TestObjCKeyTy.objectCount = 0 TestObjCValueTy.objectCount = 0 TestObjCEquatableValueTy.objectCount = 0 } func expectNoLeaksOfObjCDictionaryKeysValues() { expectEqual(0, TestObjCKeyTy.objectCount, "TestObjCKeyTy leak") expectEqual(0, TestObjCValueTy.objectCount, "TestObjCValueTy leak") expectEqual( 0, TestObjCEquatableValueTy.objectCount, "TestObjCEquatableValueTy leak") } func getBridgedNSDictionaryOfRefTypesBridgedVerbatim() -> NSDictionary { assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self)) assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self)) var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) let bridged = unsafeBitCast(convertDictionaryToNSDictionary(d), to: NSDictionary.self) assert(isNativeNSDictionary(bridged)) return bridged } func getBridgedEmptyNSDictionary() -> NSDictionary { let d = Dictionary<TestObjCKeyTy, TestObjCValueTy>() let bridged = unsafeBitCast(convertDictionaryToNSDictionary(d), to: NSDictionary.self) assert(isNativeNSDictionary(bridged)) return bridged } func getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: Int = 3 ) -> NSDictionary { assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self)) var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>() for i in 1..<(numElements + 1) { d[TestBridgedKeyTy(i * 10)] = TestBridgedValueTy(i * 10 + 1000) } let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } import SlurpFastEnumeration func slurpFastEnumerationFromSwift( _ a: NSArray, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void, maxItems: Int? = nil ) { var state = NSFastEnumerationState() let stackBufLength = 3 let stackBuf = _HeapBuffer<(), AnyObject?>( _HeapBufferStorage<(), AnyObject?>.self, (), stackBufLength) var itemsReturned = 0 while true { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectNotEqual(0, state.state) expectNotEmpty(state.mutationsPtr) if returnedCount == 0 { break } for i in 0..<returnedCount { let value: AnyObject = state.itemsPtr![i]! sink(value) itemsReturned += 1 } if maxItems != nil && itemsReturned >= maxItems! { return } } for _ in 0..<3 { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectNotEqual(0, state.state) expectNotEmpty(state.mutationsPtr) expectEqual(0, returnedCount) } } typealias AnyObjectTuple2 = (AnyObject, AnyObject) func slurpFastEnumerationFromSwift( _ d: NSDictionary, _ fe: NSFastEnumeration, _ sink: (AnyObjectTuple2) -> Void, maxItems: Int? = nil ) { var state = NSFastEnumerationState() let stackBufLength = 3 let stackBuf = _HeapBuffer<(), AnyObject?>( _HeapBufferStorage<(), AnyObject?>.self, (), stackBufLength) var itemsReturned = 0 while true { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectNotEqual(0, state.state) expectNotEmpty(state.mutationsPtr) if returnedCount == 0 { break } for i in 0..<returnedCount { let key: AnyObject = state.itemsPtr![i]! let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = (key, value) sink(kv) itemsReturned += 1 } if maxItems != nil && itemsReturned >= maxItems! { return } } for _ in 0..<3 { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectEqual(0, returnedCount) } } func slurpFastEnumerationOfNSEnumeratorFromSwift( _ a: NSArray, _ enumerator: NSEnumerator, _ sink: (AnyObject) -> Void, maxFastEnumerationItems: Int ) { slurpFastEnumerationFromSwift( a, enumerator, sink, maxItems: maxFastEnumerationItems) while let value = enumerator.nextObject() { sink(value as AnyObject) } } func slurpFastEnumerationOfNSEnumeratorFromSwift( _ d: NSDictionary, _ enumerator: NSEnumerator, _ sink: (AnyObjectTuple2) -> Void, maxFastEnumerationItems: Int ) { slurpFastEnumerationFromSwift( d, enumerator, sink, maxItems: maxFastEnumerationItems) while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = (key as AnyObject, value) sink(kv) } } func slurpFastEnumerationFromObjC( _ a: NSArray, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void ) { let objcValues = NSMutableArray() slurpFastEnumerationOfArrayFromObjCImpl(a, fe, objcValues) for value in objcValues { sink(value as AnyObject) } } func _checkArrayFastEnumerationImpl( _ expected: [Int], _ a: NSArray, _ makeEnumerator: () -> NSFastEnumeration, _ useEnumerator: (NSArray, NSFastEnumeration, (AnyObject) -> ()) -> Void, _ convertValue: @escaping (AnyObject) -> Int ) { let expectedContentsWithoutIdentity = _makeExpectedArrayContents(expected) var expectedContents = [ExpectedArrayElement]() for i in 0..<3 { var actualContents = [ExpectedArrayElement]() let sink = { (value: AnyObject) in actualContents.append(ExpectedArrayElement( value: convertValue(value), valueIdentity: unsafeBitCast(value, to: UInt.self))) } useEnumerator(a, makeEnumerator(), sink) expectTrue( _equalsWithoutElementIdentity( expectedContentsWithoutIdentity, actualContents), "expected: \(expectedContentsWithoutIdentity)\n" + "actual: \(actualContents)\n") if i == 0 { expectedContents = actualContents } expectEqualSequence(expectedContents, actualContents) } } func checkArrayFastEnumerationFromSwift( _ expected: [Int], _ a: NSArray, _ makeEnumerator: () -> NSFastEnumeration, _ convertValue: @escaping (AnyObject) -> Int ) { _checkArrayFastEnumerationImpl( expected, a, makeEnumerator, { (a, fe, sink) in slurpFastEnumerationFromSwift(a, fe, sink) }, convertValue) } func checkArrayFastEnumerationFromObjC( _ expected: [Int], _ a: NSArray, _ makeEnumerator: () -> NSFastEnumeration, _ convertValue: @escaping (AnyObject) -> Int ) { _checkArrayFastEnumerationImpl( expected, a, makeEnumerator, { (a, fe, sink) in slurpFastEnumerationFromObjC(a, fe, sink) }, convertValue) } func checkArrayEnumeratorPartialFastEnumerationFromSwift( _ expected: [Int], _ a: NSArray, maxFastEnumerationItems: Int, _ convertValue: @escaping (AnyObject) -> Int ) { _checkArrayFastEnumerationImpl( expected, a, { a.objectEnumerator() }, { (a, fe, sink) in slurpFastEnumerationOfNSEnumeratorFromSwift( a, fe as! NSEnumerator, sink, maxFastEnumerationItems: maxFastEnumerationItems) }, convertValue) } func _checkSetFastEnumerationImpl( _ expected: [Int], _ s: NSSet, _ makeEnumerator: () -> NSFastEnumeration, _ useEnumerator: (NSSet, NSFastEnumeration, (AnyObject) -> ()) -> Void, _ convertMember: @escaping (AnyObject) -> Int ) { let expectedContentsWithoutIdentity = _makeExpectedSetContents(expected) var expectedContents = [ExpectedSetElement]() for i in 0..<3 { var actualContents = [ExpectedSetElement]() let sink = { (value: AnyObject) in actualContents.append(ExpectedSetElement( value: convertMember(value), valueIdentity: unsafeBitCast(value, to: UInt.self))) } useEnumerator(s, makeEnumerator(), sink) expectTrue( _equalsUnorderedWithoutElementIdentity( expectedContentsWithoutIdentity, actualContents), "expected: \(expectedContentsWithoutIdentity)\n" + "actual: \(actualContents)\n") if i == 0 { expectedContents = actualContents } expectTrue(equalsUnordered(expectedContents, actualContents)) } } func slurpFastEnumerationFromObjC( _ s: NSSet, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void ) { let objcValues = NSMutableArray() slurpFastEnumerationOfArrayFromObjCImpl(s, fe, objcValues) for value in objcValues { sink(value as AnyObject) } } func slurpFastEnumerationOfNSEnumeratorFromSwift( _ s: NSSet, _ enumerator: NSEnumerator, _ sink: (AnyObject) -> Void, maxFastEnumerationItems: Int ) { slurpFastEnumerationFromSwift( s, enumerator, sink, maxItems: maxFastEnumerationItems) while let value = enumerator.nextObject() { sink(value as AnyObject) } } func slurpFastEnumerationFromSwift( _ s: NSSet, _ fe: NSFastEnumeration, _ sink: (AnyObject) -> Void, maxItems: Int? = nil ) { var state = NSFastEnumerationState() let stackBufLength = 3 let stackBuf = _HeapBuffer<(), AnyObject?>( _HeapBufferStorage<(), AnyObject?>.self, (), stackBufLength) var itemsReturned = 0 while true { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectNotEqual(0, state.state) expectNotEmpty(state.mutationsPtr) if returnedCount == 0 { break } for i in 0..<returnedCount { let value: AnyObject = state.itemsPtr![i]! sink(value) itemsReturned += 1 } if maxItems != nil && itemsReturned >= maxItems! { return } } for _ in 0..<3 { let returnedCount = fe.countByEnumerating( with: &state, objects: AutoreleasingUnsafeMutablePointer(stackBuf.baseAddress), count: stackBufLength) expectNotEqual(0, state.state) expectNotEmpty(state.mutationsPtr) expectEqual(0, returnedCount) } } func checkSetFastEnumerationFromSwift( _ expected: [Int], _ s: NSSet, _ makeEnumerator: () -> NSFastEnumeration, _ convertMember: @escaping (AnyObject) -> Int ) { _checkSetFastEnumerationImpl( expected, s, makeEnumerator, { (s, fe, sink) in slurpFastEnumerationFromSwift(s, fe, sink) }, convertMember) } func checkSetFastEnumerationFromObjC( _ expected: [Int], _ s: NSSet, _ makeEnumerator: () -> NSFastEnumeration, _ convertMember: @escaping (AnyObject) -> Int ) { _checkSetFastEnumerationImpl( expected, s, makeEnumerator, { (s, fe, sink) in slurpFastEnumerationFromObjC(s, fe, sink) }, convertMember) } func checkSetEnumeratorPartialFastEnumerationFromSwift( _ expected: [Int], _ s: NSSet, maxFastEnumerationItems: Int, _ convertMember: @escaping (AnyObject) -> Int ) { _checkSetFastEnumerationImpl( expected, s, { s.objectEnumerator() }, { (s, fe, sink) in slurpFastEnumerationOfNSEnumeratorFromSwift( s, fe as! NSEnumerator, sink, maxFastEnumerationItems: maxFastEnumerationItems) }, convertMember) } func slurpFastEnumerationFromObjC( _ d: NSDictionary, _ fe: NSFastEnumeration, _ sink: (AnyObjectTuple2) -> Void ) { let objcPairs = NSMutableArray() slurpFastEnumerationOfDictionaryFromObjCImpl(d, fe, objcPairs) for i in 0..<objcPairs.count/2 { let key = objcPairs[i * 2] as AnyObject let value = objcPairs[i * 2 + 1] as AnyObject let kv = (key, value) sink(kv) } } func _checkDictionaryFastEnumerationImpl( _ expected: [(Int, Int)], _ d: NSDictionary, _ makeEnumerator: () -> NSFastEnumeration, _ useEnumerator: (NSDictionary, NSFastEnumeration, (AnyObjectTuple2) -> ()) -> Void, _ convertKey: @escaping (AnyObject) -> Int, _ convertValue: @escaping (AnyObject) -> Int ) { let expectedContentsWithoutIdentity = _makeExpectedDictionaryContents(expected) var expectedContents = [ExpectedDictionaryElement]() for i in 0..<3 { var actualContents = [ExpectedDictionaryElement]() let sink: (AnyObjectTuple2) -> Void = { (key, value) in actualContents.append(ExpectedDictionaryElement( key: convertKey(key), value: convertValue(value), keyIdentity: unsafeBitCast(key, to: UInt.self), valueIdentity: unsafeBitCast(value, to: UInt.self))) } useEnumerator(d, makeEnumerator(), sink) expectTrue( _equalsUnorderedWithoutElementIdentity( expectedContentsWithoutIdentity, actualContents), "expected: \(expectedContentsWithoutIdentity)\n" + "actual: \(actualContents)\n") if i == 0 { expectedContents = actualContents } expectTrue(equalsUnordered(expectedContents, actualContents)) } } func checkDictionaryFastEnumerationFromSwift( _ expected: [(Int, Int)], _ d: NSDictionary, _ makeEnumerator: () -> NSFastEnumeration, _ convertKey: @escaping (AnyObject) -> Int, _ convertValue: @escaping (AnyObject) -> Int ) { _checkDictionaryFastEnumerationImpl( expected, d, makeEnumerator, { (d, fe, sink) in slurpFastEnumerationFromSwift(d, fe, sink) }, convertKey, convertValue) } func checkDictionaryFastEnumerationFromObjC( _ expected: [(Int, Int)], _ d: NSDictionary, _ makeEnumerator: () -> NSFastEnumeration, _ convertKey: @escaping (AnyObject) -> Int, _ convertValue: @escaping (AnyObject) -> Int ) { _checkDictionaryFastEnumerationImpl( expected, d, makeEnumerator, { (d, fe, sink) in slurpFastEnumerationFromObjC(d, fe, sink) }, convertKey, convertValue) } func checkDictionaryEnumeratorPartialFastEnumerationFromSwift( _ expected: [(Int, Int)], _ d: NSDictionary, maxFastEnumerationItems: Int, _ convertKey: @escaping (AnyObject) -> Int, _ convertValue: @escaping (AnyObject) -> Int ) { _checkDictionaryFastEnumerationImpl( expected, d, { d.keyEnumerator() }, { (d, fe, sink) in slurpFastEnumerationOfNSEnumeratorFromSwift( d, fe as! NSEnumerator, sink, maxFastEnumerationItems: maxFastEnumerationItems) }, convertKey, convertValue) } func getBridgedNSArrayOfRefTypeVerbatimBridged( numElements: Int = 3, capacity: Int? = nil ) -> NSArray { assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self)) var a = [TestObjCValueTy]() if let requestedCapacity = capacity { a.reserveCapacity(requestedCapacity) } for i in 1..<(numElements + 1) { a.append(TestObjCValueTy(i * 10)) } let bridged = convertArrayToNSArray(a) assert(isNativeNSArray(bridged)) return bridged } func convertNSArrayToArray<T>(_ source: NSArray?) -> [T] { if _slowPath(source == nil) { return [] } var result: [T]? Array._forceBridgeFromObjectiveC(source!, result: &result) return result! } func convertArrayToNSArray<T>(_ array: [T]) -> NSArray { return array._bridgeToObjectiveC() } func getBridgedNSArrayOfValueTypeCustomBridged( numElements: Int = 3, capacity: Int? = nil ) -> NSArray { assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self)) var a = [TestBridgedValueTy]() if let requestedCapacity = capacity { a.reserveCapacity(requestedCapacity) } for i in 1..<(numElements + 1) { a.append(TestBridgedValueTy(i * 10)) } let bridged = convertArrayToNSArray(a) assert(isNativeNSArray(bridged)) return bridged }
26.634441
86
0.706821
896b482d2ba4adf8f9abaeb311ef5297e4bf2213
5,845
import Html import SnapshotTesting import XCTest final class EventsTests: XCTestCase { func testElementsSnapshot() { let doc = [ audio( [ onabort("alert('Abort');"), onabort(unsafe: "alert('Abort');"), oncanplay("alert();"), oncanplay(unsafe: "alert();"), oncanplaythrough("alert();"), oncanplaythrough(unsafe: "alert();"), ondurationchange("alert();"), ondurationchange(unsafe: "alert();"), onemptied("alert();"), onemptied(unsafe: "alert();"), onended("alert();"), onended(unsafe: "alert();"), onerror("alert();"), onerror(unsafe: "alert();"), onloadeddata("alert();"), onloadeddata(unsafe: "alert();"), onloadedmetadata("alert();"), onloadedmetadata(unsafe: "alert();"), onloadstart("alert();"), onloadstart(unsafe: "alert();"), onpause("alert();"), onpause(unsafe: "alert();"), onplay("alert();"), onplay(unsafe: "alert();"), onplaying("alert();"), onplaying(unsafe: "alert();"), onseeked("alert();"), onseeked(unsafe: "alert();"), onseeking("alert();"), onseeking(unsafe: "alert();"), onstalled("alert();"), onstalled(unsafe: "alert();"), onprogress("alert();"), onprogress(unsafe: "alert();"), onratechange("alert();"), onratechange(unsafe: "alert();"), onsuspend("alert();"), onsuspend(unsafe: "alert();"), ontimeupdate("alert();"), ontimeupdate(unsafe: "alert();"), onvolumechange("alert();"), onvolumechange(unsafe: "alert();"), onwaiting("alert();"), onwaiting(unsafe: "alert();"), ], [ track(src: "track", [ oncuechange("alert();"), oncuechange(unsafe: "alert();"), ]) ] ), details( [ ontoggle("alert();"), ontoggle(unsafe: "alert();"), ], [] ), div( [ onblur("alert();"), onblur(unsafe: "alert();"), onclick("alert();"), onclick(unsafe: "alert();"), oncontextmenu("alert();"), oncontextmenu(unsafe: "alert();"), oncopy("alert();"), oncopy(unsafe: "alert();"), oncut("alert();"), oncut(unsafe: "alert();"), ondblclick("alert();"), ondblclick(unsafe: "alert();"), ondrag("alert();"), ondrag(unsafe: "alert();"), ondragend("alert();"), ondragend(unsafe: "alert();"), ondragenter("alert();"), ondragenter(unsafe: "alert();"), ondragover("alert();"), ondragover(unsafe: "alert();"), ondragstart("alert();"), ondragstart(unsafe: "alert();"), ondrop("alert();"), ondrop(unsafe: "alert();"), onfocus("alert();"), onfocus(unsafe: "alert();"), onkeydown("alert();"), onkeydown(unsafe: "alert();"), onkeypress("alert();"), onkeypress(unsafe: "alert();"), onkeyup("alert();"), onkeyup(unsafe: "alert();"), onmousedown("alert();"), onmousedown(unsafe: "alert();"), onmousemove("alert();"), onmousemove(unsafe: "alert();"), onmouseout("alert();"), onmouseout(unsafe: "alert();"), onmouseover("alert();"), onmouseover(unsafe: "alert();"), onmouseup("alert();"), onmouseup(unsafe: "alert();"), onpaste("alert();"), onpaste(unsafe: "alert();"), onscroll("alert();"), onscroll(unsafe: "alert();"), onwheel("alert();"), onwheel(unsafe: "alert();"), ], [] ), form( [ onreset("alert();"), onreset(unsafe: "alert();"), onsubmit("alert();"), onsubmit(unsafe: "alert();"), ], [] ), html([ body( [ onafterprint("alert();"), onafterprint(unsafe: "alert();"), onbeforeprint("alert();"), onbeforeprint(unsafe: "alert();"), onbeforeunload("alert();"), onbeforeunload(unsafe: "alert();"), onhashchange("alert();"), onhashchange(unsafe: "alert();"), onload("alert();"), onload(unsafe: "alert();"), onmessage("alert();"), onmessage(unsafe: "alert();"), onoffline("alert();"), onoffline(unsafe: "alert();"), ononline("alert();"), ononline(unsafe: "alert();"), onpagehide("alert();"), onpagehide(unsafe: "alert();"), onpageshow("alert();"), onpageshow(unsafe: "alert();"), onpopstate("alert();"), onpopstate(unsafe: "alert();"), onresize("alert();"), onresize(unsafe: "alert();"), onstorage("alert();"), onstorage(unsafe: "alert();"), onunload("alert();"), onunload(unsafe: "alert();"), ], [] ) ]), input( [ onchange("alert();"), onchange(unsafe: "alert();"), oninput("alert();"), oninput(unsafe: "alert();"), oninvalid("alert();"), oninvalid(unsafe: "alert();"), onsearch("alert();"), onsearch(unsafe: "alert();"), onselect("alert();"), onselect(unsafe: "alert();"), ] ), ] assertSnapshot(matching: render(doc), pathExtension: "html") } }
31.424731
64
0.444311
5007da77f87bdbfa20ac9991e1f9905ffec39acb
5,763
// // CameraPhotoFilterVC.swift // BBMetalImageDemo // // Created by Kaibo Lu on 5/13/19. // Copyright © 2019 Kaibo Lu. All rights reserved. // import UIKit import AVFoundation import BBMetalImage class CameraPhotoFilterVC: UIViewController { private var camera: BBMetalCamera! private var metalView: BBMetalView! private var faceView: UIView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .gray let x: CGFloat = 10 let width: CGFloat = view.bounds.width - 20 metalView = BBMetalView(frame: CGRect(x: x, y: 100, width: width, height: view.bounds.height - 200)) view.addSubview(metalView) let tapMetalView = UITapGestureRecognizer(target: self, action: #selector(tapMetalView(_:))) metalView.addGestureRecognizer(tapMetalView) faceView = UIView(frame: .zero) faceView.backgroundColor = UIColor.red.withAlphaComponent(0.2) metalView.addSubview(faceView) let photoButton = UIButton(frame: CGRect(x: x, y: metalView.frame.maxY + 10, width: width, height: 30)) photoButton.backgroundColor = .blue photoButton.setTitle("Take photo", for: .normal) photoButton.addTarget(self, action: #selector(clickPhotoButton(_:)), for: .touchUpInside) view.addSubview(photoButton) camera = BBMetalCamera(sessionPreset: .hd1920x1080) camera.addMetadataOutput(with: [.face]) camera.metadataObjectDelegate = self camera.canTakePhoto = true camera.photoDelegate = self camera.add(consumer: BBMetalLookupFilter(lookupTable: UIImage(named: "test_lookup")!.bb_metalTexture!)) .add(consumer: metalView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) camera.start() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) camera.stop() } @objc private func tapMetalView(_ tap: UITapGestureRecognizer) { camera.switchCameraPosition() } @objc private func clickPhotoButton(_ button: UIButton) { camera.takePhoto() } } extension CameraPhotoFilterVC: BBMetalCameraPhotoDelegate { func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture) { // In main thread let filter = BBMetalLookupFilter(lookupTable: UIImage(named: "test_lookup")!.bb_metalTexture!) let imageView = UIImageView(frame: metalView.frame) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = filter.filteredImage(with: texture.bb_image!) view.addSubview(imageView) DispatchQueue.main.asyncAfter(deadline: .now() + 3) { imageView.removeFromSuperview() } } func camera(_ camera: BBMetalCamera, didFail error: Error) { // In main thread print("Fail taking photo. Error: \(error)") } } extension CameraPhotoFilterVC: BBMetalCameraMetadataObjectDelegate { func camera(_ camera: BBMetalCamera, didOutput metadataObjects: [AVMetadataObject]) { guard let first = metadataObjects.first else { DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.faceView.isHidden = true } return } DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.handleMetadataBounds(first.bounds) } } private func handleMetadataBounds(_ bounds: CGRect) { let imageWidth: CGFloat = 1080 let imageHeight: CGFloat = 1920 let aa: CGFloat = imageWidth / imageHeight let bb: CGFloat = metalView.bounds.width / metalView.bounds.height // top x, right y let x = camera.position == .front ? bounds.minY : 1 - bounds.maxY let y = bounds.origin.x // x' = sx * x + tx // y' = sy * y + ty var sx: CGFloat = metalView.bounds.width var tx: CGFloat = 0 var sy: CGFloat = metalView.bounds.height var ty: CGFloat = 0 var displayImageWidth = imageWidth var displayImageHeight = imageHeight if aa > bb { // Mask left and right displayImageWidth = imageHeight * bb let maskImageMarginLeft = abs(imageWidth - displayImageWidth) * 0.5 tx = -maskImageMarginLeft / displayImageWidth * metalView.bounds.width sx = (1 + maskImageMarginLeft / displayImageWidth) * metalView.bounds.width - tx } else { // Mask top and bottom displayImageHeight = imageWidth / bb let maskImageMarginTop = abs(imageHeight - displayImageHeight) * 0.5 ty = -maskImageMarginTop / displayImageHeight * metalView.bounds.height sy = (1 + maskImageMarginTop / displayImageHeight) * metalView.bounds.height - ty } var frame: CGRect = .zero frame.origin.x = sx * x + tx frame.size.width = bounds.height * imageWidth / displayImageWidth * metalView.bounds.width frame.origin.y = sy * y + ty frame.size.height = bounds.width * imageHeight / displayImageHeight * metalView.bounds.height if frame.minX >= 0, frame.maxX <= metalView.bounds.width, frame.minY >= 0, frame.maxY <= metalView.bounds.height { faceView.frame = frame faceView.isHidden = false } else { faceView.isHidden = true } } }
36.245283
111
0.61999
182bf0240c0ff4bd294b1e4bbef6a37807e49965
731
// // PanelView.swift // VergeiOS // // Created by Swen van Zanten on 24-07-18. // Copyright © 2018 Verge Currency. All rights reserved. // import UIKit class PanelView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.createView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.createView() } func createView() { self.backgroundColor = .white self.layer.cornerRadius = 5 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.15 self.layer.shadowOffset = CGSize.zero self.layer.shadowRadius = 15 } }
19.756757
57
0.585499
61585417814eeec6c454586d25da68cb6e12db00
266
// // Ingredients.swift // PankApp // // Created by Motonari Nakashima on 2020/04/15. // Copyright © 2020 motoshima1150. All rights reserved. // import Foundation struct Ingredients: Decodable { let malt: [Malt] let hops: [Hop] let yeast: String }
16.625
56
0.672932
1d841f0e36715e41293e8dc253bf6dcfcbc4da99
6,820
// // BuildingDoor.swift // // Created by Zack Brown on 05/08/2021. // import Euclid import Foundation import Meadow struct BuildingDoor: Prop { enum Constants { static let width = 0.75 static let depth = 0.05 static let height = World.Constants.slope * 3 } let architecture: Building.Architecture let c0: Vector let c1: Vector let cardinal: Cardinal func build(position: Vector) -> [Euclid.Polygon] { let borderTextureCoordinates = UVs(start: Vector(0.5, 0.375), end: Vector(1.0, 0.5)) let doorTextureCoordinates = UVs(start: Vector(0.5, 0.125), end: Vector(1.0, 0.25)) let outer = Mesh(shape(position: position, uvs: borderTextureCoordinates, width: Constants.width, depth: Constants.depth, height: Constants.height)) let inner = Mesh(shape(position: position, uvs: borderTextureCoordinates, width: Constants.width - 0.1, depth: 0.07, height: Constants.height - 0.05)) let door = Mesh(shape(position: position, uvs: doorTextureCoordinates, width: Constants.width - 0.1, depth: 0.06, height: Constants.height - 0.05)) return outer.subtract(inner).union(door).polygons } func shape(position: Vector, uvs: UVs, width: Double, depth: Double, height: Double) -> [Euclid.Polygon] { let radius = width / 2.0 let offset = (-cardinal.normal * depth) let v0 = position + (-offset / 2.0) + c0.lerp(c1, (1.0 - width) / 2.0) let v1 = position + (-offset / 2.0) + c1.lerp(c0, (1.0 - width) / 2.0) let v2 = v1 + Vector(0, height, 0) let v3 = v0 + Vector(0, height, 0) switch architecture.borderStyle { case .pointy: let v4 = v1 + Vector(0, height - ((v0 - v1).length / 4.0), 0) let v5 = v0 + Vector(0, height - ((v0 - v1).length / 4.0), 0) let p0 = v2.lerp(v3, 0.5) let puv = uvs.corners[0].lerp(uvs.corners[1], 0.5) let faceUVs = [uvs.corners[0], puv, uvs.corners[1], uvs.corners[2], uvs.corners[3]] let (v6, v7, v8, v9, p1) = (v0 + offset, v1 + offset, v4 + offset, v5 + offset, p0 + offset) guard let front = polygon(vectors: [v5, p0, v4, v1, v0], uvs: faceUVs), let back = polygon(vectors: [v6, v7, v8, p1, v9], uvs: faceUVs), let lhs = polygon(vectors: [v4, v8, v7, v1], uvs: uvs.corners), let rhs = polygon(vectors: [v0, v6, v9, v5], uvs: uvs.corners), let tlhs = polygon(vectors: [p0, p1, v8, v4], uvs: uvs.corners), let trhs = polygon(vectors: [v9, p1, p0, v5], uvs: uvs.corners), let bottom = polygon(vectors: [v0, v1, v7, v6], uvs: uvs.corners) else { return [] } return [front, back, lhs, rhs, tlhs, trhs, bottom] case .rounded: let segments = 10 let rotation = Angle(radians: Double.pi / Double(segments)) let needsFlipping = cardinal == .north || cardinal == .east let v4 = v1 + Vector(0, height - (radius / 2.0), 0) let v5 = v0 + Vector(0, height - (radius / 2.0), 0) let p1 = v4.lerp(v5, 0.5) let (v6, v7, v8, v9) = (v0 + offset, v1 + offset, v4 + offset, v5 + offset) var frontFace = needsFlipping ? [v4, v1, v0] : [v5, v0, v1] var backFace = needsFlipping ? [v8, v7, v6] : [v9, v6, v7] var topFaces: [Euclid.Polygon] = [] let uvRadius = (uvs.end.x - uvs.start.x) / 2.0 let uv0 = uvs.corners[0].lerp(uvs.corners[3], 0.5) let uv1 = uvs.corners[1].lerp(uvs.corners[2], 0.5) let puv = uv0.lerp(uv1, 0.5) var faceUVs = [uv1, uvs.corners[2], uvs.corners[3]] var sweep: Vector? = nil for segment in 0..<segments { let angle = rotation * Double(segment) let p2 = plot(radians: angle.radians - (Double.pi / 2.0), radius: (v4 - v5).length / 2.0) let p3 = cardinal == .north || cardinal == .south ? Vector(p2.x, p2.z, 0) : Vector(0, p2.z, p2.x) let uvp = plot(radians: angle.radians - (Double.pi / 2.0), radius: uvRadius) frontFace.append(p1 + p3) backFace.append(p1 + offset + p3) faceUVs.append(puv + uvp) if let sweep = sweep { let face = needsFlipping ? [sweep + offset, p1 + offset + p3, p1 + p3, sweep] : [sweep, p1 + p3, p1 + offset + p3, sweep + offset] guard let polygon = polygon(vectors: face, uvs: uvs.corners) else { break } topFaces.append(polygon) } sweep = p1 + p3 } if let sweep = sweep { let face = needsFlipping ? [sweep + offset, v8, v4, sweep] : [sweep, v5, v9, sweep + offset] if let polygon = polygon(vectors: face, uvs: uvs.corners) { topFaces.append(polygon) } } guard let front = polygon(vectors: needsFlipping ? frontFace : frontFace.reversed(), uvs: faceUVs), let back = polygon(vectors: needsFlipping ? backFace.reversed() : backFace, uvs: faceUVs), let lhs = polygon(vectors: [v4, v8, v7, v1], uvs: uvs.corners), let rhs = polygon(vectors: [v0, v6, v9, v5], uvs: uvs.corners), let bottom = polygon(vectors: [v0, v1, v7, v6], uvs: uvs.corners) else { return [] } return [front, back, lhs, rhs, bottom] + topFaces case .square: let (v4, v5, v6, v7) = (v0 + offset, v1 + offset, v2 + offset, v3 + offset) guard let front = polygon(vectors: [v3, v2, v1, v0], uvs: uvs.corners), let back = polygon(vectors: [v4, v5, v6, v7], uvs: uvs.corners), let lhs = polygon(vectors: [v2, v6, v5, v1], uvs: uvs.corners), let rhs = polygon(vectors: [v0, v4, v7, v3], uvs: uvs.corners), let top = polygon(vectors: [v3, v7, v6, v2], uvs: uvs.corners), let bottom = polygon(vectors: [v0, v1, v5, v4], uvs: uvs.corners) else { return [] } return [front, back, lhs, rhs, top, bottom] } } }
44.575163
158
0.498534
18141de8b7f0174f4c8ae23d12e953a7273865d2
4,157
// // ZLibTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class ZLibTest: XCTestCase { // MARK: Instance Methods func testCaseA() { for level in 1..<10 { do { guard let compressed = ZLib.deflate([], level: level) else { return XCTFail() } XCTAssert(compressed == []) XCTAssert(ZLib.inflate(compressed) == nil) } do { var data: [UInt8] = [] for _ in 0..<1234 { if arc4random_uniform(2) > 0 { data.append(UInt8(arc4random_uniform(256))) } else { data.append(0) } } guard let compressed = ZLib.deflate(data, level: level) else { return XCTFail() } XCTAssert((!compressed.isEmpty) && (compressed.count < data.count)) guard let decompressed = ZLib.inflate(compressed) else { return XCTFail() } XCTAssert(decompressed == data) } } } func testCaseB() { do { guard let compressed = ZLib.deflate([], level: -1) else { return XCTFail() } XCTAssert(compressed == []) XCTAssert(ZLib.inflate(compressed) == nil) } do { var data: [UInt8] = [] for _ in 0..<1234 { if arc4random_uniform(2) > 0 { data.append(UInt8(arc4random_uniform(256))) } else { data.append(0) } } guard let compressed = ZLib.deflate(data, level: -1) else { return XCTFail() } XCTAssert((!compressed.isEmpty) && (compressed.count < data.count)) guard let decompressed = ZLib.inflate(compressed) else { return XCTFail() } XCTAssert(decompressed == data) } } func testCaseC() { do { guard let compressed = ZLib.deflate([], level: 0) else { return XCTFail() } XCTAssert(compressed == []) XCTAssert(ZLib.inflate(compressed) == nil) } do { var data: [UInt8] = [] for _ in 0..<1234 { if arc4random_uniform(2) > 0 { data.append(UInt8(arc4random_uniform(256))) } else { data.append(0) } } guard let compressed = ZLib.deflate(data, level: 0) else { return XCTFail() } XCTAssert(!compressed.isEmpty) guard let decompressed = ZLib.inflate(compressed) else { return XCTFail() } XCTAssert(decompressed == data) } } }
28.868056
83
0.521049
5d6ad7bad21e3eedbc37f19f058ed7991c93e10d
325
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest class AWSS3StorageServiceUploadBehaviorTests: AWSS3StorageServiceTestBase { func testClassMustNotBeEmpty() { // Swift format crashes if a test class is empty } }
21.666667
75
0.726154
1d068b5a1a3d21aa14c8b90ce9f92e4abe9533d8
886
// // LandmarkDetail.swift // SwiftUITest // // Created by freshera on 2021/6/7. // import SwiftUI struct LandmarkDetail: View { var entity: Landmark var body: some View { VStack { CircleImage(imageName: entity.imageName) .padding(.top, 50.0) VStack(alignment: .leading) { Text(entity.name) .font(.title) HStack { Text(entity.description) .font(.subheadline) Spacer() } Spacer() } .padding() } .navigationTitle("详情") .navigationBarTitleDisplayMode(.inline) } } struct LandmarkDetail_Previews: PreviewProvider { static var previews: some View { LandmarkDetail(entity: landmarks[0]) } }
21.609756
52
0.490971
20cde9966d9d880ff5248e4d6b170d00479ff730
927
// // CGColor+IsEqual.swift // SExtensions // // Created by Ray on 2019/1/24. // Copyright © 2019 Ray. All rights reserved. // import CoreGraphics public extension CGColor { /// Returns true if self is equal to another CGColor with different color space. /// /// let clearColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor /// print(clearColor.isEqualWithConversion(to: UIColor.clear.cgColor)) /// // Prints "true" /// /// - Parameter other: Another CGColor. /// - Returns: Returns `true` if self is the same color as another CGColor with different color space; otherwise returns `false`. func isEqualWithConversion(to other: CGColor) -> Bool { guard let space = colorSpace else { return false } guard let converted = other.converted(to: space, intent: .defaultIntent, options: nil) else { return false } return self == converted } }
34.333333
133
0.658037