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
ac38c0bade353c99791e459c2dd030380e3c2207
2,164
// // AppDelegate.swift // TinderLab // // Created by Thalia on 3/14/18. // Copyright © 2018 Thalia . All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.042553
285
0.754159
18bf71fc41cebe8f89a3f5a51ebfe0ebbcb572dd
15,968
// // UserAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import RxSwift open class UserAPI { /** Create user - parameter body: (body) Created user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Create user - POST /user - This can only be done by the logged in user. - parameter body: (body) Created user object - returns: RequestBuilder<Void> */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder<Void> { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Creates list of users with given input array - POST /user/createWithArray - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Creates list of users with given input array - POST /user/createWithList - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Delete user - parameter username: (path) The name that needs to be deleted - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Delete user - DELETE /user/{username} - This can only be done by the logged in user. - parameter username: (path) The name that needs to be deleted - returns: RequestBuilder<Void> */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> { var path = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String: Any]? = nil let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Get user by user name - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<User> */ open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<User> { return Observable.create { observer -> Disposable in getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): observer.onNext(response.body!) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Get user by user name - GET /user/{username} - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder<User> */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> { var path = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters: [String: Any]? = nil let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Logs user into the system - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<String> */ open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<String> { return Observable.create { observer -> Disposable in loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): observer.onNext(response.body!) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Logs user into the system - GET /user/login - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - returns: RequestBuilder<String> */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path let parameters: [String: Any]? = nil var urlComponents = URLComponents(string: URLString) urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Logs out current logged in user session - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Logs out current logged in user session - GET /user/logout - returns: RequestBuilder<Void> */ open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path let parameters: [String: Any]? = nil let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Updated user - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<Void> */ open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<Void> { return Observable.create { observer -> Disposable in updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: observer.onNext(()) case let .failure(error): observer.onError(error) } observer.onCompleted() } return Disposables.create() } } /** Updated user - PUT /user/{username} - This can only be done by the logged in user. - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - returns: RequestBuilder<Void> */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder<Void> { var path = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } }
39.92
159
0.643349
de40b1a6b86b27053acc3b1bb992ec575a7c0139
5,668
@_exported import ObjectiveC @_exported import CoreGraphics @_exported import Foundation @_silgen_name("swift_StringToNSString") internal func _convertStringToNSString(_ string: String) -> NSString @_silgen_name("swift_NSStringToString") internal func _convertNSStringToString(_ nsstring: NSString?) -> String public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) } public let NSUTF8StringEncoding: UInt = 8 // NSArray bridging entry points func _convertNSArrayToArray<T>(_ nsarr: NSArray?) -> [T] { return [T]() } func _convertArrayToNSArray<T>(_ arr: [T]) -> NSArray { return NSArray() } // NSDictionary bridging entry points internal func _convertDictionaryToNSDictionary<Key, Value>( _ d: Dictionary<Key, Value> ) -> NSDictionary { return NSDictionary() } internal func _convertNSDictionaryToDictionary<K: NSObject, V: AnyObject>( _ d: NSDictionary? ) -> Dictionary<K, V> { return Dictionary<K, V>() } // NSSet bridging entry points internal func _convertSetToNSSet<T : Hashable>(_ s: Set<T>) -> NSSet { return NSSet() } internal func _convertNSSetToSet<T : Hashable>(_ s: NSSet?) -> Set<T> { return Set<T>() } extension String : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSString { return NSString() } public static func _forceBridgeFromObjectiveC(_ x: NSString, result: inout String?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSString?) -> String { return String() } } extension Int : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Int { return 0 } } extension Array : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSArray { return NSArray() } public static func _forceBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSArray? ) -> Array { return Array() } } extension Dictionary : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSDictionary { return NSDictionary() } public static func _forceBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSDictionary? ) -> Dictionary { return Dictionary() } } extension Set : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSSet { return NSSet() } public static func _forceBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSSet? ) -> Set { return Set() } } extension CGFloat : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> CGFloat { return CGFloat() } } extension NSRange : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public func _bridgeToObjectiveC() -> NSValue { return NSValue() } public static func _forceBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSValue? ) -> NSRange { return NSRange() } } extension NSError : ErrorProtocol { public var _domain: String { return domain } public var _code: Int { return code } } extension NSArray { @objc(methodIntroducedInOverlay) public func introducedInOverlay() { } } @_silgen_name("swift_convertNSErrorToErrorProtocol") func _convertNSErrorToErrorProtocol(_ string: NSError?) -> ErrorProtocol @_silgen_name("swift_convertErrorProtocolToNSError") func _convertErrorProtocolToNSError(_ string: ErrorProtocol) -> NSError
23.134694
85
0.695483
674550b8d2014115d4f80fa6e9b0e8625c9ea5d3
3,487
// // Authenticator.swift // WebAuthnKit // // Created by Lyo Kato on 2018/11/20. // Copyright © 2018 Lyo Kato. All rights reserved. // import Foundation import LocalAuthentication public struct AuthenticatorAssertionResult { var credentailId: [UInt8]? var userHandle: [UInt8]? var signature: [UInt8] var authenticatorData: [UInt8] init(authenticatorData: [UInt8], signature: [UInt8]) { self.authenticatorData = authenticatorData self.signature = signature } } public protocol AuthenticatorMakeCredentialSessionDelegate: class { func authenticatorSessionDidBecomeAvailable(session: AuthenticatorMakeCredentialSession) func authenticatorSessionDidBecomeUnavailable(session: AuthenticatorMakeCredentialSession) func authenticatorSessionDidStopOperation(session: AuthenticatorMakeCredentialSession, reason: WAKError) func authenticatorSessionDidMakeCredential(session: AuthenticatorMakeCredentialSession, attestation: AttestationObject) } public protocol AuthenticatorGetAssertionSessionDelegate: class { func authenticatorSessionDidBecomeAvailable(session: AuthenticatorGetAssertionSession) func authenticatorSessionDidBecomeUnavailable(session: AuthenticatorGetAssertionSession) func authenticatorSessionDidStopOperation(session: AuthenticatorGetAssertionSession, reason: WAKError) func authenticatorSessionDidDiscoverCredential(session: AuthenticatorGetAssertionSession, assertion: AuthenticatorAssertionResult) } public protocol AuthenticatorGetAssertionSession { var attachment: AuthenticatorAttachment { get } var transport: AuthenticatorTransport { get } var delegate: AuthenticatorGetAssertionSessionDelegate? { set get } func getAssertion( rpId: String, hash: [UInt8], allowCredentialDescriptorList: [PublicKeyCredentialDescriptor], requireUserPresence: Bool, requireUserVerification: Bool // extensions: [] ) func canPerformUserVerification() -> Bool func start() func cancel(reason: WAKError) } public protocol AuthenticatorMakeCredentialSession { var attachment: AuthenticatorAttachment { get } var transport: AuthenticatorTransport { get } var delegate: AuthenticatorMakeCredentialSessionDelegate? { set get } func makeCredential( hash: [UInt8], rpEntity: PublicKeyCredentialRpEntity, userEntity: PublicKeyCredentialUserEntity, requireResidentKey: Bool, requireUserPresence: Bool, requireUserVerification: Bool, credTypesAndPubKeyAlgs: [PublicKeyCredentialParameters], excludeCredentialDescriptorList: [PublicKeyCredentialDescriptor] ) func canPerformUserVerification() -> Bool func canStoreResidentKey() -> Bool func start() func cancel(reason: WAKError) } public protocol Authenticator { var attachment: AuthenticatorAttachment { get } var transport: AuthenticatorTransport { get } var counterStep: UInt32 { set get } var allowResidentKey: Bool { get } var allowUserVerification: Bool { get } func newMakeCredentialSession(context: LAContext?) -> AuthenticatorMakeCredentialSession func newGetAssertionSession(context: LAContext?) -> AuthenticatorGetAssertionSession }
34.87
134
0.723258
eb8a7726aec7cd100d5a3abc8e9ad452bd7ad4a8
1,603
// // 705-DesignHashset.swift // AlgorithmPractice // // Created by guojie shi on 2021/3/13. // Copyright © 2021 Jeffrey. All rights reserved. // import Foundation /* 705. 设计哈希集合 不使用任何内建的哈希表库设计一个哈希集合(HashSet)。 实现 MyHashSet 类: void add(key) 向哈希集合中插入值 key 。 bool contains(key) 返回哈希集合中是否存在这个值 key 。 void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。 示例: 输入: ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] [[], [1], [2], [1], [3], [2], [2], [2], [2]] 输出: [null, null, null, true, false, null, true, null, false] 解释: MyHashSet myHashSet = new MyHashSet(); myHashSet.add(1); // set = [1] myHashSet.add(2); // set = [1, 2] myHashSet.contains(1); // 返回 True myHashSet.contains(3); // 返回 False ,(未找到) myHashSet.add(2); // set = [1, 2] myHashSet.contains(2); // 返回 True myHashSet.remove(2); // set = [1] myHashSet.contains(2); // 返回 False ,(已移除) 提示: 0 <= key <= 106 最多调用 104 次 add、remove 和 contains 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-hashset 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ extension Solution { static func test705() { let hashSet = MyHashSetWithSystem() hashSet.add(1) hashSet.add(2) hashSet.remove(3) print(hashSet.contains(2)) } } class MyHashSet { // 可以使用数组或者哈希链表法 } // 使用系统方法实现 class MyHashSetWithSystem { var hashSet: Set<Int> = [] init() {} func add(_ key: Int) { hashSet.insert(key) } func remove(_ key: Int) { hashSet.remove(key) } func contains(_ key: Int) -> Bool { return hashSet.contains(key) } }
19.54878
93
0.630069
1a106f017e9a93b9bc49e8ae93f0a62a083a8a07
3,583
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. import SotoCore /// Error enum for Appflow public struct AppflowErrorType: AWSErrorType { enum Code: String { case conflictException = "ConflictException" case connectorAuthenticationException = "ConnectorAuthenticationException" case connectorServerException = "ConnectorServerException" case internalServerException = "InternalServerException" case resourceNotFoundException = "ResourceNotFoundException" case serviceQuotaExceededException = "ServiceQuotaExceededException" case unsupportedOperationException = "UnsupportedOperationException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize Appflow public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// There was a conflict when processing the request (for example, a flow with the given name already exists within the account. Check for conflicting resource names and try again. public static var conflictException: Self { .init(.conflictException) } /// An error occurred when authenticating with the connector endpoint. public static var connectorAuthenticationException: Self { .init(.connectorAuthenticationException) } /// An error occurred when retrieving data from the connector endpoint. public static var connectorServerException: Self { .init(.connectorServerException) } /// An internal service error occurred during the processing of your request. Try again later. public static var internalServerException: Self { .init(.internalServerException) } /// The resource specified in the request (such as the source or destination connector profile) is not found. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// The request would cause a service quota (such as the number of flows) to be exceeded. public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) } /// The requested operation is not supported for the current flow. public static var unsupportedOperationException: Self { .init(.unsupportedOperationException) } /// The request has invalid or missing parameters. public static var validationException: Self { .init(.validationException) } } extension AppflowErrorType: Equatable { public static func == (lhs: AppflowErrorType, rhs: AppflowErrorType) -> Bool { lhs.error == rhs.error } } extension AppflowErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
44.7875
185
0.700251
21180776f259996050ab7499aa85bb3cdbc8ae20
372
import UIKit public struct SlidingProperties { let fromX: CGFloat let toX: CGFloat let animationDuration: TimeInterval public init(fromX: CGFloat = 0, toX: CGFloat = UIScreen.main.bounds.width * 1.2, animationDuration: TimeInterval = 0.7) { self.fromX = fromX self.toX = toX self.animationDuration = animationDuration } }
26.571429
125
0.674731
1407d37ba8dc83db92db908d319a63a970d40ffa
2,195
// // AppDelegate.swift // ElanCard // // Created by Imrane EL HAMIANI on 09/27/2017. // Copyright (c) 2017 Imrane EL HAMIANI. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private 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:. } }
46.702128
285
0.754442
1eb836b689e783822e719663f4995b36b21b095b
1,402
// // WeatherDaysForecastView.swift // Pretty Weather // // Created by Bart Chrzaszcz on 2017-12-31. // Copyright © 2017 Bart Chrzaszcz. All rights reserved. // import UIKit import Cartography class WeatherDaysForecastView: UIView { static var HEIGHT: CGFloat { get { return 300 } } private var didSetupConstraints = false override init(frame: CGRect) { super.init(frame: frame) setup() style() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // This method is called by the framework when all other constraints are set and the view needs to be laid out override func updateConstraints() { if didSetupConstraints { super.updateConstraints() return } layoutView() super.updateConstraints() didSetupConstraints = true } } // MARK: - Setup private extension WeatherDaysForecastView { func setup() { } } // MARK: - Layout private extension WeatherDaysForecastView { func layoutView() { constrain(self) { view in view.height == WeatherDaysForecastView.HEIGHT return } } } // MARK: - Style private extension WeatherDaysForecastView { func style() { backgroundColor = UIColor.blue } }
20.925373
114
0.61127
9b91989d63f8433f9fff7cf6272225e7a8bb6573
38,060
// // BarChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class BarChartRenderer: BarLineScatterCandleBubbleRenderer { /// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver /// /// Its use is apparent when there are multiple data sets, since we want to read bars in left to right order, /// irrespective of dataset. However, drawing is done per dataset, so using this array and then flattening it prevents us from needing to /// re-render for the sake of accessibility. /// /// In practise, its structure is: /// /// ```` /// [ /// [dataset1 element1, dataset2 element1], /// [dataset1 element2, dataset2 element2], /// [dataset1 element3, dataset2 element3] /// ... /// ] /// ```` /// This is done to provide numerical inference across datasets to a screenreader user, in the same way that a sighted individual /// uses a multi-dataset bar chart. /// /// The ````internal```` specifier is to allow subclasses (HorizontalBar) to populate the same array internal lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements() internal var barCornerRadius = CGFloat(0) internal var barCorners: UIRectCorner = [.allCorners] private typealias Buffer = [CGRect] @objc open weak var dataProvider: BarChartDataProvider? @objc public init(dataProvider: BarChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } // [CGRect] per dataset private var _buffers = [Buffer]() open override func initBuffers() { guard let barData = dataProvider?.barData else { return _buffers.removeAll() } // Match buffers count to dataset count if _buffers.count != barData.count { while _buffers.count < barData.count { _buffers.append(Buffer()) } while _buffers.count > barData.count { _buffers.removeLast() } } _buffers = zip(_buffers, barData).map { buffer, set -> Buffer in let set = set as! BarChartDataSetProtocol let size = set.entryCount * (set.isStacked ? set.stackSize : 1) return buffer.count == size ? buffer : Buffer(repeating: .zero, count: size) } } private func prepareBuffer(dataSet: BarChartDataSetProtocol, index: Int) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } let barWidthHalf = CGFloat(barData.barWidth / 2.0) var bufferIndex = 0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) let phaseY = CGFloat(animator.phaseY) for i in (0..<dataSet.entryCount).clamped(to: 0..<Int(ceil(Double(dataSet.entryCount) * animator.phaseX))) { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } let x = CGFloat(e.x) let left = x - barWidthHalf let right = x + barWidthHalf var y = e.y if containsStacks, let vals = e.yValues { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // fill the stack for value in vals { if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value yStart = y } else if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } var top = isInverted ? (y <= yStart ? CGFloat(y) : CGFloat(yStart)) : (y >= yStart ? CGFloat(y) : CGFloat(yStart)) var bottom = isInverted ? (y >= yStart ? CGFloat(y) : CGFloat(yStart)) : (y <= yStart ? CGFloat(y) : CGFloat(yStart)) // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY let barRect = CGRect(x: left, y: top, width: right - left, height: bottom - top) _buffers[index][bufferIndex] = barRect bufferIndex += 1 } } else { var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) /* When drawing each bar, the renderer actually draws each bar from 0 to the required value. * This drawn bar is then clipped to the visible chart rect in BarLineChartViewBase's draw(rect:) using clipDataToContent. * While this works fine when calculating the bar rects for drawing, it causes the accessibilityFrames to be oversized in some cases. * This offset attempts to undo that unnecessary drawing when calculating barRects * * +---------------------------------------------------------------+---------------------------------------------------------------+ * | Situation 1: (!inverted && y >= 0) | Situation 3: (inverted && y >= 0) | * | | | * | y -> +--+ <- top | 0 -> ---+--+---+--+------ <- top | * | |//| } topOffset = y - max | | | |//| } topOffset = min | * | max -> +---------+--+----+ <- top - topOffset | min -> +--+--+---+--+----+ <- top + topOffset | * | | +--+ |//| | | | | | |//| | | * | | | | |//| | | | +--+ |//| | | * | | | | |//| | | | |//| | | * | min -> +--+--+---+--+----+ <- bottom + bottomOffset | max -> +---------+--+----+ <- bottom - bottomOffset | * | | | |//| } bottomOffset = min | |//| } bottomOffset = y - max | * | 0 -> ---+--+---+--+----- <- bottom | y -> +--+ <- bottom | * | | | * +---------------------------------------------------------------+---------------------------------------------------------------+ * | Situation 2: (!inverted && y < 0) | Situation 4: (inverted && y < 0) | * | | | * | 0 -> ---+--+---+--+----- <- top | y -> +--+ <- top | * | | | |//| } topOffset = -max | |//| } topOffset = min - y | * | max -> +--+--+---+--+----+ <- top - topOffset | min -> +---------+--+----+ <- top + topOffset | * | | | | |//| | | | +--+ |//| | | * | | +--+ |//| | | | | | |//| | | * | | |//| | | | | | |//| | | * | min -> +---------+--+----+ <- bottom + bottomOffset | max -> +--+--+---+--+----+ <- bottom - bottomOffset | * | |//| } bottomOffset = min - y | | | |//| } bottomOffset = -max | * | y -> +--+ <- bottom | 0 -> ---+--+---+--+------- <- bottom | * | | | * +---------------------------------------------------------------+---------------------------------------------------------------+ */ var topOffset: CGFloat = 0.0 var bottomOffset: CGFloat = 0.0 if let offsetView = dataProvider as? BarChartView { let offsetAxis = offsetView.getAxis(dataSet.axisDependency) if y >= 0 { // situation 1 if offsetAxis.axisMaximum < y { topOffset = CGFloat(y - offsetAxis.axisMaximum) } if offsetAxis.axisMinimum > 0 { bottomOffset = CGFloat(offsetAxis.axisMinimum) } } else // y < 0 { //situation 2 if offsetAxis.axisMaximum < 0 { topOffset = CGFloat(offsetAxis.axisMaximum * -1) } if offsetAxis.axisMinimum > y { bottomOffset = CGFloat(offsetAxis.axisMinimum - y) } } if isInverted { // situation 3 and 4 // exchange topOffset/bottomOffset based on 1 and 2 // see diagram above (topOffset, bottomOffset) = (bottomOffset, topOffset) } } //apply offset top = isInverted ? top + topOffset : top - topOffset bottom = isInverted ? bottom - bottomOffset : bottom + bottomOffset // multiply the height of the rect with the phase // explicitly add 0 + topOffset to indicate this is changed after adding accessibility support (#3650, #3520) if top > 0 + topOffset { top *= phaseY } else { bottom *= phaseY } let barRect = CGRect(x: left, y: top, width: right - left, height: bottom - top) _buffers[index][bufferIndex] = barRect bufferIndex += 1 } } } open override func drawData(context: CGContext) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements() // Make the chart header the first element in the accessible elements array if let chart = dataProvider as? BarChartView { let element = createAccessibleHeader(usingChart: chart, andData: barData, withDefaultDescription: "Bar Chart") accessibleChartElements.append(element) } // Populate logically ordered nested elements into accessibilityOrderedElements in drawDataSet() for i in barData.indices { guard let set = barData[i] as? BarChartDataSetProtocol else { fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset") } guard set.isVisible else { continue } drawDataSet(context: context, dataSet: set, index: i) } // Merge nested ordered arrays into the single accessibleChartElements. accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } ) accessibilityPostLayoutChangedNotification() } private var _barShadowRectBuffer: CGRect = CGRect() @objc open func drawDataSet(context: CGContext, dataSet: BarChartDataSetProtocol, index: Int) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) prepareBuffer(dataSet: dataSet, index: index) trans.rectValuesToPixel(&_buffers[index]) let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 context.saveGState() defer { context.restoreGState() } // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { guard let barData = dataProvider.barData else { return } let barWidth = barData.barWidth let barWidthHalf = barWidth / 2.0 var x: Double = 0.0 let range = (0..<dataSet.entryCount).clamped(to: 0..<Int(ceil(Double(dataSet.entryCount) * animator.phaseX))) for i in range { guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue } x = e.x _barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf) _barShadowRectBuffer.size.width = CGFloat(barWidth) trans.rectValueToPixel(&_barShadowRectBuffer) guard viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width) else { continue } guard viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x) else { break } _barShadowRectBuffer.origin.y = viewPortHandler.contentTop _barShadowRectBuffer.size.height = viewPortHandler.contentHeight context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(_barShadowRectBuffer) } } let buffer = _buffers[index] // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { for barRect in buffer where viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width) { guard viewPortHandler.isInBoundsRight(barRect.origin.x) else { break } context.setFillColor(dataSet.barShadowColor.cgColor) // let bezierPath = UIBezierPath( // roundedRect: barRect, // cornerRadius: barCornerRadius // ) // context.addPath(bezierPath.cgPath) // context.drawPath(using: .fill) } } let isSingleColor = dataSet.colors.count == 1 if isSingleColor { context.setFillColor(dataSet.color(atIndex: 0).cgColor) } // In case the chart is stacked, we need to accomodate individual bars within accessibilityOrdereredElements let isStacked = dataSet.isStacked let stackSize = isStacked ? dataSet.stackSize : 1 for j in buffer.indices { let barRect = buffer[j] guard viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width) else { continue } guard viewPortHandler.isInBoundsRight(barRect.origin.x) else { break } if !isSingleColor { // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.color(atIndex: j).cgColor) } let bezierPath = UIBezierPath( roundedRect: barRect, byRoundingCorners: barCorners, cornerRadii: CGSize(width: barCornerRadius, height: barCornerRadius) ) context.addPath(bezierPath.cgPath) context.drawPath(using: .fill) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } // Create and append the corresponding accessibility element to accessibilityOrderedElements if let chart = dataProvider as? BarChartView { let element = createAccessibleElement( withIndex: j, container: chart, dataSet: dataSet, dataSetIndex: index, stackSize: stackSize ) { (element) in element.accessibilityFrame = barRect } accessibilityOrderedElements[j/stackSize].append(element) } } } open func prepareBarHighlight( x: Double, y1: Double, y2: Double, barWidthHalf: Double, trans: Transformer, rect: inout CGRect) { let left = x - barWidthHalf let right = x + barWidthHalf let top = y1 let bottom = y2 rect.origin.x = CGFloat(left) rect.origin.y = CGFloat(top) rect.size.width = CGFloat(right - left) rect.size.height = CGFloat(bottom - top) trans.rectValueToPixel(&rect, phaseY: animator.phaseY ) } open override func drawValues(context: CGContext) { // if values are drawn if isDrawingValuesAllowed(dataProvider: dataProvider) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } let valueOffsetPlus: CGFloat = 4.5 var posOffset: CGFloat var negOffset: CGFloat let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled for dataSetIndex in barData.indices { guard let dataSet = barData[dataSetIndex] as? BarChartDataSetProtocol, shouldDrawValues(forDataSet: dataSet) else { continue } let angleRadians = dataSet.valueLabelAngle.DEG2RAD let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if isInverted { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } let buffer = _buffers[dataSetIndex] let formatter = dataSet.valueFormatter let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY let iconsOffset = dataSet.iconsOffset // if only single values are drawn (sum) if !dataSet.isStacked { let range = 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX)) for j in range { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let rect = buffer[j] let x = rect.origin.x + rect.size.width / 2.0 guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(rect.origin.y), viewPortHandler.isInBoundsLeft(x) else { continue } let val = e.y if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(j), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset) px += iconsOffset.x py += iconsOffset.y context.drawImage(icon, atCenter: CGPoint(x: px, y: py), size: icon.size) } } } else { // if we have stacks var bufferIndex = 0 let lastIndex = ceil(Double(dataSet.entryCount) * animator.phaseX) for index in 0 ..< Int(lastIndex) { guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue } let vals = e.yValues let rect = buffer[bufferIndex] let x = rect.origin.x + rect.size.width / 2.0 // we still draw stacked bars, but there is one non-stacked in between if let values = vals { // draw stack values var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for value in values { let y: Double if value == 0.0 && (posY == 0.0 || negY == 0.0) { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value } else if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY))) } trans.pointValuesToPixel(&transformed) for (value, transformed) in zip(values, transformed) { let drawBelow = (value == 0.0 && negY == 0.0 && posY > 0.0) || value < 0.0 let y = transformed.y + (drawBelow ? negOffset : posOffset) guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(y), viewPortHandler.isInBoundsLeft(x) else { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( value, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: y, font: valueFont, align: .center, color: dataSet.valueTextColorAt(index), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians) } if let icon = e.icon, dataSet.isDrawIconsEnabled { context.drawImage(icon, atCenter: CGPoint(x: x + iconsOffset.x, y: y + iconsOffset.y), size: icon.size) } } } else { guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(rect.origin.y), viewPortHandler.isInBoundsLeft(x) else { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler), xPos: x, yPos: rect.origin.y + (e.y >= 0 ? posOffset : negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(index), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = rect.origin.y + (e.y >= 0 ? posOffset : negOffset) px += iconsOffset.x py += iconsOffset.y context.drawImage(icon, atCenter: CGPoint(x: px, y: py), size: icon.size) } } bufferIndex += vals?.count ?? 1 } } } } } /// Draws a value at the specified x and y position. @objc open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: TextAlignment, color: NSUIColor, anchor: CGPoint, angleRadians: CGFloat) { if (angleRadians == 0.0) { context.drawText(value, at: CGPoint(x: xPos, y: yPos), align: align, attributes: [.font: font, .foregroundColor: color]) } else { // align left to center text with rotation context.drawText(value, at: CGPoint(x: xPos, y: yPos), align: align, anchor: anchor, angleRadians: angleRadians, attributes: [.font: font, .foregroundColor: color]) } } open override func drawExtras(context: CGContext) { } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } context.saveGState() defer { context.restoreGState() } var barRect = CGRect() for high in indices { guard let set = barData[high.dataSetIndex] as? BarChartDataSetProtocol, set.isHighlightEnabled else { continue } if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry { guard isInBoundsX(entry: e, dataSet: set) else { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) context.setFillColor(set.highlightColor.cgColor) context.setAlpha(set.highlightAlpha) let isStack = high.stackIndex >= 0 && e.isStacked let y1: Double let y2: Double if isStack { if dataProvider.isHighlightFullBarEnabled { y1 = e.positiveSum y2 = -e.negativeSum } else { let range = e.ranges?[high.stackIndex] y1 = range?.from ?? 0.0 y2 = range?.to ?? 0.0 } } else { y1 = e.y y2 = 0.0 } prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect) setHighlightDrawPos(highlight: high, barRect: barRect) let bezierPath = UIBezierPath( roundedRect: barRect, cornerRadius: barCornerRadius ) context.addPath(bezierPath.cgPath) context.drawPath(using: .fill) } } } /// Sets the drawing position of the highlight object based on the given bar-rect. internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect) { high.setDraw(x: barRect.midX, y: barRect.origin.y) } /// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements. /// This is marked internal to support HorizontalBarChartRenderer as well. internal func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]] { guard let chart = dataProvider as? BarChartView else { return [] } // Unlike Bubble & Line charts, here we use the maximum entry count to account for stacked bars let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0 return Array(repeating: [NSUIAccessibilityElement](), count: maxEntryCount) } /// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart /// i.e. in case of a stacked chart, this returns each stack, not the combined bar. /// Note that it is marked internal to support subclass modification in the HorizontalBarChart. internal func createAccessibleElement(withIndex idx: Int, container: BarChartView, dataSet: BarChartDataSetProtocol, dataSetIndex: Int, stackSize: Int, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) let xAxis = container.xAxis guard let e = dataSet.entryForIndex(idx/stackSize) as? BarChartDataEntry else { return element } guard let dataProvider = dataProvider else { return element } // NOTE: The formatter can cause issues when the x-axis labels are consecutive ints. // i.e. due to the Double conversion, if there are more than one data set that are grouped, // there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution. let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)" var elementValueText = dataSet.valueFormatter.stringForValue( e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) if dataSet.isStacked, let vals = e.yValues { let labelCount = min(dataSet.colors.count, stackSize) let stackLabel: String? if (!dataSet.stackLabels.isEmpty && labelCount > 0) { let labelIndex = idx % labelCount stackLabel = dataSet.stackLabels.indices.contains(labelIndex) ? dataSet.stackLabels[labelIndex] : nil } else { stackLabel = nil } //Handles empty array of yValues let yValue = vals.isEmpty ? 0.0 : vals[idx % vals.count] elementValueText = dataSet.valueFormatter.stringForValue( yValue, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) if let stackLabel = stackLabel { elementValueText = stackLabel + " \(elementValueText)" } else { elementValueText = "\(elementValueText)" } } let dataSetCount = dataProvider.barData?.dataSetCount ?? -1 let doesContainMultipleDataSets = dataSetCount > 1 element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)" modifier(element) return element } }
44.566745
190
0.427903
69eacc53469ce413f1a932aac9a62c333c315e11
2,759
// // BookSearchUseCase.swift // TReader // // Created by tadas on 2020-09-05. // Copyright © 2020 Scale3C. All rights reserved. // import Foundation import RxSwift import RxCocoa protocol BookSearchUseCase { func search(query: String, in book: Book) -> Observable<[BookSearchResult]> } class DefaultBookSearchUseCase: BookSearchUseCase { private let filesService: BookFilesService private let prefixLenth = 25 init(filesService: BookFilesService) { self.filesService = filesService } func search(query: String, in book: Book) -> Observable<[BookSearchResult]> { Observable.create { [weak self] observer -> Disposable in guard let `self` = self else { return Disposables.create() } do { var result = [BookSearchResult]() try book.chapters.forEach { chapter in let file = self.filesService.getChapterUrl(id: book.info.id, chapterFile: chapter.fileName) // var data = try Data(contentsOf: file) let text = try self.html2String(url: file) let regex = try NSRegularExpression(pattern: query, options: .caseInsensitive) let range = NSRange(location: 0, length: text.utf16.count) regex.enumerateMatches(in: text, options: [], range: range) { (match, _, _) in guard let range = match?.range, range.location != NSNotFound else { return } let lowerBound = max(0, range.lowerBound - self.prefixLenth) let upperBound = min(text.count, range.upperBound + self.prefixLenth) let start = text.index(text.startIndex, offsetBy: lowerBound) let end = text.index(text.startIndex, offsetBy: upperBound) let subString = text[start..<end] let model = BookSearchResult(chapterId: chapter.id, chapterTitle: chapter.title, text: String(subString)) result.append(model) } } observer.onNext(result) } catch { observer.onError(error) } return Disposables.create() } .observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) } func html2String(url: URL) throws -> String { let type = NSAttributedString.DocumentType.html let encoding = String.Encoding.utf8.rawValue let str = try NSAttributedString(url: url, options: [.documentType: type, .characterEncoding: encoding], documentAttributes: nil) return str.string } }
41.179104
129
0.58282
d6584848d9860a2135a12eec87fbdbe0a6f55ed3
3,195
// // AppDelegate.swift // ZDOpenSourceSwiftDemo // // Created by Zero.D.Saber on 2017/8/4. // Copyright © 2017年 Zero.D.Saber. All rights reserved. // import UIKit import GDPerformanceView_Swift import Buglife import Watchdog @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var watchDog: Watchdog! private func showPerformanceMonitor() { // performanceMonitor PerformanceMonitor.shared().start() } internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //watchDog = Watchdog(threshold: 0.4, strictMode: true) showPerformanceMonitor() // bugMonitor Buglife.shared().start(withEmail: "[email protected]") //self.window?.swizzleShake() return true } func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return true } func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } override func becomeFirstResponder() -> Bool { return true } override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == .motionShake { } } }
39.444444
285
0.712363
56ec8fce21a76e28ff63cfd7fc68bf9cdfe16dff
399
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "NBBottomSheet", platforms: [.iOS(.v9)], products: [ .library( name: "NBBottomSheet", targets: ["NBBottomSheet"] ) ], targets: [ .target( name: "NBBottomSheet", path: "NBBottomSheet/NBBottomSheet/Sources" ) ] )
19
55
0.526316
e56d6f5b52fd9f6e648a625ae7f07f2ef1b454ab
600
// // TextFieldTableViewCell.swift // HealthApp // // Created by Moisés Córdova on 7/9/19. // Copyright © 2019 Moisés Córdova. All rights reserved. // import UIKit class TextFieldTableViewCell: UITableViewCell { @IBOutlet var textField: UITextField! override func awakeFromNib() { super.awakeFromNib() textField.useUnderline() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
23.076923
65
0.656667
6215a45fac8807170179a81e2355a6a01cd365cb
1,377
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // IntegerBitPackingTests+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension IntegerBitPackingTests { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (IntegerBitPackingTests) -> () throws -> Void)] { return [ ("testAllUInt8PairsRoundtrip", testAllUInt8PairsRoundtrip), ("testExtremesWorkForUInt32UInt16UInt8", testExtremesWorkForUInt32UInt16UInt8), ("testExtremesWorkForUInt16UInt8", testExtremesWorkForUInt16UInt8), ("testExtremesWorkForUInt32CInt", testExtremesWorkForUInt32CInt), ] } }
36.236842
162
0.634713
2897d4f3fe077807e2bc9baa7db4768a73751d64
27,613
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @_implementationOnly import _SwiftConcurrencyShims // ==== Task ------------------------------------------------------------------- /// An asynchronous task (just "Task" hereafter) is the analogue of a thread for /// asynchronous functions. All asynchronous functions run as part of some task. /// /// A task can only be interacted with by code running "in" the task, /// by invoking the appropriate context sensitive static functions which operate /// on the "current" task. Because all such functions are `async` they can only /// be invoked as part of an existing task, and therefore are guaranteed to be /// effective. /// /// A task's execution can be seen as a series of periods where the task was /// running. Each such period ends at a suspension point or -- finally -- the /// completion of the task. /// /// These partial periods towards the task's completion are `PartialAsyncTask`. /// Partial tasks are generally not interacted with by end-users directly, /// unless implementing a scheduler. @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public struct Task { internal let _task: Builtin.NativeObject // May only be created by the standard library. internal init(_ task: Builtin.NativeObject) { self._task = task } } // ==== Current Task ----------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// Returns 'current' `Task` instance, representing the task from within which /// this function was called. /// /// All functions available on the Task public static var current: Task? { guard let _task = _getCurrentAsyncTask() else { return nil } // FIXME: This retain seems pretty wrong, however if we don't we WILL crash // with "destroying a task that never completed" in the task's destroy. // How do we solve this properly? _swiftRetain(_task) return Task(_task) } } // ==== Task Priority ---------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// Returns the `current` task's priority. /// /// If no current `Task` is available, returns `Priority.default`. /// /// - SeeAlso: `Task.Priority` /// - SeeAlso: `Task.priority` public static var currentPriority: Priority { withUnsafeCurrentTask { task in task?.priority ?? Priority.default } } /// Returns the `current` task's priority. /// /// If no current `Task` is available, returns `Priority.default`. /// /// - SeeAlso: `Task.Priority` /// - SeeAlso: `Task.currentPriority` public var priority: Priority { getJobFlags(_task).priority } /// Task priority may inform decisions an `Executor` makes about how and when /// to schedule tasks submitted to it. /// /// ### Priority scheduling /// An executor MAY utilize priority information to attempt running higher /// priority tasks first, and then continuing to serve lower priority tasks. /// /// The exact semantics of how priority is treated are left up to each /// platform and `Executor` implementation. /// /// ### Priority inheritance /// Child tasks automatically inherit their parent task's priority. /// /// Detached tasks (created by `detach`) DO NOT inherit task priority, /// as they are "detached" from their parent tasks after all. /// /// ### Priority elevation /// In some situations the priority of a task must be elevated (or "escalated", "raised"): /// /// - if a `Task` running on behalf of an actor, and a new higher-priority /// task is enqueued to the actor, its current task must be temporarily /// elevated to the priority of the enqueued task, in order to allow the new /// task to be processed at--effectively-- the priority it was enqueued with. /// - this DOES NOT affect `Task.currentPriority()`. /// - if a task is created with a `Task.Handle`, and a higher-priority task /// calls the `await handle.get()` function the priority of this task must be /// permanently increased until the task completes. /// - this DOES affect `Task.currentPriority()`. /// /// TODO: Define the details of task priority; It is likely to be a concept /// similar to Darwin Dispatch's QoS; bearing in mind that priority is not as /// much of a thing on other platforms (i.e. server side Linux systems). public enum Priority: Int, Comparable { // Values must be same as defined by the internal `JobPriority`. case userInteractive = 0x21 case userInitiated = 0x19 case `default` = 0x15 case utility = 0x11 case background = 0x09 case unspecified = 0x00 public static func < (lhs: Priority, rhs: Priority) -> Bool { lhs.rawValue < rhs.rawValue } } } // ==== Task Handle ------------------------------------------------------------ @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// A task handle refers to an in-flight `Task`, /// allowing for potentially awaiting for its result or Cancelling it. /// /// It is not a programming error to drop a handle without awaiting or cancelling it, /// i.e. the task will run regardless of the handle still being present or not. /// Dropping a handle however means losing the ability to await on the task's result /// and losing the ability to cancel it. public struct Handle<Success, Failure: Error>: Sendable { internal let _task: Builtin.NativeObject internal init(_ task: Builtin.NativeObject) { self._task = task } /// Returns the `Task` that this handle refers to. public var task: Task { Task(_task) } /// Wait for the task to complete, returning (or throwing) its result. /// /// ### Priority /// If the task has not completed yet, its priority will be elevated to the /// priority of the current task. Note that this may not be as effective as /// creating the task with the "right" priority to in the first place. /// /// ### Cancellation /// If the awaited on task gets cancelled externally the `get()` will throw /// a cancellation error. /// /// If the task gets cancelled internally, e.g. by checking for cancellation /// and throwing a specific error or using `checkCancellation` the error /// thrown out of the task will be re-thrown here. public func get() async throws -> Success { return try await _taskFutureGetThrowing(_task) } /// Wait for the task to complete, returning its `Result`. /// /// ### Priority /// If the task has not completed yet, its priority will be elevated to the /// priority of the current task. Note that this may not be as effective as /// creating the task with the "right" priority to in the first place. /// /// ### Cancellation /// If the awaited on task gets cancelled externally the `get()` will throw /// a cancellation error. /// /// If the task gets cancelled internally, e.g. by checking for cancellation /// and throwing a specific error or using `checkCancellation` the error /// thrown out of the task will be re-thrown here. public func getResult() async -> Result<Success, Failure> { do { return .success(try await get()) } catch { return .failure(error as! Failure) // as!-safe, guaranteed to be Failure } } /// Attempt to cancel the task. /// /// Whether this function has any effect is task-dependent. /// /// For a task to respect cancellation it must cooperatively check for it /// while running. Many tasks will check for cancellation before beginning /// their "actual work", however this is not a requirement nor is it guaranteed /// how and when tasks check for cancellation in general. public func cancel() { Builtin.cancelAsyncTask(_task) } } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task.Handle where Failure == Never { /// Wait for the task to complete, returning its result. /// /// ### Priority /// If the task has not completed yet, its priority will be elevated to the /// priority of the current task. Note that this may not be as effective as /// creating the task with the "right" priority to in the first place. /// /// ### Cancellation /// The task this handle refers to may check for cancellation, however /// since it is not-throwing it would have to handle it using some other /// way than throwing a `CancellationError`, e.g. it could provide a neutral /// value of the `Success` type, or encode that cancellation has occurred in /// that type itself. public func get() async -> Success { return await _taskFutureGet(_task) } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task.Handle: Hashable { public func hash(into hasher: inout Hasher) { UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher) } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task.Handle: Equatable { public static func ==(lhs: Self, rhs: Self) -> Bool { UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) == UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task)) } } // ==== Conformances ----------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task: Hashable { public func hash(into hasher: inout Hasher) { UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher) } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task: Equatable { public static func ==(lhs: Self, rhs: Self) -> Bool { UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) == UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task)) } } // ==== Job Flags -------------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// Flags for schedulable jobs. /// /// This is a port of the C++ FlagSet. struct JobFlags { /// Kinds of schedulable jobs. enum Kind: Int { case task = 0 } /// The actual bit representation of these flags. var bits: Int = 0 /// The kind of job described by these flags. var kind: Kind { get { Kind(rawValue: bits & 0xFF)! } set { bits = (bits & ~0xFF) | newValue.rawValue } } /// Whether this is an asynchronous task. var isAsyncTask: Bool { kind == .task } /// The priority given to the job. var priority: Priority { get { Priority(rawValue: (bits & 0xFF00) >> 8)! } set { bits = (bits & ~0xFF00) | (newValue.rawValue << 8) } } /// Whether this is a child task. var isChildTask: Bool { get { (bits & (1 << 24)) != 0 } set { if newValue { bits = bits | 1 << 24 } else { bits = (bits & ~(1 << 24)) } } } /// Whether this is a future. var isFuture: Bool { get { (bits & (1 << 25)) != 0 } set { if newValue { bits = bits | 1 << 25 } else { bits = (bits & ~(1 << 25)) } } } /// Whether this is a group child. var isGroupChildTask: Bool { get { (bits & (1 << 26)) != 0 } set { if newValue { bits = bits | 1 << 26 } else { bits = (bits & ~(1 << 26)) } } } } } // ==== Detached Tasks --------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { @discardableResult @available(*, deprecated, message: "`Task.runDetached` was replaced by `detach` and will be removed shortly.") public func runDetached<T>( priority: Task.Priority = .unspecified, operation: __owned @Sendable @escaping () async throws -> T ) -> Task.Handle<T, Error> { detach(priority: priority, operation: operation) } } /// Run given throwing `operation` as part of a new top-level task. /// /// Creating detached tasks should, generally, be avoided in favor of using /// `async` functions, `async let` declarations and `await` expressions - as /// those benefit from structured, bounded concurrency which is easier to reason /// about, as well as automatically inheriting the parent tasks priority, /// task-local storage, deadlines, as well as being cancelled automatically /// when their parent task is cancelled. Detached tasks do not get any of those /// benefits, and thus should only be used when an operation is impossible to /// be modelled with child tasks. /// /// ### Cancellation /// A detached task always runs to completion unless it is explicitly cancelled. /// Specifically, dropping a detached tasks `Task.Handle` does _not_ automatically /// cancel given task. /// /// Cancelling a task must be performed explicitly via `handle.cancel()`. /// /// - Note: it is generally preferable to use child tasks rather than detached /// tasks. Child tasks automatically carry priorities, task-local state, /// deadlines and have other benefits resulting from the structured /// concurrency concepts that they model. Consider using detached tasks only /// when strictly necessary and impossible to model operations otherwise. /// /// - Parameters: /// - priority: priority of the task /// - executor: the executor on which the detached closure should start /// executing on. /// - operation: the operation to execute /// - Returns: handle to the task, allowing to `await handle.get()` on the /// tasks result or `cancel` it. If the operation fails the handle will /// throw the error the operation has thrown when awaited on. @discardableResult @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public func detach<T>( priority: Task.Priority = .unspecified, operation: __owned @Sendable @escaping () async -> T ) -> Task.Handle<T, Never> { // Set up the job flags for a new task. var flags = Task.JobFlags() flags.kind = .task flags.priority = priority flags.isFuture = true // Create the asynchronous task future. let (task, _) = Builtin.createAsyncTaskFuture(flags.bits, operation) // Enqueue the resulting job. _enqueueJobGlobal(Builtin.convertTaskToJob(task)) return Task.Handle<T, Never>(task) } /// Run given throwing `operation` as part of a new top-level task. /// /// Creating detached tasks should, generally, be avoided in favor of using /// `async` functions, `async let` declarations and `await` expressions - as /// those benefit from structured, bounded concurrency which is easier to reason /// about, as well as automatically inheriting the parent tasks priority, /// task-local storage, deadlines, as well as being cancelled automatically /// when their parent task is cancelled. Detached tasks do not get any of those /// benefits, and thus should only be used when an operation is impossible to /// be modelled with child tasks. /// /// ### Cancellation /// A detached task always runs to completion unless it is explicitly cancelled. /// Specifically, dropping a detached tasks `Task.Handle` does _not_ automatically /// cancel given task. /// /// Cancelling a task must be performed explicitly via `handle.cancel()`. /// /// - Note: it is generally preferable to use child tasks rather than detached /// tasks. Child tasks automatically carry priorities, task-local state, /// deadlines and have other benefits resulting from the structured /// concurrency concepts that they model. Consider using detached tasks only /// when strictly necessary and impossible to model operations otherwise. /// /// - Parameters: /// - priority: priority of the task /// - executor: the executor on which the detached closure should start /// executing on. /// - operation: the operation to execute /// - Returns: handle to the task, allowing to `await handle.get()` on the /// tasks result or `cancel` it. If the operation fails the handle will /// throw the error the operation has thrown when awaited on. @discardableResult @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public func detach<T, Failure>( priority: Task.Priority = .unspecified, operation: __owned @Sendable @escaping () async throws -> T ) -> Task.Handle<T, Failure> { // Set up the job flags for a new task. var flags = Task.JobFlags() flags.kind = .task flags.priority = priority flags.isFuture = true // Create the asynchronous task future. let (task, _) = Builtin.createAsyncTaskFuture(flags.bits, operation) // Enqueue the resulting job. _enqueueJobGlobal(Builtin.convertTaskToJob(task)) return Task.Handle<T, Failure>(task) } // ==== Async Handler ---------------------------------------------------------- // TODO: remove this? @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) func _runAsyncHandler(operation: @escaping () async -> ()) { typealias ConcurrentFunctionType = @Sendable () async -> () detach( operation: unsafeBitCast(operation, to: ConcurrentFunctionType.self) ) } // ==== Async Sleep ------------------------------------------------------------ @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// Suspends the current task for _at least_ the given duration /// in nanoseconds. /// /// This function does _not_ block the underlying thread. public static func sleep(_ duration: UInt64) async { // Set up the job flags for a new task. var flags = Task.JobFlags() flags.kind = .task flags.priority = .default flags.isFuture = true // Create the asynchronous task future. let (task, _) = Builtin.createAsyncTaskFuture(flags.bits, {}) // Enqueue the resulting job. _enqueueJobGlobalWithDelay(duration, Builtin.convertTaskToJob(task)) await Handle<Void, Never>(task).get() } } // ==== Voluntary Suspension ----------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { /// Explicitly suspend the current task, potentially giving up execution actor /// of current actor/task, allowing other tasks to execute. /// /// This is not a perfect cure for starvation; /// if the task is the highest-priority task in the system, it might go /// immediately back to executing. public static func yield() async { // Prepare the job flags var flags = JobFlags() flags.kind = .task flags.priority = .default flags.isFuture = true // Create the asynchronous task future, it will do nothing, but simply serves // as a way for us to yield our execution until the executor gets to it and // resumes us. // TODO: consider if it would be useful for this task to be a child task let (task, _) = Builtin.createAsyncTaskFuture(flags.bits, {}) // Enqueue the resulting job. _enqueueJobGlobal(Builtin.convertTaskToJob(task)) let _ = await Handle<Void, Never>(task).get() } } // ==== UnsafeCurrentTask ------------------------------------------------------ @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension Task { @available(*, deprecated, message: "`Task.unsafeCurrent` was replaced by `withUnsafeCurrentTask { task in ... }`, and will be removed soon.") public static var unsafeCurrent: UnsafeCurrentTask? { guard let _task = _getCurrentAsyncTask() else { return nil } // FIXME: This retain seems pretty wrong, however if we don't we WILL crash // with "destroying a task that never completed" in the task's destroy. // How do we solve this properly? _swiftRetain(_task) return UnsafeCurrentTask(_task) } } /// Calls the given closure with the with the "current" task in which this /// function was invoked. /// /// If invoked from an asynchronous function the task will always be non-nil, /// as an asynchronous function is always running within some task. /// However if invoked from a synchronous function the task may be nil, /// meaning that the function is not executing within a task, i.e. there is no /// asynchronous context available in the call stack. /// /// It is generally not safe to escape/store the `UnsafeCurrentTask` for future /// use, as some operations on it may only be performed from the same task /// that it is representing. /// /// It is possible to obtain a `Task` fom the `UnsafeCurrentTask` which is safe /// to access from other tasks or even store for future reference e.g. equality /// checks. @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T { guard let _task = _getCurrentAsyncTask() else { return try body(nil) } // FIXME: This retain seems pretty wrong, however if we don't we WILL crash // with "destroying a task that never completed" in the task's destroy. // How do we solve this properly? _swiftRetain(_task) return try body(UnsafeCurrentTask(_task)) } /// An *unsafe* 'current' task handle. /// /// An `UnsafeCurrentTask` should not be stored for "later" access. /// /// Storing an `UnsafeCurrentTask` has no implication on the task's actual lifecycle. /// /// The sub-set of APIs of `UnsafeCurrentTask` which also exist on `Task` are /// generally safe to be invoked from any task/thread. /// /// All other APIs must not, be called 'from' any other task than the one /// represented by this handle itself. Doing so may result in undefined behavior, /// and most certainly will break invariants in other places of the program /// actively running on this task. @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public struct UnsafeCurrentTask { internal let _task: Builtin.NativeObject // May only be created by the standard library. internal init(_ task: Builtin.NativeObject) { self._task = task } /// Returns `Task` representing the same asynchronous context as this 'UnsafeCurrentTask'. /// /// Operations on `Task` (unlike `UnsafeCurrentTask`) are safe to be called /// from any other task (or thread). public var task: Task { Task(_task) } /// Returns `true` if the task is cancelled, and should stop executing. /// /// - SeeAlso: `checkCancellation()` public var isCancelled: Bool { _taskIsCancelled(_task) } /// Returns the `current` task's priority. /// /// If no current `Task` is available, returns `Priority.default`. /// /// - SeeAlso: `Task.Priority` /// - SeeAlso: `Task.currentPriority` public var priority: Task.Priority { getJobFlags(_task).priority } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension UnsafeCurrentTask: Hashable { public func hash(into hasher: inout Hasher) { UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher) } } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension UnsafeCurrentTask: Equatable { public static func ==(lhs: Self, rhs: Self) -> Bool { UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) == UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task)) } } // ==== Internal --------------------------------------------------------------- @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_getCurrent") func _getCurrentAsyncTask() -> Builtin.NativeObject? @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_getJobFlags") func getJobFlags(_ task: Builtin.NativeObject) -> Task.JobFlags @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_enqueueGlobal") @usableFromInline func _enqueueJobGlobal(_ task: Builtin.Job) @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_enqueueGlobalWithDelay") @usableFromInline func _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job) @available(*, deprecated) @_silgen_name("swift_task_runAndBlockThread") public func runAsyncAndBlock(_ asyncFun: @escaping () async -> ()) @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_asyncMainDrainQueue") public func _asyncMainDrainQueue() -> Never @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public func _runAsyncMain(_ asyncFun: @escaping () async throws -> ()) { #if os(Windows) detach { do { try await asyncFun() exit(0) } catch { _errorInMain(error) } } #else @MainActor @Sendable func _doMain(_ asyncFun: @escaping () async throws -> ()) async { do { try await asyncFun() } catch { _errorInMain(error) } } detach { await _doMain(asyncFun) exit(0) } #endif _asyncMainDrainQueue() } // FIXME: both of these ought to take their arguments _owned so that // we can do a move out of the future in the common case where it's // unreferenced @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_future_wait") public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_future_wait_throwing") public func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) public func _runChildTask<T>( operation: @Sendable @escaping () async throws -> T ) async -> Builtin.NativeObject { let currentTask = Builtin.getCurrentAsyncTask() // Set up the job flags for a new task. var flags = Task.JobFlags() flags.kind = .task flags.priority = getJobFlags(currentTask).priority flags.isFuture = true flags.isChildTask = true // Create the asynchronous task future. let (task, _) = Builtin.createAsyncTaskFuture( flags.bits, operation) // Enqueue the resulting job. _enqueueJobGlobal(Builtin.convertTaskToJob(task)) return task } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_cancel") func _taskCancel(_ task: Builtin.NativeObject) @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_silgen_name("swift_task_isCancelled") func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool #if _runtime(_ObjC) /// Intrinsic used by SILGen to launch a task for bridging a Swift async method /// which was called through its ObjC-exported completion-handler-based API. @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) @_alwaysEmitIntoClient @usableFromInline internal func _runTaskForBridgedAsyncMethod(_ body: @escaping () async -> Void) { // TODO: We can probably do better than detach // if we're already running on behalf of a task, // if the receiver of the method invocation is itself an Actor, or in other // situations. #if compiler(>=5.5) && $Sendable detach { await body() } #endif } #endif
35.401282
143
0.665049
29169a9cac871785c86075e7a9d11476a05944c2
2,449
// // ViewController.swift // DogClassifier // // Created by Noman Ikram on 23/05/2020. // Copyright © 2020 Noman Ikram. All rights reserved. // import UIKit import Vision class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! // UIImageView to display image chosen from cameraroll @IBOutlet weak var breedLabel: UILabel! // UILabel to display the name of the breed let pickerController = UIImagePickerController() var visionModel: VNCoreMLModel? var request: VNCoreMLRequest? let model = Dog_Breeds_Classifier() override func viewDidLoad() { super.viewDidLoad() // initial Setup settingUpCameraRollPicker() } // to process the image to identify the breed of dog func breedLabel(forImage image:UIImage)->String?{ if let imageBuffer = ImageProcessor.pixelBuffer(forImage: image.cgImage!){ guard let breed = try? model.prediction(image: imageBuffer) else { fatalError("Error") } return breed.classLabel } return nil } // pickup image from cameraroll and process @IBAction func chooseImage(_ sender: Any) { pickerController.allowsEditing = false pickerController.sourceType = .photoLibrary present(pickerController, animated: true, completion: nil) } } extension ViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate { func settingUpCameraRollPicker() { pickerController.delegate = self pickerController.allowsEditing = true pickerController.mediaTypes = ["public.image", "public.movie"] pickerController.sourceType = .photoLibrary } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { // image picked up from cameraroll imageView.contentMode = .scaleAspectFit imageView.image = pickedImage // processed and named the breed label of the view self.breedLabel.text = breedLabel(forImage: pickedImage) } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } }
33.094595
101
0.686403
f92aee289f14dd47e9614663389aa5791fe17556
274
// // Selector+.swift // Zavala // // Created by Maurice Parker on 12/31/20. // import UIKit extension Selector { static let cut = #selector(UIResponder.cut(_:)) static let copy = #selector(UIResponder.copy(_:)) static let paste = #selector(UIResponder.paste(_:)) }
18.266667
52
0.686131
113c36c6f1ca46306018dad630c357d2cc5ed335
7,215
// // SettingsViewController.swift // LazyMan-iOS // // Created by Nick Thompson on 4/26/18. // Copyright © 2018 Nick Thompson. All rights reserved. // import UIKit import LazyManCore import OptionSelector protocol SettingsViewType: AnyObject { func showNHLTeams(text: String) func showMLBTeams(text: String) func showNotifications(isOn: Bool) func showDefault(league: League) func showDefault(quality: Quality) func showDefault(cdn: CDN) func showPreferFrench(isOn: Bool) func showGameScores(isOn: Bool) func showVersionUpdates(isOn: Bool) func showBetaUpdates(isOn: Bool, enabled: Bool) func open(url: URL) func show(message: String) } private let kGameSection = 0 private let kFavoriteSection = 1 private let kUpdateSection = 2 private let kFavoriteNHLIndex = 0 private let kFavoriteMLBIndex = 1 private let kCheckUpdateIndex = 2 class SettingsViewController: UITableViewController, SettingsViewType { // MARK: - IBOutlets @IBOutlet private var versionBuildLabel: UILabel! @IBOutlet private var defaultLeagueControl: UISegmentedControl! @IBOutlet private var defaultQualityControl: UISegmentedControl! @IBOutlet private var defaultCDNControl: UISegmentedControl! @IBOutlet private var preferFrenchSwitch: UISwitch! @IBOutlet private var showScoreSwitch: UISwitch! @IBOutlet private var favoriteNHLTeamLabel: UILabel! @IBOutlet private var favoriteMLBTeamLabel: UILabel! @IBOutlet private var notificationsSwitch: UISwitch! @IBOutlet private var versionUpdatesSwitch: UISwitch! @IBOutlet private var betaUpdatesSwitch: UISwitch! @IBOutlet private var betaUpdatesLabel: UILabel! // MARK: - Properties var presenter: SettingsPresenterType? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.presenter?.showDefaults() // Set version and build number let versionString = "Version: \(Bundle.main.releaseVersionNumber) – Build: \(Bundle.main.buildVersionNumber)" self.versionBuildLabel.text = versionString if #available(iOS 13.0, *) { self.overrideUserInterfaceStyle = .dark } } // MARK: - SettingsViewType func showNHLTeams(text: String) { self.favoriteNHLTeamLabel.text = text } func showMLBTeams(text: String) { self.favoriteMLBTeamLabel.text = text } func showNotifications(isOn: Bool) { self.notificationsSwitch.setOn(isOn, animated: true) } func showDefault(league: League) { self.defaultLeagueControl.selectedSegmentIndex = league == .NHL ? 0 : 1 } func showDefault(quality: Quality) { self.defaultQualityControl.selectedSegmentIndex = quality == .auto ? 0 : 1 } func showDefault(cdn: CDN) { self.defaultCDNControl.selectedSegmentIndex = cdn == .akamai ? 0 : 1 } func showPreferFrench(isOn: Bool) { self.preferFrenchSwitch.setOn(isOn, animated: true) } func showGameScores(isOn: Bool) { self.showScoreSwitch.setOn(isOn, animated: true) } func showVersionUpdates(isOn: Bool) { self.versionUpdatesSwitch.setOn(isOn, animated: true) } func showBetaUpdates(isOn: Bool, enabled: Bool) { self.betaUpdatesSwitch.setOn(isOn, animated: true) self.betaUpdatesSwitch.isEnabled = enabled self.betaUpdatesLabel.isEnabled = enabled } func open(url: URL) { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } func show(message: String) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil) alert.addAction(okAction) let atrributedMessage = NSAttributedString(string: message, attributes: [.foregroundColor: UIColor.white]) alert.setValue(atrributedMessage, forKey: "attributedMessage") self.present(alert, animated: true, completion: nil) alert.view.searchVisualEffectsSubview()?.effect = UIBlurEffect(style: .dark) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.section { case kGameSection: return case kFavoriteSection: let viewController: DarkOptionViewController<Team> switch indexPath.row { case kFavoriteNHLIndex: guard let selector = self.presenter?.favoriteNHLTeamSelector else { return } viewController = DarkOptionViewController(selector) case kFavoriteMLBIndex: guard let selector = self.presenter?.favoriteMLBTeamSelector else { return } viewController = DarkOptionViewController(selector) default: return } viewController.popOnSelection = false viewController.title? = "Favorite Teams" self.navigationController?.pushViewController(viewController, animated: true) case kUpdateSection: if indexPath.row == kCheckUpdateIndex { self.presenter?.updatePressed() } default: return } } // MARK: - IBActions @IBAction private func donePressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction private func githubPressed(_ sender: Any) { self.presenter?.githubPressed() } @IBAction private func rLazyManPressed(_ sender: Any) { self.presenter?.rLazyManPressed() } @IBAction private func notificationsPressed(_ sender: Any) { self.presenter?.setNotifications(enabled: self.notificationsSwitch.isOn) } @IBAction private func defaultLeaguePressed(_ sender: Any) { self.presenter?.setDefault(league: self.defaultLeagueControl.selectedSegmentIndex == 0 ? .NHL : .MLB) } @IBAction private func defaultQualityPressed(_ sender: Any) { self.presenter?.setDefault(quality: self.defaultQualityControl.selectedSegmentIndex == 0 ? .auto : .best) } @IBAction private func defaultCDNPressed(_ sender: Any) { self.presenter?.setDefault(cdn: self.defaultCDNControl.selectedSegmentIndex == 0 ? .akamai : .level3) } @IBAction private func preferFrenchPressed(_ sender: Any) { self.presenter?.setPreferFrench(enabled: self.preferFrenchSwitch.isOn) } @IBAction private func showScoresPressed(_ sender: Any) { self.presenter?.setShowScores(enabled: self.showScoreSwitch.isOn) } @IBAction private func versionUpdatesPressed(_ sender: Any) { self.presenter?.setVersionUpdates(enabled: self.versionUpdatesSwitch.isOn) } @IBAction private func betaUpdatesPressed(_ sender: Any) { self.presenter?.setBetaUpdates(enabled: self.betaUpdatesSwitch.isOn) } }
33.09633
117
0.675676
9c0da87e14ab46f0f5f3c27e5dbe6d17619848cb
1,407
// // State.swift // Pods // // Created by happyo on 2018/4/28. // import Foundation public class State<S, A>: Monad { typealias B = Any typealias FA = State<S, A> typealias FB = State<S, B> typealias FF = State<S, (A) -> B> private let state : (S) -> (A, S) public init(_ state : @escaping (S) -> (A, S)) { self.state = state } public func runState() -> (S) -> (A, S) { return self.state } func fmap<B>(_ f: @escaping (A) -> B) -> State<S, State.B> { return State<S, State.B>({ (s) -> (B, S) in let (a, ss) = self.state(s) return (f(a), ss) }) } static func pure(_ a: A) -> State<S, A> { return State<S, A>({ (s) -> (A, S) in (a, s) }) } func apply(_ ff: State<S, (A) -> State.B>) -> State<S, State.B> { return State<S, State.B>({ (s) -> (B, S) in let (a, ss) = self.state(s) let (f, sss) = ff.state(ss) return (f(a), sss) }) } static func returnM(_ a: A) -> State<S, A> { return self.pure(a) } public func flatten<B>(_ f: @escaping (A) -> State<S, B>) -> State<S, B> { return State<S, B>({ (s) -> (B, S) in let (a, ss) = self.state(s) let (k, sss) = f(a).state(ss) return (k, sss) }) } }
23.847458
78
0.436389
e6fc6a06d180340b0aa019a5d488b8e86355b27a
1,196
import UIKit func rounded(radius: CGFloat, corners: RoundedCorner = .all) -> (UIView) -> Void { return { view in view.clipsToBounds = true view.layer.cornerRadius = radius view.layer.maskedCorners = corners.cornerMask } } func background(color: Color, alpha: CGFloat = 1.0) -> (UIView) -> Void { return { view in view.backgroundColor = color.ui(alpha: alpha) } } func bordered(width: CGFloat, color: Color, alpha: CGFloat = 1.0) -> (UIView) -> Void { return { view in view.layer.borderWidth = width view.layer.borderColor = color.cg(alpha: alpha) } } func shadow(color: Color, alpha: CGFloat = 1.0, x: CGFloat = 0.0, y: CGFloat = 0.0, blur: CGFloat = 0.0, spread: CGFloat = 0.0) -> (UIView) -> Void { return { view in let path = UIBezierPath(rect: view.bounds.insetBy(dx: -spread, dy: -spread)) view.layer.shadowColor = color.cg(alpha: alpha) view.layer.shadowOpacity = 1 view.layer.shadowOffset = CGSize(width: x, height: y) view.layer.shadowRadius = blur * 0.5 view.layer.shadowPath = path.cgPath } }
29.9
87
0.594482
c19b1864f9ed0f5558fb4fb3b61a7504fa79eba4
434
class Solution { func rotatedDigits(_ N: Int) -> Int { let invalid: Set<Character> = Set(["3", "4", "7"]) let diff: Set<Character> = Set(["2", "5", "6", "9"]) var res = 0 for i in 1...N { let lookup = Set(Array(String(i))) if lookup.isDisjoint(with: invalid) && !lookup.isDisjoint(with: diff) { res += 1 } } return res } }
24.111111
83
0.453917
f561c720f66790a864c9065c2e13fd6f1fdf0fd7
910
// // XBotBuilderTests.swift // XBotBuilderTests // // Created by Geoffrey Nix on 9/30/14. // Copyright (c) 2014 ModCloth. All rights reserved. // import Cocoa import XCTest class XBotBuilderTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.594595
111
0.618681
ebdb9ce3a3fad50dbc4ed6fa04c83985ed6d1e21
2,739
#if canImport(SwiftUI) import Foundation import SwiftUI /// The size constraint for a snapshot (similar to `PreviewLayout`). public enum SwiftUISnapshotLayout { #if os(iOS) || os(tvOS) /// Center the view in a device container described by`config`. case device(config: ViewImageConfig) #endif /// Center the view in a fixed size container. case fixed(width: CGFloat, height: CGFloat) /// Fit the view to the ideal size that fits its content. case sizeThatFits } #if os(iOS) || os(tvOS) @available(iOS 13.0, tvOS 13.0, *) extension Snapshotting where Value: SwiftUI.View, Format == UIImage { /// A snapshot strategy for comparing SwiftUI Views based on pixel equality. public static var image: Snapshotting { return .image() } /// A snapshot strategy for comparing SwiftUI Views based on pixel equality. /// /// - Parameters: /// - drawHierarchyInKeyWindow: Utilize the simulator's key window in order to render `UIAppearance` and `UIVisualEffect`s. This option requires a host application for your tests and will _not_ work for framework test targets. /// - precision: The percentage of pixels that must match. /// - size: A view size override. /// - traits: A trait collection override. public static func image( drawHierarchyInKeyWindow: Bool = false, precision: Float = 0.98, layout: SwiftUISnapshotLayout = .sizeThatFits, traits: UITraitCollection = .init() ) -> Snapshotting { let config: ViewImageConfig switch layout { #if os(iOS) || os(tvOS) case let .device(config: deviceConfig): config = deviceConfig #endif case .sizeThatFits: config = .init(safeArea: .zero, size: nil, traits: traits) case let .fixed(width: width, height: height): let size = CGSize(width: width, height: height) config = .init(safeArea: .zero, size: size, traits: traits) } return SimplySnapshotting.image(precision: precision, scale: traits.displayScale).asyncPullback { view in var config = config let controller: UIViewController if config.size != nil { controller = UIHostingController.init( rootView: view ) } else { let hostingController = UIHostingController.init(rootView: view) let maxSize = CGSize(width: 0.0, height: 0.0) config.size = hostingController.sizeThatFits(in: maxSize) controller = hostingController } return snapshotView( config: config, drawHierarchyInKeyWindow: drawHierarchyInKeyWindow, traits: traits, view: controller.view, viewController: controller ) } } } #endif #endif
32.607143
230
0.662286
dd456bf5f14958e77de932abfcc3dc3959dc4d68
641
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: %target-swift-frontend %s -emit-ir // Test case submitted to project by https://github.com/tmu (Teemu Kurppa) // rdar://18118173 class a<T : Hashable> { var b = [T : Bool]() init<S : Sequence>(_ c: S) where S.Iterator.Element == T { c.map { self.b[$0] = true } } } a([1])
32.05
79
0.687988
7635c0accd63e5c768aabcf5e329a7b69cf60b68
906
// // CheatCodeSwipeDirection.swift // Cheats // // Created by Ross Butler on 1/16/19. // import Foundation public enum CheatCodeSwipeDirection { // swiftlint:disable:next identifier_name case up case down case left case right } extension CheatCodeSwipeDirection: Equatable { public static func == (lhs: CheatCodeSwipeDirection, rhs: CheatCodeSwipeDirection) -> Bool { switch(lhs, rhs) { case (.up, .up), (.down, .down), (.left, .left), (.right, .right): return true default: return false } } } extension CheatCodeSwipeDirection: CustomStringConvertible { public var description: String { switch self { case .up: return "up" case .down: return "down" case .left: return "left" case .right: return "right" } } }
21.069767
96
0.577263
ac5330a626671a97e01995e0c232ec7b863e6099
4,727
// // TrackDetailViewController.swift // MusiQuiz // // Created by Tim Geldof on 14/12/2019. // Copyright © 2019 Tim Geldof. All rights reserved. // import UIKit import AVFoundation import Toast_Swift class TrackDetailViewController: UIViewController, ReachabilityObserverDelegate { @IBOutlet weak var playButton: UIButton! @IBOutlet weak var albumImage: UIImageView! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var artistNameLabel: UILabel! @IBOutlet weak var songTitleLabel: UILabel! var track : SearchTrackResponse? = nil var player: AVPlayer? = nil override func viewDidLoad() { super.viewDidLoad() updateUI(); NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidAppear(_ animated: Bool) { try! addReachabilityObserver() } func updateUI(){ if let track = track { self.albumImage.kf.indicatorType = .activity self.albumImage.kf.setImage(with: URL(string: track.album.cover_medium)) self.artistNameLabel.text = track.artist.name self.durationLabel.text = track.durationToMinuteString() self.songTitleLabel.text = track.title setUpPlayer(url: track.preview) } } @objc func playerDidFinishPlaying(){ if let player = player { player.seek(to: .zero) playButton.setImage(#imageLiteral(resourceName: "play"), for: UIControl.State.normal) player.pause() } } func setUpPlayer(url: String){ let playerItem = CachingPlayerItem(url: URL(string: url)!) self.player = AVPlayer(playerItem: playerItem) self.player?.volume = 1 } @IBAction func onStopPressed(_ sender: UIButton) { animateButton(sender: sender) if let player = player { player.seek(to: .zero) playButton.setImage(#imageLiteral(resourceName: "play"), for: UIControl.State.normal) if(player.isPlaying){ player.pause() } } } @IBAction func onPlayPressed(_ sender: UIButton) { animateButton(sender: sender) if let player = player { if(!player.isPlaying){ player.play() playButton.setImage(#imageLiteral(resourceName: "pause"), for: UIControl.State.normal) } else { player.pause() playButton.setImage(#imageLiteral(resourceName: "play"), for: UIControl.State.normal) } } } @IBAction func addToFavorites(_ sender: UIButton) { animateButton(sender: sender) DatabaseController.sharedInstance.insertTrack(track: self.track!.toTrackEntity(), completion: { (error) in if(error == nil){ self.view.makeToast("Added/Updated song", duration: 2.0, position: .bottom) } else { self.view.makeToast("Failed to add/update song", duration: 2.0, position: .bottom) } }) } override func viewWillDisappear(_ animated: Bool) { if let player = player { if(player.isPlaying){ player.pause() playButton.setImage(#imageLiteral(resourceName: "play"), for: UIControl.State.normal) } } removeReachabilityObserver() } // SOURCE: https://jgreen3d.com/animate-ios-buttons-touch/ func animateButton(sender : UIButton){ UIButton.animate(withDuration: 0.2, animations: { sender.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }, completion: { finish in UIButton.animate(withDuration: 0.2, animations: { sender.transform = CGAffineTransform.identity }) }) } func reachabilityChanged(_ isReachable: Bool) { if(!isReachable){ self.view.makeToast("No internet available! The song won't be able to play", duration: 2.0, position: .top) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } // SOURCE: https://stackoverflow.com/questions/5655864/check-play-state-of-avplayer extension AVPlayer { var isPlaying: Bool { return rate != 0 && error == nil } }
33.055944
147
0.620478
091dd7e6d7c759b50cbef20470d4a83911082e36
552
// // TodoRepository.swift // Core-CleanSwift-Example // // Created by Robert Nguyen on 9/13/18. // Copyright © 2018 Robert Nguyễn. All rights reserved. // import CoreRepository class TodoRepository: RemoteIdentifiableSingleRepository, RemoteListRepository { typealias T = TodoEntity // let store: TodoDataStore let singleRequest: TodoSingleRequest let listRequest: TodoListRequest init() { // store = TodoDataStore() singleRequest = TodoSingleRequest() listRequest = TodoListRequest() } }
23
80
0.695652
287431b210d5c6de3ba75c003d4534951a24b573
1,624
// // PromotionSectionView.swift // Harrastuspassi // // Created by Eetu Kallio on 20.11.2019. // Copyright © 2019 Haltu. All rights reserved. // import UIKit @IBDesignable class PromotionSectionView: UIView { let nibName = "PromotionSectionView" var hobbies: [HobbyData] = [] required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit() { guard let view = loadViewFromNib() else { return } view.frame = self.bounds self.addSubview(view) var subViews:[PromotionVerticalCell] = []; let cell: PromotionVerticalCell = PromotionVerticalCell(frame: CGRect(x: 0, y: 0, width: 200, height: 400)); cell.heightAnchor.constraint(equalToConstant: 400).isActive = true; cell.widthAnchor.constraint(equalToConstant: 200).isActive = true; subViews.append(cell) let cell2: PromotionVerticalCell = PromotionVerticalCell(frame: CGRect(x: 0, y: 0, width: 200, height: 400)); cell.heightAnchor.constraint(equalToConstant: 400).isActive = true; cell.widthAnchor.constraint(equalToConstant: 200).isActive = true; subViews.append(cell2) for view in subViews { contentView.addSubview(view); } } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as? UIView } }
33.142857
117
0.647783
0eded2cff6f47209f5023c586ff95a18359202ad
1,109
// // WQUIHelp.swift // Pods // // Created by WangQiang on 2019/1/14. // import Foundation final public class WQUIHelp { public class func topNormalWindow() -> UIWindow? { let app = UIApplication.shared #if targetEnvironment(macCatalyst) var topWindow = UIApplication.shared.windows.last #else var topWindow = UIApplication.shared.keyWindow #endif topWindow = topWindow ?? app.delegate?.window ?? app.windows.last(where: { $0.windowLevel == .normal }) return topWindow } public class func topVisibleViewController() -> UIViewController? { return topNormalWindow()?.rootViewController?.topVisible() } public class func topNavigationController() -> UINavigationController? { return topNormalWindow()?.rootViewController?.topNavigationController() } } public func wm_topNavigationController() -> UINavigationController? { return WQUIHelp.topNavigationController() } public func wm_topVisibleViewController() -> UIViewController? { return WQUIHelp.topVisibleViewController() }
28.435897
111
0.691614
e9c4072b613144d3b555a4304e98e50c7e241e2d
4,875
// // TagCollectionViewCell.swift // MovieTV // // Created by ZeroGravity on 1/27/21. // Copyright © 2021 ZeroGravity. All rights reserved. // import UIKit protocol TagCollectionViewCellDelegate: AnyObject { func handleTagSelection(for cell: UICollectionViewCell) } class TagCollectionViewCell: UICollectionViewCell, NibableCellProtocol { static let tagNameFont: UIFont = UIFont.h4_strong!.withSize(16) let statusHorizontalShapeLayer: CAShapeLayer = { let shape = CAShapeLayer() let path = UIBezierPath(roundedRect: .init(x: 3, y: 7, width: 10, height: 2), cornerRadius: 1) shape.path = path.cgPath shape.frame = .init(x: 0, y: 0, width: 16, height: 16) shape.fillColor = UIColor(named: "C75")?.cgColor return shape }() let statusVerticalShapeLayer: CAShapeLayer = { let shape = CAShapeLayer() let path = UIBezierPath(roundedRect: .init(x: 7, y: 3, width: 2, height: 10), cornerRadius: 1) shape.path = path.cgPath shape.frame = .init(x: 0, y: 0, width: 16, height: 16) shape.fillColor = UIColor(named: "C75")?.cgColor return shape }() var data: GenreModel! { didSet { tagNameLbl.text = data.name setSelect(data.isSelected == true, isAnimate: false) } } weak var delegate: TagCollectionViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() initial() } private func initial() { clipsToBounds = false setUpTagView() setUpStatusSignView() } private func setUpTagView() { actionBtn.specificAnimateView = tagContainerView tagNameLbl.textColor = UIColor(named: "C75") tagNameLbl.font = Self.tagNameFont tagContainerView.layer.cornerRadius = 34 / 2 tagContainerView.layer.borderWidth = 2 tagContainerView.layer.borderColor = UIColor.black.withAlphaComponent(0.1).cgColor } private func setUpStatusSignView() { statusSignView.isUserInteractionEnabled = false statusSignView.layer.cornerRadius = 8 statusSignView.layer.shadowPath = nil statusSignView.layer.shadowOffset = .zero statusSignView.layer.shadowRadius = 2 statusSignView.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.08).cgColor statusSignView.layer.shadowOpacity = 1 statusSignView.layer.addSublayer(statusHorizontalShapeLayer) statusSignView.layer.addSublayer(statusVerticalShapeLayer) } @IBAction func clickedActionBtn(_ sender: Any) { handleClickedActionBtn() } private func handleClickedActionBtn() { delegate?.handleTagSelection(for: self) data?.isSelected.toggle() setSelect(data?.isSelected == true) } func setSelect(_ value: Bool, isAnimate: Bool = true) { let animation = { self.tagContainerView.backgroundColor = value ? UIColor(named: "C75") : .white self.tagNameLbl.textColor = value ? .white : UIColor(named: "C75") } animateStatusView(forSelection: value, isAnimate: isAnimate) guard isAnimate else { animation() return } UIView.transition(with: tagContainerView, duration: 0.3, options: .transitionCrossDissolve) { animation() } } private func animateStatusView(forSelection value: Bool, isAnimate: Bool) { statusVerticalShapeLayer.removeAllAnimations() let anim = CABasicAnimation(keyPath: "transform.rotation") anim.duration = isAnimate ? 0 : 0.3 if isAnimate { anim.fromValue = value ? 0 : CGFloat.pi / 4 } anim.toValue = value ? CGFloat.pi / 4 : 0 anim.fillMode = .both anim.isRemovedOnCompletion = false statusSignView.layer.add(anim, forKey: "rotation") let colorChangeAnim = CABasicAnimation(keyPath: "fillColor") colorChangeAnim.duration = isAnimate ? 0 : 0.3 if isAnimate { colorChangeAnim.fromValue = value ? UIColor(named: "C75")?.cgColor : UIColor(named: "R100")?.cgColor } colorChangeAnim.toValue = value ? UIColor(named: "R100")?.cgColor : UIColor(named: "C75")?.cgColor colorChangeAnim.isRemovedOnCompletion = false colorChangeAnim.fillMode = .forwards statusVerticalShapeLayer.add(colorChangeAnim, forKey: "colorChanging") statusHorizontalShapeLayer.add(colorChangeAnim, forKey: "colorChanging") } @IBOutlet weak var tagNameLbl: UILabel! @IBOutlet weak var tagContainerView: UIView! @IBOutlet weak var actionBtn: MovieTVButton! @IBOutlet weak var statusSignView: UIView! }
34.821429
112
0.638154
112d91895b86c2fd1414629e5cf0988fc3270566
1,258
// // PageLayout.swift // MusicXML // // Created by James Bean on 5/28/19. // /// Page layout can be defined both in score-wide defaults and in the print element. Page margins /// are specified either for both even and odd pages, or via separate odd and even page number /// values. The type is not needed when used as part of a print element. If omitted when used in the /// defaults element, "both" is the default. public struct PageLayout { // MARK: - Instance Properties // MARK: Elements public let height: Double? public let width: Double? public let margins: [PageMargins] // MARK: - Initializers public init(height: Double? = nil, width: Double? = nil, margins: [PageMargins] = []) { self.height = height self.width = width self.margins = margins } } extension PageLayout: Equatable {} extension PageLayout: Codable { // MARK: - Codable private enum CodingKeys: String, CodingKey { case height = "page-height" case width = "page-width" case margins = "page-margins" } } import XMLCoder extension PageLayout: DynamicNodeEncoding { public static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding { return .element } }
26.765957
100
0.666932
dd050b18078a09d122f5d045d36f1585a5aba173
417
import XCTest @testable import Avenues_Shallows class Avenues_ShallowsTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. XCTAssertEqual(Avenues_Shallows().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
26.0625
96
0.681055
bb26785a0c8bb041d954b90a8d659a774ce9be91
517
// // UserActiveExtensionsRequest.swift // TwitchAPIWrapper // // Created by Eric Vennaro on 5/23/21. // import Foundation ///Get user active extension request see https://dev.twitch.tv/docs/api/reference/#get-user-active-extensions public struct UserActiveExtensionsRequest: JSONConstructableRequest { public let url: URL? public init(userID: String? = nil) { self.url = TwitchEndpoints.userActiveExtensions.construct()?.appending(queryItems: ["user_id": userID].buildQueryItems()) } }
28.722222
129
0.733075
615108dc4e51e5ca4785c38b3c90984582795008
1,836
// // AboutViewController.swift // Covid-19 Status // // Created by Marcin Gajda on 25/03/2020. // Copyright © 2020 Marcin Gajda. All rights reserved. // import Cocoa import Foundation class AboutViewController: NSViewController { @IBOutlet weak var sourceLink: NSTextField? @IBOutlet weak var version: NSTextField? override func viewDidLoad() { super.viewDidLoad() guard let version = version else { ErrorHandler.standard.critical(withMessage: "The app UI is broken (version)") return } guard let sourceLink = sourceLink else { ErrorHandler.standard.critical(withMessage: "The app UI is broken (source link)") return } let versionNumber = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) version.stringValue = String( format: NSLocalizedString("version %@", comment: ""), versionNumber ?? "??" ) let sourceClickHandler = NSClickGestureRecognizer( target: self, action: #selector(self.sourceLinkHandler(sender:)) ) sourceLink.addGestureRecognizer(sourceClickHandler) NSApplication.shared.activate(ignoringOtherApps: true) } @IBAction func sourceLinkHandler(sender: NSClickGestureRecognizer) { guard let link = sourceLink?.stringValue else { ErrorHandler.standard.critical(withMessage: "Can't open the URL address.") return } guard let urlAddress = URL(string: link) else { ErrorHandler.standard.critical(withMessage: "Can't open the URL address.") return } NSWorkspace.shared.open(urlAddress) } @IBAction func dismissAboutWindow(_ sender: NSButton) { view.window?.close() } }
28.6875
98
0.639434
036bdefe61f003d57fa31a722fb1e9cd1933069d
1,052
// // Copyright (c) 2018 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation class OpenInvoiceFormSection: FormSection { // MARK: - Internal override func addFormElement(_ element: UIView) { guard elements.contains(element) == false else { return } elements.append(element) super.addFormElement(element) } func isValid() -> Bool { var valid = true elements.forEach { subview in if let formTextField = subview as? FormTextField, formTextField.validatedValue == nil { valid = valid && false } else if let formPickerField = subview as? FormPickerField, formPickerField.selectedValue == nil { valid = valid && false } } return valid || isHidden } // MARK: - Private // Keep track of added elements for validation purposes private var elements: [UIView] = [] }
26.974359
111
0.593156
5680e4997445c9f723ff579224481f109e2b26b1
319
//___FILEHEADER___ import Cocoa class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaSubclass___ { override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } }
22.785714
134
0.739812
1cc248750f4d5e21be202add16f42b90739010f9
1,860
// // GPXPerson.swift // GPXKit // // Created by Vincent on 18/11/18. // import Foundation /// A value type that is designated to hold information regarding the person or organisation who has created the GPX file. public class GPXPerson: GPXElement, Codable { /// Name of person who has created the GPX file. public var name: String? /// The email address of the person who has created the GPX file. public var email: GPXEmail? /// An external website that holds information on the person who has created the GPX file. Additional information may be supported as well. public var link: GPXLink? // MARK:- Initializers // Default Initializer. public required init() { super.init() } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { for child in raw.children { switch child.name { case "name": self.name = child.text case "email": self.email = GPXEmail(raw: child) case "link": self.link = GPXLink(raw: child) default: continue } } } // MARK:- Tag override func tagName() -> String { return "person" } // MARK:- GPX override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forValue: name, gpx: gpx, tagName: "name", indentationLevel: indentationLevel) if email != nil { self.email?.gpx(gpx, indentationLevel: indentationLevel) } if link != nil { self.link?.gpx(gpx, indentationLevel: indentationLevel) } } }
27.761194
143
0.597312
0869c9fe461a0c1265ac1d5a01e5bb5056000467
1,740
//: [Previous](@previous) [Homepage](Homepage) import CodableWrapper /*: # 支持多个 Key 映射到同一个属性 > 业务迭代中, 功能有交集的多个接口可能会复用同一个数据模型. 由于种种原因, 不同接口中相同字段使用了不同的 key, 端上只能兼容多个 key --- */ //: ## Native Codable struct User: Codable { var vip: Bool = false enum CodingKeys: String, CodingKey { case vip = "vip_user" } } example("Native.1: 另一个接口返回类似模型, key 不同, 无法解析❌") { let api1 = #" { "vip_user": true } "# let api2 = #" { "is_vip": true } "# for (i, api) in [api1, api2].enumerated() { do { let user = try User.decode(from: api) print("user\(i+1):", user) } catch { print("user\(i+1):", error) } } } /*: ## Codec */ struct CodecUser: Codable { @Codec("is_vip", "vip_user") var vip: Bool = false } example("Codec.1: 多个 key 可同时映射到一个属性, 解析成功✅") { let api1 = #" { "vip":true } "# let api2 = #" { "is_vip":true } "# let api3 = #" { "vip_user":true } "# for (i, api) in [api1, api2, api3].enumerated() { do { let user = try CodecUser.decode(from: api) print("user\(i+1):", user) } catch { print(error) } } } //: `Support DecodingKeyStrategy` struct CodecAutoConvertUser: Codable { @Codec("vipUser", "user_vip") var isVip: Bool = false } example("Codec.2: 驼峰下划线自动转换✅") { let api1 = #" { "is_vip":true } "# let api2 = #" { "vip_user":true } "# let api3 = #" { "userVip":true } "# for (i, api) in [api1, api2, api3].enumerated() { do { let user = try CodecAutoConvertUser.decode(from: api) print("user\(i+1):", user) } catch { print(error) } } } //: [Next](@next)
22.894737
75
0.51954
5b07ddcb8abca7999dacb49180ed2a76860592ca
498
import UIKit protocol ZoomAnimatable: class { func zoomAnimatorAnimationWillBegin(_ animator: ZoomAnimator) func zoomAnimatorImage(_ animator: ZoomAnimator) -> UIImage? func zoomAnimator(_ animator: ZoomAnimator, imageFrameInView view: UIView) -> CGRect? func zoomAnimatorAnimationDidEnd(_ animator: ZoomAnimator) } extension ZoomAnimatable { func zoomAnimatorAnimationWillBegin(_ animator: ZoomAnimator) {} func zoomAnimatorAnimationDidEnd(_ animator: ZoomAnimator) {} }
35.571429
89
0.789157
1483941845e8cee4e35a6e287cce96a0f722af3a
7,404
// // SurveyIDViewController.swift // Voice Capture Utility // // Created by Jia Rui Shan on 2019/5/6. // Copyright © 2019 UC Berkeley. All rights reserved. // import UIKit import SwiftyJSON import SurveyLex class SurveyIDViewController: UIViewController, SurveyResponseDelegate { private var lookupButton: UIButton! private var textView: UITextView! private var accessoryView: UIView! override func viewDidLoad() { super.viewDidLoad() title = "SurveyLex Demo" accessoryView = makeAccessoryView() // 1 textView = makeTextView() // 2 lookupButton = makeLookupButton() // 3 // Tribe 4 application // textView.text = "16261720-43fe-11e9-8a24-cd4ab4d0c054" // Post day diary // textView.text = "41e8abf0-62b9-11e9-a454-f5b21638e785" // Music survey // textView.text = "5f108ef0-5d23-11e9-8d7e-bb5f7e5229ff" // Custom (everything in one survey) // textView.text = "b1d9d390-9b5c-11e9-a279-9f8e317e3dcc" // Comprehensive test // textView.text = "cc3330f0-a332-11e9-81d0-29f9b1295ce4" // Response test textView.text = "a198a1d0-a89c-11e9-b466-e38db5a54ad8" // Voiceome Survey A // textView.text = "c741cba0-acca-11e9-aeb9-2b1c6d8db2a2" // Voiceome Survey B // textView.text = "ec001370-acca-11e9-aeb9-2b1c6d8db2a2" // Voiceome Survey C // textView.text = "f43cfe40-acca-11e9-aeb9-2b1c6d8db2a2" // Voiceome Survey D // textView.text = "fd781f30-acca-11e9-aeb9-2b1c6d8db2a2" } /// Make keyboard accessory view private func makeAccessoryView() -> UIView { let button = UIButton(type: .system) button.setTitle("Done", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.addTarget(self, action: #selector(dismissKeyboard), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false let signButton = UIButton(type: .system) signButton.setTitle("–", for: .normal) signButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) signButton.addTarget(self, action: #selector(dash), for: .touchUpInside) signButton.translatesAutoresizingMaskIntoConstraints = false let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 45)) view.layer.borderWidth = 1 view.layer.borderColor = UIColor(white: 0.92, alpha: 1).cgColor view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) view.addSubview(signButton) view.backgroundColor = UIColor(white: 0.95, alpha: 0.9) NSLayoutConstraint.activate([ button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20), button.centerYAnchor.constraint(equalTo: view.centerYAnchor), signButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), signButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), signButton.widthAnchor.constraint(equalToConstant: 30) ]) return view } /// Make a text view! private func makeTextView() -> UITextView { let txv = UITextView() txv.layer.borderColor = UIColor(white: 0.93, alpha: 1).cgColor txv.textContainerInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) txv.font = UIFont.systemFont(ofSize: 24) txv.allowsEditingTextAttributes = false txv.textColor = UIColor(white: 0.1, alpha: 1) txv.autocapitalizationType = .none txv.keyboardType = .asciiCapable txv.textAlignment = .center txv.autocorrectionType = .no txv.layer.borderWidth = 1 txv.layer.cornerRadius = 8 txv.inputAccessoryView = accessoryView txv.translatesAutoresizingMaskIntoConstraints = false view.addSubview(txv) // Layout constraints txv.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true txv.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true txv.heightAnchor.constraint(equalToConstant: 120).isActive = true txv.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor, constant: -25).isActive = true return txv } /// Make a customized-looking button! private func makeLookupButton() -> UIButton { let button = UIButton(type: .system) button.setTitle("Launch Survey", for: .normal) button.layer.cornerRadius = 24 button.tintColor = BUTTON_DEEP_BLUE button.layer.borderWidth = 1 button.layer.borderColor = BUTTON_TINT.cgColor button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) button.widthAnchor.constraint(equalToConstant: 160).isActive = true button.heightAnchor.constraint(equalToConstant: 48).isActive = true button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true button.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 20).isActive = true button.addTarget(self, action: #selector(lookup(_:)), for: .touchUpInside) return button } @objc private func dismissKeyboard() { textView.endEditing(true) } @objc private func dash() { textView.insertText("-") } @objc func lookup(_ sender: UIButton) { let survey: Survey if textView.text.contains("{") { survey = try! Survey(json: JSON(parseJSON: textView.text), target: self) } else { survey = Survey(surveyID: textView.text, target: self) } // Survey configuration survey.allowMenuCollapse = true survey.delegate = self survey.mode = .submission // survey.theme = .purple survey.load() sender.isEnabled = false sender.setTitle("Loading...", for: .normal) } // MARK: Delegate methods // Some protocol methods have default implementation, so be sure to check the documentation func surveyDidLoad(_ survey: Survey) { survey.present() } func surveyDidPresent(_ survey: Survey) { lookupButton.isEnabled = true lookupButton.setTitle("Launch Survey", for: .normal) } func surveyFailedToPresent(_ survey: Survey, error: Survey.Error) { lookupButton.isEnabled = true lookupButton.setTitle("Lookup Survey", for: .normal) } } /* extension UITextView { /// Center the text vertically within the container. override open var contentSize: CGSize { didSet { var topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0 topCorrection = max(0, topCorrection) contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0) } } } */
35.090047
95
0.61953
7936f791e7294318670b6a6cf9729607f7435f18
3,112
// // Calvette.swift // Hydra2.0 // // Created by Simon Desrochers on 2020-11-27. // import UIKit class Calvette: ObservableObject, Codable { @Published var temperature1: Float @Published var humidity1: Float @Published var humidityLowerTreshold1: Float @Published var humidityUpperTreshold1: Float @Published var temperature2: Float @Published var humidity2: Float @Published var humidityLowerTreshold2: Float @Published var humidityUpperTreshold2: Float @Published var temperature3: Float @Published var humidity3: Float @Published var humidityLowerTreshold3: Float @Published var humidityUpperTreshold3: Float enum CodingKeys : CodingKey{ case temperature1, humidity1, humidityLowerTreshold1, humidityUpperTreshold1, temperature2, humidity2, humidityLowerTreshold2, humidityUpperTreshold2, temperature3, humidity3, humidityLowerTreshold3, humidityUpperTreshold3 } init() { temperature1 = 25.0 humidity1 = 85.0 humidityLowerTreshold1 = 85.0 humidityUpperTreshold1 = 95.0 temperature2 = 25.0 humidity2 = 85.0 humidityLowerTreshold2 = 85.0 humidityUpperTreshold2 = 95.0 temperature3 = 25.0 humidity3 = 85.0 humidityLowerTreshold3 = 85.0 humidityUpperTreshold3 = 95.0 } func encode(to encoder: Encoder) throws { /*var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(temp, forKey: .temp) try container.encode(humidity, forKey: .humidity)*/ } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) temperature1 = try container.decode(Float.self, forKey: .temperature1) humidity1 = try container.decode(Float.self, forKey: .humidity1) humidityLowerTreshold1 = try container.decode(Float.self, forKey: .humidityLowerTreshold1) humidityUpperTreshold1 = try container.decode(Float.self, forKey: .humidityUpperTreshold1) temperature2 = try container.decode(Float.self, forKey: .temperature2) humidity2 = try container.decode(Float.self, forKey: .humidity2) humidityLowerTreshold2 = try container.decode(Float.self, forKey: .humidityLowerTreshold2) humidityUpperTreshold2 = try container.decode(Float.self, forKey: .humidityUpperTreshold2) temperature3 = try container.decode(Float.self, forKey: .temperature3) humidity3 = try container.decode(Float.self, forKey: .humidity3) humidityLowerTreshold3 = try container.decode(Float.self, forKey: .humidityLowerTreshold3) humidityUpperTreshold3 = try container.decode(Float.self, forKey: .humidityUpperTreshold3) } }
28.036036
230
0.637532
fb8be5b185383a4dbbad6ed2f15cf77754f7f303
303
// // ProViewApp.swift // ProView // // Created by Patrik Duksin on 2021-05-09. // import SwiftUI @main struct ProViewApp: App { @StateObject var viewRouter = ViewRouter() var body: some Scene { WindowGroup { MotherView().environmentObject(viewRouter) } } }
15.947368
54
0.617162
1c67bfddff1c722d0363bfe26375fe42b0151794
6,022
import Foundation #if canImport(Combine) import Combine #else import OpenCombine import OpenCombineDispatch import OpenCombineFoundation #endif import SpotifyWebAPI import SpotifyExampleContent /** Ensure that the examples in the README compile. These methods should not be called. This class is intentionally **NOT** a subclass of `XCTestCase`. For example, if a symbol was renamed, then this file would fail to compile, serving as a warning that the documentation needs to be updated to reflect the changes. */ private class READMEExamplesCompilationTests { private var cancellables: Set<AnyCancellable> = [] func testDocsAuthorizationCodeFlowPKCE() { let spotify = SpotifyAPI( authorizationManager: AuthorizationCodeFlowPKCEManager( clientId: "Your Client Id" ) ) let codeVerifier = String.randomURLSafe(length: 128) let codeChallenge = String.makeCodeChallenge(codeVerifier: codeVerifier) let state = String.randomURLSafe(length: 128) let authorizationURL = spotify.authorizationManager.makeAuthorizationURL( redirectURI: URL(string: "Your Redirect URI")!, codeChallenge: codeChallenge, state: state, scopes: [ .playlistModifyPrivate, .userModifyPlaybackState, .playlistReadCollaborative, .userReadPlaybackPosition ] )! _ = authorizationURL let url = URL(string: "redirectURIWithQuery")! spotify.authorizationManager.requestAccessAndRefreshTokens( redirectURIWithQuery: url, // Must match the code verifier that was used to generate the // code challenge when creating the authorization URL. codeVerifier: codeVerifier, // Must match the value used when creating the authorization URL. state: state ) .sink(receiveCompletion: { completion in switch completion { case .finished: print("successfully authorized") case .failure(let error): if let authError = error as? SpotifyAuthorizationError, authError.accessWasDenied { print("The user denied the authorization request") } else { print("couldn't authorize application: \(error)") } } }) .store(in: &cancellables) let playbackRequest = PlaybackRequest( context: .uris( URIs.Tracks.array(.faces, .illWind, .fearless) ), offset: .uri(URIs.Tracks.fearless), positionMS: 50_000 ) spotify.play(playbackRequest) .sink(receiveCompletion: { completion in print(completion) }) .store(in: &cancellables) } func testDocsAuthorizationCodeFlow() { let spotify = SpotifyAPI( authorizationManager: AuthorizationCodeFlowManager( clientId: "Your Client Id", clientSecret: "Your Client Secret" ) ) let authorizationURL = spotify.authorizationManager.makeAuthorizationURL( redirectURI: URL(string: "YourRedirectURI")!, showDialog: false, scopes: [ .playlistModifyPrivate, .userModifyPlaybackState, .playlistReadCollaborative, .userReadPlaybackPosition ] )! _ = authorizationURL let url = URL(string: "redirectURIWithQuery")! spotify.authorizationManager.requestAccessAndRefreshTokens( redirectURIWithQuery: url ) .sink(receiveCompletion: { completion in switch completion { case .finished: print("successfully authorized") break case .failure(let error): if let authError = error as? SpotifyAuthorizationError, authError.accessWasDenied { print("The user denied the authorization request") } else { print("couldn't authorize application: \(error)") } } }) .store(in: &cancellables) spotify.currentUserPlaylists() .extendPages(spotify) .sink( receiveCompletion: { completion in print(completion) }, receiveValue: { results in print(results) } ) .store(in: &cancellables) } func testDocsClientCredentialsCodeFlow() { let spotify = SpotifyAPI( authorizationManager: ClientCredentialsFlowManager( clientId: "Your Client Id", clientSecret: "Your Client Secret" ) ) spotify.authorizationManager.authorize() .sink(receiveCompletion: { completion in switch completion { case .finished: print("successfully authorized application") case .failure(let error): print("could not authorize application: \(error)") } }) .store(in: &cancellables) spotify.search(query: "Pink Floyd", categories: [.track]) .sink( receiveCompletion: { completion in print(completion) }, receiveValue: { results in print(results) } ) .store(in: &cancellables) } }
32.551351
81
0.537529
b9bee4cc582f68c0568a8c51b4b6c9ca17c673cd
2,331
// // AudioPlayerProtocol.swift // SoundScape // // Created by Astrid on 2021/11/24. // import Foundation import UIKit protocol AudioPlayerProtocol: AnyObject { // UI var playButton: UIButton { get } var progressView: UIView { get } var caDisplayLink: CADisplayLink? { get set } var playButtonImagePlay: UIImage? { get } // default var playButtonImagePause: UIImage? { get } // default // method func togglePlayer() // default func changeButtonImage() // default func updatePlaybackTime(notification: Notification) // default } // MARK: - default setting extension AudioPlayerProtocol { // model var audioPlayHelper: AudioPlayHelper { return AudioPlayHelper.shared } // UI var playButtonImagePlay: UIImage? { UIImage(systemName: CommonUsage.SFSymbol.play) } var playButtonImagePause: UIImage? { UIImage(systemName: CommonUsage.SFSymbol.pause) } // method func togglePlayer() { if audioPlayHelper.isPlaying { audioPlayHelper.pause() } else { audioPlayHelper.play() } } func updatePlaybackTime(notification: Notification) { guard let playProgress = notification.userInfo?["UserInfo"] as? PlayProgress else { return } let currentTime = playProgress.currentTime let duration = playProgress.duration let timeProgress = currentTime / duration updateProgressWaveform(timeProgress) } func updateProgressWaveform(_ progress: Double) { let fullRect = progressView.bounds let newWidth = Double(fullRect.size.width) * progress let maskLayer = CAShapeLayer() let maskRect = CGRect(x: 0.0, y: 0.0, width: newWidth, height: Double(fullRect.size.height)) let path = CGPath(rect: maskRect, transform: nil) maskLayer.path = path progressView.layer.mask = maskLayer } func changeButtonImage() { DispatchQueue.main.async { self.playButton.isHidden = false let image = self.audioPlayHelper.isPlaying ? self.playButtonImagePause : self.playButtonImagePlay self.playButton.setImage(image, for: .normal) } } }
25.336957
109
0.630202
5b672bd3a1e758dec52f3e98a3e33fe3fd368785
596
// // SingletonTests.swift // DesignPatterns // // Created by Alex Salom on 09/11/15. // Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved. // import XCTest @testable import DesignPatterns class SingletonTests: XCTestCase { func testSingletonA() { XCTAssertTrue(SingletonA.sharedInstance === SingletonA.sharedInstance) } func testSingletonB() { XCTAssertTrue(SingletonB.sharedInstance === SingletonB.sharedInstance) } func testSingletonC() { XCTAssertTrue(SingletonC.sharedInstance === SingletonC.sharedInstance) } }
22.923077
78
0.696309
e257bb823727bf993cc3db207f49f5a53f678226
1,670
// // ThemeFontStyle.swift // ThemeManager // // Created by Giuseppe Lanza on 14/11/2019. // Copyright © 2019 MERLin Tech. All rights reserved. // public enum ThemeFontAttribute: CaseIterable { case regular, bold, sBold, italic } public enum ThemeFontStyle: CaseIterable { case small(attribute: ThemeFontAttribute) case caption(attribute: ThemeFontAttribute) case subhead(attribute: ThemeFontAttribute) case body(attribute: ThemeFontAttribute) case headline(attribute: ThemeFontAttribute) case title(attribute: ThemeFontAttribute) case display(attribute: ThemeFontAttribute) case displayBig(attribute: ThemeFontAttribute) public var attribute: ThemeFontAttribute { switch self { case let .small(attribute): return attribute case let .caption(attribute): return attribute case let .subhead(attribute): return attribute case let .body(attribute): return attribute case let .headline(attribute): return attribute case let .title(attribute): return attribute case let .display(attribute): return attribute case let .displayBig(attribute): return attribute } } public static var allCases: [ThemeFontStyle] { return ThemeFontAttribute.allCases.flatMap { [ .small(attribute: $0), .caption(attribute: $0), .subhead(attribute: $0), .body(attribute: $0), .headline(attribute: $0), .title(attribute: $0), .display(attribute: $0), .displayBig(attribute: $0) ] } } }
32.745098
57
0.635928
7943b2f67762256c5094fe76827d5bf33dedbf4a
2,262
// // NMOutlineViewController.swift // OutlineView // // Created by on 12/3/19. // Copyright © 2019 Netmedia. All rights reserved. // import UIKit @objc(NMOutlineViewController) @IBDesignable @objcMembers open class NMOutlineViewController: UIViewController { @IBOutlet @objc dynamic open var outlineView: NMOutlineView! @objc open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.view = NMOutlineView(frame: UIScreen.main.bounds, style: .plain) } open override func viewDidLoad() { super.viewDidLoad() self.outlineView?.datasource = self } } @objc extension NMOutlineViewController: NMOutlineViewDatasource { @objc open func outlineView(_ outlineView: NMOutlineView, numberOfChildrenOfItem item: Any?) -> Int { fatalError("NMOutlineViewDatasource Protocol method method numberOfChildrenOfItem must be imoplemented") } @objc open func outlineView(_ outlineView: NMOutlineView, isItemExpandable item: Any) -> Bool { fatalError("NMOutlineViewDatasource Protocol method method isItemExpandable must be imoplemented") } @objc open func outlineView(_ outlineView: NMOutlineView, cellFor item: Any) -> NMOutlineViewCell { fatalError("NMOutlineViewDatasource Protocol method method outlineView(_: NMOutlineView, cellFor: Any) -> NMOutlineViewCell must be imoplemented") } @objc open func outlineView(_ outlineView: NMOutlineView, child index: Int, ofItem item: Any?) -> Any { fatalError("NMOutlineViewDatasource Protocol method outlineView(_: NMOutlineView, child: Int, ofItem: Any?) -> Any must be implemented") } @objc open func outlineView(_ outlineView: NMOutlineView, didSelect cell: NMOutlineViewCell) { fatalError("NMOutlineViewDatasource Protocol method method outlineView(_: NMOutlineView, didSelect: NMOutlineViewCell) must be imoplemented") } @objc open func outlineView(_ outlineView: NMOutlineView, shouldExpandItem item: Any) -> Bool { fatalError("NMOutlineViewDatasource Protocol method method outlineView(_: NMOutlineView, shouldExpandItem: Any) -> Bool must be imoplemented") } }
35.34375
154
0.721043
eb36461261f79e9d1142cdd9068b3ee729e7890f
1,263
// // Lyrics3FieldType.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 Foundation public enum Lyrics3FieldType { case native case custom }
39.46875
81
0.748219
508ef315a159ca1de08c36982ec55e0430c89d72
1,422
// // PhotoEditor+Keyboard.swift // Pods // // Created by Mohamed Hamed on 6/16/17. // // import Foundation import UIKit extension PhotoEditorViewController { @objc func keyboardWillChangeFrame(_ notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw) if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height { self.colorPickerViewBottomConstraint?.constant = 0.0 } else { self.colorPickerViewBottomConstraint?.constant = endFrame?.size.height ?? 0.0 } UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } } }
40.628571
131
0.649086
09cea4717b40a0b8e49798d68560f67173ca015c
1,860
import XCTest @testable import RemoteConfigSwiftUI final class RemoteConfigSwiftUITests: XCTestCase { let textRawJson = "{ \"value\": \"Text value\"}" let decoder = JSONDecoder() func testText() { let value = try! decoder.decode(ConfigText.self, from: textRawJson.data(using: .utf8)!) print(value) } func testHStack() { let rawJson = "{ \"spacing\": 10, \"value\": \(textRawJson) }" let data = rawJson.data(using: .utf8)! let output = try! decoder.decode(ConfigHStack.self, from: data) print(output) } func testColor() { let colorInHex = "#ff00ff" let config = ConfigColor(hex: colorInHex) XCTAssertNotNil(config) XCTAssertEqual(config?.red, 255) XCTAssertEqual(config?.green, 0) XCTAssertEqual(config?.blue, 255) let config2: ConfigColor = "#ffff00" XCTAssertEqual(config2.red, 255) XCTAssertEqual(config2.green, 255) XCTAssertEqual(config2.blue, 0) let rawJson = "{\n\"color\":\"#0000ff\",\"color2\": { \"red\": 255, \"blue\":200,\"green\":100 } }" struct Test: Codable { let color: ConfigColor let color2: ConfigColor } let data = rawJson.data(using: .utf8)! XCTAssertNotNil(data, "Data is nil") let output = try! decoder.decode(Test.self, from: data) XCTAssertEqual(output.color.red, 0) XCTAssertEqual(output.color.green, 0) XCTAssertEqual(output.color.blue, 255) XCTAssertEqual(output.color2.red, 255) XCTAssertEqual(output.color2.green, 100) XCTAssertEqual(output.color2.blue, 200) } }
34.444444
111
0.552688
f7d1748c650b812093664ca59570c791a816dd67
1,068
// // NewPhotoViewModel.swift // ForumThreads // // Created by aSqar on 13.05.2018. // Copyright © 2018 Askar Bakirov. All rights reserved. // import Foundation import ReactiveCocoa class NewPhotoViewModel : BaseViewModel { var isSaved:Bool { get { return self.photo.id != 0 } } var photo:PhotoDto! { didSet { (self.updatedContentSignal as! RACSubject).sendNext(nil) } } init(photo:PhotoDto!) { self.photo = photo super.init() } func send(){ CachedNetworkService().createPhoto(photo: photo) { (resultPhoto) in resultPhoto.withValue({ (rlmPhoto) in self.photo = PhotoDto.mapFromRealmObject(rlmPhoto) do { try self.realm().write { self.realm().add(rlmPhoto, update: true) } } catch let error { print(error) } }) } } }
22.25
75
0.487828
ccd749dabc8f5c9f414827c99f6e9fbb77d7fdc6
2,183
// // AppDelegate.swift // ReadHardCopyText // // Created by Mamun Ar Rashid on 7/1/17. // Copyright © 2017 Fantasy Apps. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.446809
285
0.755841
ef8bad226cc22fb4dd9d4b616b5971ac86b8e973
1,256
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten import Foundation // === xdr source ============================================================ // struct TimeBounds // { // //: specifies inclusive min ledger close time after which transaction is valid // uint64 minTime; // //: specifies inclusive max ledger close time before which transaction is valid. // //: note: transaction will be rejected if max time exceeds close time of current ledger on more then [`tx_expiration_period`](https://tokend.gitlab.io/horizon/#operation/info) // uint64 maxTime; // 0 here means no maxTime // }; // =========================================================================== public struct TimeBounds: XDRCodable { public var minTime: Uint64 public var maxTime: Uint64 public init( minTime: Uint64, maxTime: Uint64) { self.minTime = minTime self.maxTime = maxTime } public func toXDR() -> Data { var xdr = Data() xdr.append(self.minTime.toXDR()) xdr.append(self.maxTime.toXDR()) return xdr } public init(xdrData: inout Data) throws { self.minTime = try Uint64(xdrData: &xdrData) self.maxTime = try Uint64(xdrData: &xdrData) } }
28.545455
183
0.602707
89f5a503f7d8f240f82558cdfcace748d4ecb0f8
3,496
// // ViewController.swift // Project10 // // Created by TwoStraws on 17/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import UIKit class ViewController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var people = [Person]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewPerson)) let defaults = UserDefaults.standard if let savedPeople = defaults.object(forKey: "people") as? Data { let jsonDecoder = JSONDecoder() do { people = try jsonDecoder.decode([Person].self, from: savedPeople) } catch { print("Failed to load people") } } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return people.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Person", for: indexPath) as! PersonCell let person = people[indexPath.item] cell.name.text = person.name let path = getDocumentsDirectory().appendingPathComponent(person.image) cell.imageView.image = UIImage(contentsOfFile: path.path) cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor cell.imageView.layer.borderWidth = 2 cell.imageView.layer.cornerRadius = 3 cell.layer.cornerRadius = 7 return cell } @objc func addNewPerson() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self present(picker, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { var newImage: UIImage if let possibleImage = info[.editedImage] as? UIImage { newImage = possibleImage } else { return } let imageName = UUID().uuidString let imagePath = getDocumentsDirectory().appendingPathComponent(imageName) if let jpegData = newImage.jpegData(compressionQuality: 0.8) { try? jpegData.write(to: imagePath) } let person = Person(name: "Unknown", image: imageName) people.append(person) collectionView?.reloadData() dismiss(animated: true) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let person = people[indexPath.item] let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .alert) ac.addTextField() ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) ac.addAction(UIAlertAction(title: "OK", style: .default) { [unowned self, ac] _ in let newName = ac.textFields![0] person.name = newName.text! self.collectionView?.reloadData() self.save() }) present(ac, animated: true) } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } func save() { let jsonEncoder = JSONEncoder() if let savedData = try? jsonEncoder.encode(people) { let defaults = UserDefaults.standard defaults.set(savedData, forKey: "people") } else { print("Failed to save people.") } } }
29.133333
144
0.711957
0925be3f2f44bbf0bbd878b41349f1af1ea291f1
1,218
// // main.swift // fib_swift // // Created by Guillermo Lella on 3/21/21. // import Foundation func fib_recursive(n: Int) -> Int { if n <= 1 { return n } return (fib_recursive(n: n &- 1) &+ fib_recursive(n: n &- 2)) } func fib_iterative(n: Int) -> Int { var a = 0 var b = 1 for _ in 0..<n { let c = a + b a = b b = c } return a } var start = DispatchTime.now() // <<<<<<<<<< Start time print(fib_recursive(n: 42)) var end = DispatchTime.now() // <<<<<<<<<< end time var nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64) var timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests print("Recursive took: \(String(format: "%.3f", timeInterval)) secs") start = DispatchTime.now() // <<<<<<<<<< Start time print(fib_iterative(n: 42)) end = DispatchTime.now() // <<<<<<<<<< end time nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64) timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests print("Iterative took: \(String(format: "%.3f", timeInterval)) secs")
30.45
107
0.63711
791b6e32746f5e3ec6348f6416f2cc497afd5ab2
30,868
import Foundation /** A `MeiliSearch` instance represents a MeiliSearch client used to easily integrate your Swift product with the MeiliSearch server. - warning: `MeiliSearch` instances are thread safe and can be shared across threads or dispatch queues. */ public struct MeiliSearch { // MARK: Properties /** Current and immutable MeiliSearch configuration. To change this configuration please create a new MeiliSearch instance. */ private(set) var config: Config private let indexes: Indexes private let documents: Documents private let search: Search private let updates: Updates private let keys: Keys private let settings: Settings private let stats: Stats private let system: System // MARK: Initializers /** Obtains a MeiliSearch instance for the given `config`. - parameter config: Set the default configuration for the client. */ public init(_ config: Config = Config.default) throws { let request: Request = Request(config) self.config = try config.validate(request) self.indexes = Indexes(request) self.documents = Documents(request) self.search = Search(request) self.updates = Updates(request) self.keys = Keys(request) self.settings = Settings(request) self.stats = Stats(request) self.system = System(request) } // MARK: Index /** Create a new Index for the given `uid`. - parameter UID: The unique identifier for the `Index` to be created. - parameter completion: The completion closure used to notify when the server completes the write request, it returns a `Result` object that contains `Index` value. If the request was sucessful or `Error` if a failure occured. */ public func createIndex( UID: String, _ completion: @escaping (Result<Index, Swift.Error>) -> Void) { self.indexes.create(UID, completion) } /** Get the Index for the given `uid`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Index` value. If the request was sucessful or `Error` if a failure occured. */ public func getIndex( UID: String, _ completion: @escaping (Result<Index, Swift.Error>) -> Void) { self.indexes.get(UID, completion) } /** List the all Indexes. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[Index]` value. If the request was sucessful or `Error` if a failure occured. */ public func getIndexes( _ completion: @escaping (Result<[Index], Swift.Error>) -> Void) { self.indexes.getAll(completion) } /** Update index name. - parameter UID: The unique identifier for the `Index` to be found. - parameter name: New index name. - parameter completion: The completion closure used to notify when the server completes the update request, it returns a `Result` object that contains `()` value. If the request was sucessful or `Error` if a failure occured. */ public func updateIndex( UID: String, name: String, _ completion: @escaping (Result<(), Swift.Error>) -> Void) { self.indexes.update(UID, name, completion) } /** Delete the Index for the given `uid`. - parameter completion: The completion closure used to notify when the server completes the delete request, it returns a `Result` object that contains `()` value. If the request was sucessful or `Error` if a failure occured. */ public func deleteIndex( UID: String, _ completion: @escaping (Result<(), Swift.Error>) -> Void) { self.indexes.delete(UID, completion) } // MARK: Document /** Add a list of documents or replace them if they already exist. If you send an already existing document (same id) the whole existing document will be overwritten by the new document. Fields previously in the document not present in the new document are removed. For a partial update of the document see `addOrUpdateDocument`. - parameter UID: The unique identifier for the Document's index to be found. - parameter document: The document data (JSON) to be processed. - parameter completion: The completion closure used to notify when the server completes the update request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func addOrReplaceDocument( UID: String, document: Data, primaryKey: String?, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.documents.addOrReplace( UID, document, primaryKey, completion) } /** Add a list of documents and update them if they already. If you send an already existing document (same id) the old document will be only partially updated according to the fields of the new document. Thus, any fields not present in the new document are kept and remained unchanged. To completely overwrite a document see `addOrReplaceDocument`. - parameter UID: The unique identifier for the Document's index to be found. - parameter document: The document data (JSON) to be processed. - parameter completion: The completion closure used to notify when the server completes the update request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func addOrUpdateDocument( UID: String, document: Data, primaryKey: String?, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.documents.addOrUpdate( UID, document, primaryKey, completion) } /** Get the Document for the given `uid` and `identifier`. - parameter UID: The unique identifier for the Document's index to be found. - parameter identifier: The document identifier for the Document to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `T` value. If the request was sucessful or `Error` if a failure occured. */ public func getDocument<T>( UID: String, identifier: String, _ completion: @escaping (Result<T, Swift.Error>) -> Void) where T: Codable, T: Equatable { self.documents.get(UID, identifier, completion) } /** List the all Documents. - parameter UID: The unique identifier for the Document's index to be found. - parameter limit: Limit the size of the query. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[T]` value. If the request was sucessful or `Error` if a failure occured. */ public func getDocuments<T>( UID: String, limit: Int, _ completion: @escaping (Result<[T], Swift.Error>) -> Void) where T: Codable, T: Equatable { self.documents.getAll(UID, limit, completion) } /** Delete the Document for the given `uid` and `identifier`. - parameter UID: The unique identifier for the Document's index to be found. - parameter identifier: The document identifier for the Document to be found. - parameter completion: The completion closure used to notify when the server completes the delete request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func deleteDocument( UID: String, identifier: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.documents.delete(UID, identifier, completion) } /** Delete all Documents for the given `uid`. - parameter UID: The unique identifier for the Document's index to be found. - parameter completion: The completion closure used to notify when the server completes the delete request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func deleteAllDocuments( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.documents.deleteAll(UID, completion) } /** Delete a selection of documents based on array of document `uid`'s. - parameter UID: The unique identifier for the Document's index to be deleted. - parameter documentsUID: The array of unique identifier for the Document to be deleted. - parameter completion: The completion closure used to notify when the server completes the delete request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func deleteBatchDocuments( UID: String, documentsUID: [Int], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.documents.deleteBatch(UID, documentsUID, completion) } /** Search for a document in the `uid` and `searchParameters` - parameter UID: The unique identifier for the Document's index to be found. - parameter searchParameters: The document identifier for the Document to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `SearchResult<T>` value. If the request was sucessful or `Error` if a failure occured. */ public func search<T>( UID: String, _ searchParameters: SearchParameters, _ completion: @escaping (Result<SearchResult<T>, Swift.Error>) -> Void) where T: Codable, T: Equatable { self.search.search(UID, searchParameters, completion) } // MARK: Updates /** Get the status of an update in a given `Index`. - parameter UID: The unique identifier for the Document's index to be found. - parameter update: The update value. - parameter completion:The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Key` value. If the request was sucessful or `Error` if a failure occured. */ public func getUpdate( UID: String, _ update: Update, _ completion: @escaping (Result<Update.Result, Swift.Error>) -> Void) { self.updates.get(UID, update, completion) } /** Get the status of an update in a given `Index`. - parameter UID: The unique identifier for the Document's index to be found. - parameter update: The update value. - parameter completion:The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Key` value. If the request was sucessful or `Error` if a failure occured. */ public func getAllUpdates( UID: String, _ completion: @escaping (Result<[Update.Result], Swift.Error>) -> Void) { self.updates.getAll(UID, completion) } // MARK: Keys /** Each instance of MeiliSearch has three keys: a master, a private, and a public. Each key has a given set of permissions on the API routes. - parameter masterKey: Master key to access the `keys` function. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Key` value. If the request was sucessful or `Error` if a failure occured. */ public func keys( masterKey: String, _ completion: @escaping (Result<Key, Swift.Error>) -> Void) { self.keys.get(masterKey, completion) } // MARK: Settings /** Get a list of all the customization possible for an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Setting` value. If the request was sucessful or `Error` if a failure occured. */ public func getSetting( UID: String, _ completion: @escaping (Result<Setting, Swift.Error>) -> Void) { self.settings.get(UID, completion) } /** Update the settings for a given `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter setting: Setting to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateSetting( UID: String, _ setting: Setting, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.update(UID, setting, completion) } /** Reset the settings for a given `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetSetting( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.reset(UID, completion) } // MARK: Synonyms /** Get a list of all synonyms possible for an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String: [String]]` value. If the request was sucessful or `Error` if a failure occured. */ public func getSynonyms( UID: String, _ completion: @escaping (Result<[String: [String]], Swift.Error>) -> Void) { self.settings.getSynonyms(UID, completion) } /** Update the synonyms for a given `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter setting: Setting to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateSynonyms( UID: String, _ synonyms: [String: [String]], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateSynonyms(UID, synonyms, completion) } /** Reset the synonyms for a given `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetSynonyms( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetSynonyms(UID, completion) } // MARK: Stop words /** Get a list of all stop-words possible for an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String]` value. If the request was sucessful or `Error` if a failure occured. */ public func getStopWords( UID: String, _ completion: @escaping (Result<[String], Swift.Error>) -> Void) { self.settings.getStopWords(UID, completion) } /** Update the stop-words for a given `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter stopWords: Array of stop-word to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateStopWords( UID: String, _ stopWords: [String], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateStopWords(UID, stopWords, completion) } /** Reset the stop-words for a given `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetStopWords( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetStopWords(UID, completion) } // MARK: Ranking rules /** Get a list of all ranking rules possible for an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String]` value. If the request was sucessful or `Error` if a failure occured. */ public func getRankingRules( UID: String, _ completion: @escaping (Result<[String], Swift.Error>) -> Void) { self.settings.getRankingRules(UID, completion) } /** Update the ranking rules for a given `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter rankingRules: Array of ranking rules to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateRankingRules( UID: String, _ rankingRules: [String], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateRankingRules(UID, rankingRules, completion) } /** Reset the ranking rules for a given `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetRankingRules( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetRankingRules(UID, completion) } // MARK: Distinct Attribute /** Get the distinct attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String]` value. If the request was sucessful or `Error` if a failure occured. */ public func getDistinctAttribute( UID: String, _ completion: @escaping (Result<String, Swift.Error>) -> Void) { self.settings.getDistinctAttribute(UID, completion) } /** Update the distinct attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter distinctAttribute: The distinct attribute to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateDistinctAttribute( UID: String, _ distinctAttribute: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateDistinctAttribute( UID, distinctAttribute, completion) } /** Reset the distinct attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetDistinctAttribute( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetDistinctAttribute(UID, completion) } // MARK: Searchable Attribute /** Get the searchable attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String]` value. If the request was sucessful or `Error` if a failure occured. */ public func getSearchableAttributes( UID: String, _ completion: @escaping (Result<[String], Swift.Error>) -> Void) { self.settings.getSearchableAttributes(UID, completion) } /** Update the searchable attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter searchableAttribute: The searchable attribute to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateSearchableAttributes( UID: String, _ searchableAttribute: [String], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateSearchableAttributes( UID, searchableAttribute, completion) } /** Reset the searchable attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetSearchableAttributes( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetSearchableAttributes(UID, completion) } // MARK: Displayed Attribute /** Get the displayed attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `[String]` value. If the request was sucessful or `Error` if a failure occured. */ public func getDisplayedAttributes( UID: String, _ completion: @escaping (Result<[String], Swift.Error>) -> Void) { self.settings.getDisplayedAttributes(UID, completion) } /** Update the displayed attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter displayedAttribute: The displayed attribute to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateDisplayedAttributes( UID: String, _ displayedAttribute: [String], _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateDisplayedAttributes( UID, displayedAttribute, completion) } /** Reset the displayed attribute field of an `Index`. - parameter UID: The unique identifier for the `Index` to be reset. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func resetDisplayedAttributes( UID: String, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.resetDisplayedAttributes(UID, completion) } // MARK: Accept New Fields /** Get the accept new fields field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Bool` value. If the request was sucessful or `Error` if a failure occured. */ public func getAcceptNewFields( UID: String, _ completion: @escaping (Result<Bool, Swift.Error>) -> Void) { self.settings.getAcceptNewFields(UID, completion) } /** Update the accept new fields field of an `Index`. - parameter UID: The unique identifier for the `Index` to be found. - parameter acceptNewFields: The accept new fields option to be applied into `Index`. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Update` value. If the request was sucessful or `Error` if a failure occured. */ public func updateAcceptNewFields( UID: String, _ acceptNewFields: Bool, _ completion: @escaping (Result<Update, Swift.Error>) -> Void) { self.settings.updateAcceptNewFields(UID, acceptNewFields, completion) } // MARK: Stats /** Get stats of an index. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Stat` value. If the request was sucessful or `Error` if a failure occured. */ public func stat( UID: String, _ completion: @escaping (Result<Stat, Swift.Error>) -> Void) { self.stats.stat(UID, completion) } /** Get stats of all indexes. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `AllStats` value. If the request was sucessful or `Error` if a failure occured. */ public func allStats( _ completion: @escaping (Result<AllStats, Swift.Error>) -> Void) { self.stats.allStats(completion) } // MARK: System /** Update health of MeiliSearch server. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `()` value. If the request was sucessful or `Error` if a failure occured. */ public func health(_ completion: @escaping (Result<(), Swift.Error>) -> Void) { self.system.health(completion) } /** Get health of MeiliSearch server. - parameter health: Set the MeiliSearch server health status. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `()` value. If the request was sucessful or `Error` if a failure occured. */ public func updateHealth( health: Bool, _ completion: @escaping (Result<(), Swift.Error>) -> Void) { self.system.updateHealth(health, completion) } /** Get version of MeiliSearch. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `Version` value. If the request was sucessful or `Error` if a failure occured. */ public func version( _ completion: @escaping (Result<Version, Swift.Error>) -> Void) { self.system.version(completion) } /** Get system information. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `SystemInfo` value. If the request was sucessful or `Error` if a failure occured. */ public func systemInfo( _ completion: @escaping (Result<SystemInfo, Swift.Error>) -> Void) { self.system.systemInfo(completion) } /** Get the pretty system information. - parameter completion: The completion closure used to notify when the server completes the query request, it returns a `Result` object that contains `SystemInfo` value. If the request was sucessful or `Error` if a failure occured. */ public func prettySystemInfo( _ completion: @escaping (Result<PrettySystemInfo, Swift.Error>) -> Void) { self.system.prettySystemInfo(completion) } }
39.473146
105
0.661008
f88c1b5cb331701def54bf0703469c8da1cbc2e4
733
// // UpdateUpdateItemQualityUsecase.swift // Wemanity // // Created by Jean-Nicolas DEFOSSE on 15/12/2020. // // import Foundation protocol UpdateItemsQualityUseCase{ func execute(request: UpdateItemsQualityRequest, _ completion: (Result<[Item], ItemError>) -> Void) } final class AppUpdateItemsQualityUseCase: UpdateItemsQualityUseCase { var repository: ItemRepository init(repository: ItemRepository) { self.repository = repository } func execute(request: UpdateItemsQualityRequest, _ completion: (Result<[Item], ItemError>) -> Void) { repository.updateQuality(items: request.items, completion: completion) } } struct UpdateItemsQualityRequest { var items: [Item] }
23.645161
105
0.720327
3a289faaf1e5df07175e7d3980cd7902203bca43
26,628
// // RNTrackPlayer.swift // RNTrackPlayer // // Created by David Chavez on 13.08.17. // Copyright © 2017 David Chavez. All rights reserved. // import Foundation import MediaPlayer import SwiftAudioEx @objc(RNTrackPlayer) public class RNTrackPlayer: RCTEventEmitter { // MARK: - Attributes private var hasInitialized = false private let player = QueuedAudioPlayer() // MARK: - Lifecycle Methods public override init() { super.init() player.event.playbackEnd.addListener(self, handleAudioPlayerPlaybackEnded) player.event.receiveMetadata.addListener(self, handleAudioPlayerMetadataReceived) player.event.stateChange.addListener(self, handleAudioPlayerStateChange) player.event.fail.addListener(self, handleAudioPlayerFailed) player.event.queueIndex.addListener(self, handleAudioPlayerQueueIndexChange) } deinit { reset(resolve: { _ in }, reject: { _, _, _ in }) } // MARK: - RCTEventEmitter override public static func requiresMainQueueSetup() -> Bool { return true; } @objc(constantsToExport) override public func constantsToExport() -> [AnyHashable: Any] { return [ "STATE_NONE": AVPlayerWrapperState.idle.rawValue, "STATE_READY": AVPlayerWrapperState.ready.rawValue, "STATE_PLAYING": AVPlayerWrapperState.playing.rawValue, "STATE_PAUSED": AVPlayerWrapperState.paused.rawValue, "STATE_STOPPED": AVPlayerWrapperState.idle.rawValue, "STATE_BUFFERING": AVPlayerWrapperState.loading.rawValue, "TRACK_PLAYBACK_ENDED_REASON_END": PlaybackEndedReason.playedUntilEnd.rawValue, "TRACK_PLAYBACK_ENDED_REASON_JUMPED": PlaybackEndedReason.jumpedToIndex.rawValue, "TRACK_PLAYBACK_ENDED_REASON_NEXT": PlaybackEndedReason.skippedToNext.rawValue, "TRACK_PLAYBACK_ENDED_REASON_PREVIOUS": PlaybackEndedReason.skippedToPrevious.rawValue, "TRACK_PLAYBACK_ENDED_REASON_STOPPED": PlaybackEndedReason.playerStopped.rawValue, "PITCH_ALGORITHM_LINEAR": PitchAlgorithm.linear.rawValue, "PITCH_ALGORITHM_MUSIC": PitchAlgorithm.music.rawValue, "PITCH_ALGORITHM_VOICE": PitchAlgorithm.voice.rawValue, "CAPABILITY_PLAY": Capability.play.rawValue, "CAPABILITY_PLAY_FROM_ID": "NOOP", "CAPABILITY_PLAY_FROM_SEARCH": "NOOP", "CAPABILITY_PAUSE": Capability.pause.rawValue, "CAPABILITY_STOP": Capability.stop.rawValue, "CAPABILITY_SEEK_TO": Capability.seek.rawValue, "CAPABILITY_SKIP": "NOOP", "CAPABILITY_SKIP_TO_NEXT": Capability.next.rawValue, "CAPABILITY_SKIP_TO_PREVIOUS": Capability.previous.rawValue, "CAPABILITY_SET_RATING": "NOOP", "CAPABILITY_JUMP_FORWARD": Capability.jumpForward.rawValue, "CAPABILITY_JUMP_BACKWARD": Capability.jumpBackward.rawValue, "CAPABILITY_LIKE": Capability.like.rawValue, "CAPABILITY_DISLIKE": Capability.dislike.rawValue, "CAPABILITY_BOOKMARK": Capability.bookmark.rawValue, "REPEAT_OFF": RepeatMode.off.rawValue, "REPEAT_TRACK": RepeatMode.track.rawValue, "REPEAT_QUEUE": RepeatMode.queue.rawValue, ] } @objc(supportedEvents) override public func supportedEvents() -> [String] { return [ "playback-queue-ended", "playback-state", "playback-error", "playback-track-changed", "playback-metadata-received", "remote-stop", "remote-pause", "remote-play", "remote-duck", "remote-next", "remote-seek", "remote-previous", "remote-jump-forward", "remote-jump-backward", "remote-like", "remote-dislike", "remote-bookmark", ] } func setupInterruptionHandling() { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self) notificationCenter.addObserver(self, selector: #selector(handleInterruption), name: AVAudioSession.interruptionNotification, object: nil) } @objc func handleInterruption(notification: Notification) { guard let userInfo = notification.userInfo, let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let type = AVAudioSession.InterruptionType(rawValue: typeValue) else { return } if type == .began { // Interruption began, take appropriate actions (save state, update user interface) self.sendEvent(withName: "remote-duck", body: [ "paused": true ]) } else if type == .ended { guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else { return } let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue) if options.contains(.shouldResume) { // Interruption Ended - playback should resume self.sendEvent(withName: "remote-duck", body: [ "paused": false ]) } else { // Interruption Ended - playback should NOT resume self.sendEvent(withName: "remote-duck", body: [ "paused": true, "permanent": true ]) } } } // MARK: - Bridged Methods @objc(setupPlayer:resolver:rejecter:) public func setupPlayer(config: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if hasInitialized { resolve(NSNull()) return } setupInterruptionHandling(); // configure if player waits to play let autoWait: Bool = config["waitForBuffer"] as? Bool ?? false player.automaticallyWaitsToMinimizeStalling = autoWait // configure buffer size let minBuffer: TimeInterval = config["minBuffer"] as? TimeInterval ?? 0 player.bufferDuration = minBuffer // configure if control center metdata should auto update let autoUpdateMetadata: Bool = config["autoUpdateMetadata"] as? Bool ?? true player.automaticallyUpdateNowPlayingInfo = autoUpdateMetadata // configure audio session - category, options & mode var sessionCategory: AVAudioSession.Category = .playback var sessionCategoryOptions: AVAudioSession.CategoryOptions = [] var sessionCategoryMode: AVAudioSession.Mode = .default if let sessionCategoryStr = config["iosCategory"] as? String, let mappedCategory = SessionCategory(rawValue: sessionCategoryStr) { sessionCategory = mappedCategory.mapConfigToAVAudioSessionCategory() } let sessionCategoryOptsStr = config["iosCategoryOptions"] as? [String] let mappedCategoryOpts = sessionCategoryOptsStr?.compactMap { SessionCategoryOptions(rawValue: $0)?.mapConfigToAVAudioSessionCategoryOptions() } ?? [] sessionCategoryOptions = AVAudioSession.CategoryOptions(mappedCategoryOpts) if let sessionCategoryModeStr = config["iosCategoryMode"] as? String, let mappedCategoryMode = SessionCategoryMode(rawValue: sessionCategoryModeStr) { sessionCategoryMode = mappedCategoryMode.mapConfigToAVAudioSessionCategoryMode() } // Progressively opt into AVAudioSession policies for background audio // and AirPlay 2. if #available(iOS 13.0, *) { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longFormAudio, options: sessionCategoryOptions) } else if #available(iOS 11.0, *) { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, policy: .longForm, options: sessionCategoryOptions) } else { try? AVAudioSession.sharedInstance().setCategory(sessionCategory, mode: sessionCategoryMode, options: sessionCategoryOptions) } // setup event listeners player.remoteCommandController.handleChangePlaybackPositionCommand = { [weak self] event in if let event = event as? MPChangePlaybackPositionCommandEvent { self?.sendEvent(withName: "remote-seek", body: ["position": event.positionTime]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleNextTrackCommand = { [weak self] _ in self?.sendEvent(withName: "remote-next", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePauseCommand = { [weak self] _ in self?.sendEvent(withName: "remote-pause", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePlayCommand = { [weak self] _ in self?.sendEvent(withName: "remote-play", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handlePreviousTrackCommand = { [weak self] _ in self?.sendEvent(withName: "remote-previous", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleSkipBackwardCommand = { [weak self] event in if let command = event.command as? MPSkipIntervalCommand, let interval = command.preferredIntervals.first { self?.sendEvent(withName: "remote-jump-backward", body: ["interval": interval]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleSkipForwardCommand = { [weak self] event in if let command = event.command as? MPSkipIntervalCommand, let interval = command.preferredIntervals.first { self?.sendEvent(withName: "remote-jump-forward", body: ["interval": interval]) return MPRemoteCommandHandlerStatus.success } return MPRemoteCommandHandlerStatus.commandFailed } player.remoteCommandController.handleStopCommand = { [weak self] _ in self?.sendEvent(withName: "remote-stop", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleTogglePlayPauseCommand = { [weak self] _ in if self?.player.playerState == .paused { self?.sendEvent(withName: "remote-play", body: nil) return MPRemoteCommandHandlerStatus.success } self?.sendEvent(withName: "remote-pause", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleLikeCommand = { [weak self] _ in self?.sendEvent(withName: "remote-like", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleDislikeCommand = { [weak self] _ in self?.sendEvent(withName: "remote-dislike", body: nil) return MPRemoteCommandHandlerStatus.success } player.remoteCommandController.handleBookmarkCommand = { [weak self] _ in self?.sendEvent(withName: "remote-bookmark", body: nil) return MPRemoteCommandHandlerStatus.success } hasInitialized = true resolve(NSNull()) } @objc(destroy) public func destroy() { print("Destroying player") self.player.stop() self.player.nowPlayingInfoController.clear() try? AVAudioSession.sharedInstance().setActive(false) hasInitialized = false } @objc(updateOptions:resolver:rejecter:) public func update(options: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { var capabilitiesStr = options["capabilities"] as? [String] ?? [] if (capabilitiesStr.contains("play") && capabilitiesStr.contains("pause")) { capabilitiesStr.append("togglePlayPause"); } let capabilities = capabilitiesStr.compactMap { Capability(rawValue: $0) } player.remoteCommands = capabilities.map { capability in capability.mapToPlayerCommand(forwardJumpInterval: options["forwardJumpInterval"] as? NSNumber, backwardJumpInterval: options["backwardJumpInterval"] as? NSNumber, likeOptions: options["likeOptions"] as? [String: Any], dislikeOptions: options["dislikeOptions"] as? [String: Any], bookmarkOptions: options["bookmarkOptions"] as? [String: Any]) } resolve(NSNull()) } @objc(add:before:resolver:rejecter:) public func add(trackDicts: [[String: Any]], before trackIndex: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { UIApplication.shared.beginReceivingRemoteControlEvents(); } var tracks = [Track]() for trackDict in trackDicts { guard let track = Track(dictionary: trackDict) else { reject("invalid_track_object", "Track is missing a required key", nil) return } tracks.append(track) } if (trackIndex.intValue > player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) } else if trackIndex.intValue == -1 { // -1 means no index was passed and therefore should be inserted at the end. try? player.add(items: tracks, playWhenReady: false) } else { try? player.add(items: tracks, at: trackIndex.intValue) } resolve(NSNull()) } @objc(remove:resolver:rejecter:) public func remove(tracks indexes: [Int], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Removing tracks:", indexes) for index in indexes { // we do not allow removal of the current item if index == player.currentIndex { continue } try? player.removeItem(at: index) } resolve(NSNull()) } @objc(removeUpcomingTracks:rejecter:) public func removeUpcomingTracks(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Removing upcoming tracks") player.removeUpcomingItems() resolve(NSNull()) } @objc(skip:resolver:rejecter:) public func skip(to trackIndex: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (trackIndex.intValue < 0 || trackIndex.intValue >= player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) return } print("Skipping to track:", trackIndex) try? player.jumpToItem(atIndex: trackIndex.intValue, playWhenReady: player.playerState == .playing) resolve(NSNull()) } @objc(skipToNext:rejecter:) public func skipToNext(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Skipping to next track") do { try player.next() resolve(NSNull()) } catch (_) { reject("queue_exhausted", "There is no tracks left to play", nil) } } @objc(skipToPrevious:rejecter:) public func skipToPrevious(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Skipping to next track") do { try player.previous() resolve(NSNull()) } catch (_) { reject("no_previous_track", "There is no previous track", nil) } } @objc(reset:rejecter:) public func reset(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Resetting player.") player.stop() resolve(NSNull()) DispatchQueue.main.async { UIApplication.shared.endReceivingRemoteControlEvents(); } } @objc(play:rejecter:) public func play(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Starting/Resuming playback") try? AVAudioSession.sharedInstance().setActive(true) player.play() resolve(NSNull()) } @objc(pause:rejecter:) public func pause(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Pausing playback") player.pause() resolve(NSNull()) } @objc(stop:rejecter:) public func stop(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Stopping playback") player.stop() resolve(NSNull()) } @objc(seekTo:resolver:rejecter:) public func seek(to time: Double, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Seeking to \(time) seconds") player.seek(to: time) resolve(NSNull()) } @objc(setRepeatMode:resolver:rejecter:) public func setRepeatMode(repeatMode: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { player.repeatMode = SwiftAudioEx.RepeatMode(rawValue: repeatMode.intValue) ?? .off resolve(NSNull()) } @objc(getRepeatMode:rejecter:) public func getRepeatMode(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current repeatMode") resolve(player.repeatMode.rawValue) } @objc(setVolume:resolver:rejecter:) public func setVolume(level: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Setting volume to \(level)") player.volume = level resolve(NSNull()) } @objc(getVolume:rejecter:) public func getVolume(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current volume") resolve(player.volume) } @objc(setRate:resolver:rejecter:) public func setRate(rate: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Setting rate to \(rate)") player.rate = rate resolve(NSNull()) } @objc(getRate:rejecter:) public func getRate(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { print("Getting current rate") resolve(player.rate) } @objc(getTrack:resolver:rejecter:) public func getTrack(index: NSNumber, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (index.intValue >= 0 && index.intValue < player.items.count) { let track = player.items[index.intValue] resolve((track as? Track)?.toObject()) } else { resolve(NSNull()) } } @objc(getQueue:rejecter:) public func getQueue(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { let serializedQueue = player.items.map { ($0 as! Track).toObject() } resolve(serializedQueue) } @objc(getCurrentTrack:rejecter:) public func getCurrentTrack(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { let index = player.currentIndex if index < 0 || index >= player.items.count { resolve(NSNull()) } else { resolve(index) } } @objc(getDuration:rejecter:) public func getDuration(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.duration) } @objc(getBufferedPosition:rejecter:) public func getBufferedPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.bufferedPosition) } @objc(getPosition:rejecter:) public func getPosition(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.currentTime) } @objc(getState:rejecter:) public func getState(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(player.playerState.rawValue) } @objc(updateMetadataForTrack:metadata:resolver:rejecter:) public func updateMetadata(for trackIndex: NSNumber, metadata: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if (trackIndex.intValue < 0 || trackIndex.intValue >= player.items.count) { reject("index_out_of_bounds", "The track index is out of bounds", nil) return } let track = player.items[trackIndex.intValue] as! Track track.updateMetadata(dictionary: metadata) if (player.currentIndex == trackIndex.intValue) { Metadata.update(for: player, with: metadata) } resolve(NSNull()) } @objc(clearNowPlayingMetadata:rejecter:) public func clearNowPlayingMetadata(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { player.nowPlayingInfoController.clear() } @objc(updateNowPlayingMetadata:resolver:rejecter:) public func updateNowPlayingMetadata(metadata: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { Metadata.update(for: player, with: metadata) } // MARK: - QueuedAudioPlayer Event Handlers func handleAudioPlayerStateChange(state: AVPlayerWrapperState) { sendEvent(withName: "playback-state", body: ["state": state.rawValue]) } func handleAudioPlayerMetadataReceived(metadata: [AVMetadataItem]) { func getMetadataItem(forIdentifier: AVMetadataIdentifier) -> String { return AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: forIdentifier).first?.stringValue ?? "" } var source: String { switch metadata.first?.keySpace { case AVMetadataKeySpace.id3: return "id3" case AVMetadataKeySpace.icy: return "icy" case AVMetadataKeySpace.quickTimeMetadata: return "quicktime" case AVMetadataKeySpace.common: return "unknown" default: return "unknown" } } let album = getMetadataItem(forIdentifier: .commonIdentifierAlbumName) var artist = getMetadataItem(forIdentifier: .commonIdentifierArtist) var title = getMetadataItem(forIdentifier: .commonIdentifierTitle) var date = getMetadataItem(forIdentifier: .commonIdentifierCreationDate) var url = ""; var genre = ""; if (source == "icy") { url = getMetadataItem(forIdentifier: .icyMetadataStreamURL) } else if (source == "id3") { if (date.isEmpty) { date = getMetadataItem(forIdentifier: .id3MetadataDate) } genre = getMetadataItem(forIdentifier: .id3MetadataContentType) url = getMetadataItem(forIdentifier: .id3MetadataOfficialAudioSourceWebpage) if (url.isEmpty) { url = getMetadataItem(forIdentifier: .id3MetadataOfficialAudioFileWebpage) } if (url.isEmpty) { url = getMetadataItem(forIdentifier: .id3MetadataOfficialArtistWebpage) } } else if (source == "quicktime") { genre = getMetadataItem(forIdentifier: .quickTimeMetadataGenre) } // Detect ICY metadata and split title into artist & title: // - source should be either "unknown" (pre iOS 14) or "icy" (iOS 14 and above) // - we have a title, but no artist if ((source == "unknown" || source == "icy") && !title.isEmpty && artist.isEmpty) { if let index = title.range(of: " - ")?.lowerBound { artist = String(title.prefix(upTo: index)); title = String(title.suffix(from: title.index(index, offsetBy: 3))); } } var data : [String : String?] = [ "title": title.isEmpty ? nil : title, "url": url.isEmpty ? nil : url, "artist": artist.isEmpty ? nil : artist, "album": album.isEmpty ? nil : album, "date": date.isEmpty ? nil : date, "genre": genre.isEmpty ? nil : genre ] if (data.values.contains { $0 != nil }) { data["source"] = source sendEvent(withName: "playback-metadata-received", body: data) } } func handleAudioPlayerFailed(error: Error?) { sendEvent(withName: "playback-error", body: ["error": error?.localizedDescription]) } func handleAudioPlayerPlaybackEnded(reason: PlaybackEndedReason) { // fire an event for the queue ending if player.nextItems.count == 0 && reason == PlaybackEndedReason.playedUntilEnd { sendEvent(withName: "playback-queue-ended", body: [ "track": player.currentIndex, "position": player.currentTime, ]) } // fire an event for the same track starting again switch player.repeatMode { case .track: handleAudioPlayerQueueIndexChange(previousIndex: player.currentIndex, nextIndex: player.currentIndex) default: break } } func handleAudioPlayerQueueIndexChange(previousIndex: Int?, nextIndex: Int?) { var dictionary: [String: Any] = [ "position": player.currentTime ] if let previousIndex = previousIndex { dictionary["track"] = previousIndex } if let nextIndex = nextIndex { dictionary["nextTrack"] = nextIndex } // Load isLiveStream option for track var isTrackLiveStream = false if let nextIndex = nextIndex { let track = player.items[nextIndex] isTrackLiveStream = (track as? Track)?.isLiveStream ?? false } if player.automaticallyUpdateNowPlayingInfo { player.nowPlayingInfoController.set(keyValue: NowPlayingInfoProperty.isLiveStream(isTrackLiveStream)) } sendEvent(withName: "playback-track-changed", body: dictionary) } }
40.162896
161
0.640379
dd2f49329ca98de9a9cf4783745c2795eb1ff539
1,331
// // AccountLink.swift // // // Created by Andrew Edwards on 11/3/19. // import Foundation /// The [Account Link Object](https://stripe.com/docs/api/account_links/object). public struct AccountLink: StripeModel { /// String representing the object’s type. Objects of the same type share the same value. public var object: String /// Time at which the object was created. Measured in seconds since the Unix epoch. public var created: Date /// The timestamp at which this account link will expire. public var expiresAt: Date? /// The URL for the account link. public var url: String? } public enum AccountLinkCreationType: String, StripeModel { /// Provides a form for inputting outstanding requirements. Send the user to the form in this mode to just collect the new information you need. case customAccountVerification = "custom_account_verification" /// Displays the fields that are already populated on the account object, and allows your user to edit previously provided information. Consider framing this as “edit my profile” or “update my verification information”. case customAccountUpdate = "custom_account_update" } public enum AccountLinkCreationCollectType: String, StripeModel { case currentlyDue = "currently_due" case eventuallyDue = "eventually_due" }
40.333333
223
0.747558
20907b1b92eb45fefc3a7c06c1ec534475086ce7
3,723
import ReactiveSwift import XCTest @testable import ComposableArchitecture final class EffectThrottleTests: XCTestCase { let scheduler = TestScheduler() func testThrottleLatest() { var values: [Int] = [] var effectRuns = 0 func runThrottledEffect(value: Int) { struct CancelToken: Hashable {} Effect.deferred { () -> Effect<Int, Never> in effectRuns += 1 return .init(value: value) } .throttle(id: CancelToken(), for: 1, scheduler: scheduler, latest: true) .startWithValues { values.append($0) } } runThrottledEffect(value: 1) // A value emits right away. XCTAssertEqual(values, [1]) runThrottledEffect(value: 2) // A second value is throttled. XCTAssertEqual(values, [1]) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 3) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 4) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 5) // A third value is throttled. XCTAssertEqual(values, [1]) scheduler.advance(by: .milliseconds(250)) // The latest value emits. XCTAssertEqual(values, [1, 5]) } func testThrottleFirst() { var values: [Int] = [] var effectRuns = 0 func runThrottledEffect(value: Int) { struct CancelToken: Hashable {} Effect.deferred { () -> Effect<Int, Never> in effectRuns += 1 return .init(value: value) } .throttle(id: CancelToken(), for: 1, scheduler: scheduler, latest: false) .startWithValues { values.append($0) } } runThrottledEffect(value: 1) // A value emits right away. XCTAssertEqual(values, [1]) runThrottledEffect(value: 2) // A second value is throttled. XCTAssertEqual(values, [1]) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 3) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 4) scheduler.advance(by: .milliseconds(250)) runThrottledEffect(value: 5) // A third value is throttled. XCTAssertEqual(values, [1]) scheduler.advance(by: .milliseconds(250)) // The first throttled value emits. XCTAssertEqual(values, [1, 2]) } func testThrottleAfterInterval() { var values: [Int] = [] var effectRuns = 0 func runThrottledEffect(value: Int) { struct CancelToken: Hashable {} Effect.deferred { () -> Effect<Int, Never> in effectRuns += 1 return .init(value: value) } .throttle(id: CancelToken(), for: 1, scheduler: scheduler, latest: true) .startWithValues { values.append($0) } } runThrottledEffect(value: 1) // A value emits right away. XCTAssertEqual(values, [1]) scheduler.advance(by: .seconds(2)) runThrottledEffect(value: 2) // A second value is emitted right away. XCTAssertEqual(values, [1, 2]) } func testThrottleEmitsFirstValueOnce() { var values: [Int] = [] var effectRuns = 0 func runThrottledEffect(value: Int) { struct CancelToken: Hashable {} Effect.deferred { () -> Effect<Int, Never> in effectRuns += 1 return .init(value: value) } .throttle( id: CancelToken(), for: 1, scheduler: scheduler, latest: false ) .startWithValues { values.append($0) } } runThrottledEffect(value: 1) // A value emits right away. XCTAssertEqual(values, [1]) scheduler.advance(by: .milliseconds(500)) runThrottledEffect(value: 2) scheduler.advance(by: .milliseconds(500)) runThrottledEffect(value: 3) // A second value is emitted right away. XCTAssertEqual(values, [1, 2]) } }
22.840491
79
0.639269
16dc308ad50799efdbca7e10836e6633d4638978
577
// // CollectionView.ItemsInSectionError.swift // AnKit // // Created by Anvipo on 07.11.2021. // import Foundation public extension CollectionView { /// Error, which could occure in `CollectionView` `items(in:)` method. enum ItemsInSectionError { /// Specified section was not found in collection view. case sectionWasNotFound } } extension CollectionView.ItemsInSectionError: LocalizedError { public var errorDescription: String? { switch self { case .sectionWasNotFound: return """ Specified section was not found in collection view. """ } } }
20.607143
71
0.72617
6a139e9a5c5e1d843c5ad399e45dc6bf80a9d31f
2,114
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-silgen -primary-file %s -o %t/OSLogConstantEvaluableTest_silgen.sil // // Run the (mandatory) passes on which constant evaluator depends, and run the // constant evaluator on the SIL produced after the dependent passes are run. // // RUN: %target-sil-opt -silgen-cleanup -raw-sil-inst-lowering -allocbox-to-stack -mandatory-inlining -constexpr-limit 2048 -test-constant-evaluable-subset %t/OSLogConstantEvaluableTest_silgen.sil > %t/OSLogConstantEvaluableTest.sil 2> %t/error-output // // RUN: %FileCheck %s < %t/error-output // // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos // Test that the functions defined in the OSLogPrototype overlay annotated as // constant evaluable are so (with the constexpr-limit defined above). // This test is meant to catch regressions in the OSLog overlay implementation // affecting the constant evaluability of functions that are expected to be so. import OSLogPrototype // CHECK-LABEL: @init(stringLiteral: String) -> OSLogMessage // CHECK-NOT: error: @_semantics("test_driver") func osLogMessageStringLiteralInitTest() -> OSLogMessage { return "A string literal" } // CHECK-LABEL: @init(literalCapacity: Int, interpolationCount: Int) -> OSLogInterpolation // CHECK-NOT: error: // CHECK-LABEL: @appendLiteral(String) -> () // CHECK-NOT: error: // CHECK-LABEL: @appendInterpolation(_: @autoclosure () -> Int, format: IntFormat, privacy: Privacy) -> () // CHECK-NOT: error: // CHECK-LABEL: @appendLiteral(String) -> () // CHECK-NOT: error: // CHECK-LABEL: @init(stringInterpolation: OSLogInterpolation) -> OSLogMessage // CHECK-NOT: error: @_semantics("test_driver") func intValueInterpolationTest() -> OSLogMessage { return "An integer value \(10)" } // CHECK-LABEL: @init(literalCapacity: Int, interpolationCount: Int) -> OSLogInterpolation // CHECK-NOT: error: // CHECK-LABEL: @appendInterpolation(_: @autoclosure () -> String, privacy: Privacy) -> () // CHECK-NOT: error: @_semantics("test_driver") func stringValueInterpolationTest() -> OSLogMessage { return "A string value \("xyz")" }
42.28
251
0.737938
110ca93547433415ebd02778a35a826f1392297b
979
// // beaconTestTests.swift // beaconTestTests // // Created by 大庭 正考 on 2018/05/05. // Copyright © 2018年 masataka oba. All rights reserved. // import XCTest @testable import beaconTest class beaconTestTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.459459
111
0.635342
566eb1e5bd906baa0b82bef3a5706fe39c2b0a0d
15,344
// // NSButton+Kingfisher.swift // Kingfisher // // Created by Jie Zhang on 14/04/2016. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit extension KingfisherWrapper where Base: NSButton { // MARK: Setting Image /// Sets an image to the button with a source. /// /// - Parameters: /// - source: The `Source` object contains information about how to get the image. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source. /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Sets an image to the button with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource?.convertToSource(), placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } func setImage( with source: Source?, placeholder: KFCrossPlatformImage? = nil, parsedOptions: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self guard let source = source else { base.image = placeholder mutatingSelf.taskIdentifier = nil completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = parsedOptions if !options.keepCurrentImageWhileLoading { base.image = placeholder } let issuedIdentifier = Source.Identifier.next() mutatingSelf.taskIdentifier = issuedIdentifier if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.image = image }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.taskIdentifier else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.taskIdentifier = nil switch result { case .success(let value): self.base.image = value.image completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.image = image } completionHandler?(result) } } } ) mutatingSelf.imageTask = task return task } // MARK: Cancelling Downloading Task /// Cancels the image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelImageDownloadTask() { imageTask?.cancel() } // MARK: Setting Alternate Image @discardableResult public func setAlternateImage( with source: Source?, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) return setAlternateImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Sets an alternate image to the button with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setAlternateImage( with resource: Resource?, placeholder: KFCrossPlatformImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setAlternateImage( with: resource?.convertToSource(), placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } func setAlternateImage( with source: Source?, placeholder: KFCrossPlatformImage? = nil, parsedOptions: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self guard let source = source else { base.alternateImage = placeholder mutatingSelf.alternateTaskIdentifier = nil completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = parsedOptions if !options.keepCurrentImageWhileLoading { base.alternateImage = placeholder } let issuedIdentifier = Source.Identifier.next() mutatingSelf.alternateTaskIdentifier = issuedIdentifier if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.alternateImage = image }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 }, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.alternateTaskIdentifier else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.alternateImageTask = nil mutatingSelf.alternateTaskIdentifier = nil switch result { case .success(let value): self.base.alternateImage = value.image completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.alternateImage = image } completionHandler?(result) } } } ) mutatingSelf.alternateImageTask = task return task } // MARK: Cancelling Alternate Image Downloading Task /// Cancels the alternate image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelAlternateImageDownloadTask() { alternateImageTask?.cancel() } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var imageTaskKey: Void? private var alternateTaskIdentifierKey: Void? private var alternateImageTaskKey: Void? extension KingfisherWrapper where Base: NSButton { // MARK: Properties public private(set) var taskIdentifier: Source.Identifier.Value? { get { let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey) return box?.value } set { let box = newValue.map { Box($0) } setRetainedAssociatedObject(base, &taskIdentifierKey, box) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } public private(set) var alternateTaskIdentifier: Source.Identifier.Value? { get { let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey) return box?.value } set { let box = newValue.map { Box($0) } setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box) } } private var alternateImageTask: DownloadTask? { get { return getAssociatedObject(base, &alternateImageTaskKey) } set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)} } } #endif
41.358491
119
0.622263
33792dd98d87e09a38c1ab4eb53fa1ddc4f15921
1,877
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import MaterialIcons public struct Theme { public static let `default` = Self() public var foregroundColor = NSColor.textColor { didSet { self.closeButtonImage = Icon.close.asImage( dimension: self.iconDimension.width, color: self.foregroundColor ) } } public var backgroundColor = NSColor.textBackgroundColor public var separatorColor = NSColor.gridColor public var selectedForegroundColor = NSColor.selectedTextColor { didSet { self.selectedCloseButtonImage = Icon.close.asImage( dimension: self.iconDimension.width, color: self.selectedForegroundColor ) } } public var selectedBackgroundColor = NSColor.selectedTextBackgroundColor public var tabSelectedIndicatorColor = NSColor.selectedTextColor public var titleFont = NSFont.systemFont(ofSize: 11) public var selectedTitleFont = NSFont.boldSystemFont(ofSize: 11) public var tabHeight = CGFloat(28) public var tabMaxWidth = CGFloat(250) public var separatorThickness = CGFloat(1) public var tabHorizontalPadding = CGFloat(4) public var tabSelectionIndicatorThickness = CGFloat(3) public var iconDimension = CGSize(width: 16, height: 16) public var tabMinWidth: CGFloat { 3 * self.tabHorizontalPadding + self.iconDimension.width + 32 } public var tabBarHeight: CGFloat { self.tabHeight } public var tabSpacing = CGFloat(-1) public var closeButtonImage: NSImage public var selectedCloseButtonImage: NSImage public init() { self.closeButtonImage = Icon.close.asImage( dimension: self.iconDimension.width, color: self.foregroundColor ) self.selectedCloseButtonImage = Icon.close.asImage( dimension: self.iconDimension.width, color: self.selectedForegroundColor ) } }
27.202899
74
0.729355
721f1916af86a2b84e7931f69024d931835b3682
433
// 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 func a{struct C{class B:c<I>{class case,
39.363636
78
0.748268
29365e367fabb95c872b515f0e0b8967f2957bd4
1,348
// // AppDelegate.swift // Prework // // Created by Bao-Tran Thai on 11/27/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.432432
179
0.744807
5b71c3ee0dc04ffae7de19c343910c0b62d031aa
1,138
// // ListaDirecciones.swift // SellerAppNetworkingWL // // Created by Luis Cuevas on 29/06/17. // Copyright © 2017 Deloitte. All rights reserved. // import Foundation import ObjectMapper public class ListaDirecciones: Mappable{ public var poblacion: String? public var telefono1: String? public var telefono2: String? public var tipoFestejado: Float? public var numExt: String? public var calle: String? public var colonia: String? public var edificio: String? public var codPos: String? public var pais: String? public var estado: String? public var municipio: String? public required init?(map: Map){ } public func mapping(map: Map){ poblacion <- map["poblacion"] telefono1 <- map["telefono1"] telefono2 <- map["telefono2"] tipoFestejado <- map["tipoFestejado"] numExt <- map["numExt"] calle <- map["calle"] colonia <- map["colonia"] edificio <- map["edificio"] codPos <- map["codPos"] pais <- map["pais"] estado <- map["estado"] municipio <- map["municipio"] } }
26.465116
51
0.62478
08fe33929bee68ee5522285924c35240bd37846d
881
// // ChildView7Controller.swift // FFNavigationBar // // Created by fewspider on 16/1/23. // Copyright © 2016年 CocoaPods. All rights reserved. // import UIKit class ChildView7Controller: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.472222
106
0.679909
e9257bfaf5799d484d03185817b344081b735d75
2,651
import Foundation import TSCBasic import TuistCore import TuistCoreTesting import TuistGraph import TuistGraphTesting import TuistSupport import XCTest @testable import TuistGenerator final class ProjectLinterTests: XCTestCase { var targetLinter: MockTargetLinter! var schemeLinter: MockSchemeLinter! var settingsLinter: MockSettingsLinter! var packageLinter: MockPackageLinter! var subject: ProjectLinter! override func setUp() { super.setUp() targetLinter = MockTargetLinter() schemeLinter = MockSchemeLinter() settingsLinter = MockSettingsLinter() packageLinter = MockPackageLinter() subject = ProjectLinter( targetLinter: targetLinter, settingsLinter: settingsLinter, schemeLinter: schemeLinter, packageLinter: packageLinter ) } override func tearDown() { super.tearDown() subject = nil settingsLinter = nil schemeLinter = nil targetLinter = nil packageLinter = nil } func test_validate_when_there_are_duplicated_targets() throws { let target = Target.test(name: "A") let project = Project.test(targets: [target, target]) let got = subject.lint(project) XCTAssertTrue(got.contains(LintingIssue(reason: "Targets A from project at \(project.path.pathString) have duplicates.", severity: .error))) } func test_lint_valid_watchTargetBundleIdentifiers() throws { // Given let app = Target.test(name: "App", product: .app, bundleId: "app") let watchApp = Target.test(name: "WatchApp", product: .watch2App, bundleId: "app.watchapp") let watchExtension = Target.test(name: "WatchExtension", product: .watch2Extension, bundleId: "app.watchapp.watchextension") let project = Project.test(targets: [app, watchApp, watchExtension]) // When let got = subject.lint(project) // Then XCTAssertTrue(got.isEmpty) } func test_lint_duplicated_options() { // Given let project = Project.test( options: [ .textSettings(.test(indentWidth: 0, tabWidth: 0)), .textSettings(.test(indentWidth: 1, tabWidth: 1)), ] ) // When let got = subject.lint(project) // Then XCTAssertTrue( got.contains( LintingIssue( reason: "Options \"textSettings\" from project at \(project.path.pathString) have duplicates.", severity: .error ) ) ) } }
30.471264
148
0.62467
5db74c7c6d16f54ff6dd87fa8547434bff37b099
4,584
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPFormTextInputTableViewCell: SPTableViewCell { let textInputView: UITextView = UITextView() var textInputViewHeight: CGFloat = 150 { didSet { self.textInputViewHeightConstraint.constant = self.textInputViewHeight } } private var textInputViewHeightConstraint: NSLayoutConstraint! override var contentViews: [UIView] { return [self.textInputView] } override var accessoryType: UITableViewCell.AccessoryType { didSet { if self.accessoryType == .disclosureIndicator { self.selectionStyle = .default } else { self.selectionStyle = .none } } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override func commonInit() { super.commonInit() self.backgroundColor = UIColor.white self.textInputView.textAlignment = .left self.textInputView.text = "" self.textInputView.font = UIFont.system(weight: .regular, size: 17) self.textInputView.translatesAutoresizingMaskIntoConstraints = false self.textInputView.showsVerticalScrollIndicator = false self.contentView.addSubview(self.textInputView) let marginGuide = contentView.layoutMarginsGuide self.textInputView.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true self.textInputView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor).isActive = true self.textInputView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true self.textInputView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true self.textInputViewHeightConstraint = self.textInputView.heightAnchor.constraint(equalToConstant: self.textInputViewHeight) self.textInputViewHeightConstraint.isActive = true self.stopLoading(animated: false) self.separatorInsetStyle = .auto self.accessoryType = .none } override func prepareForReuse() { super.prepareForReuse() self.accessoryType = .none self.textInputView.text = "" } override func layoutSubviews() { super.layoutSubviews() let xPosition: CGFloat = (self.imageView?.frame.bottomX ?? 0) + self.layoutMargins.left self.textInputView.frame = CGRect.init( x: xPosition, y: 0, width: self.frame.width - self.layoutMargins.left - self.layoutMargins.right, height: self.contentView.frame.height ) switch self.separatorInsetStyle { case .all: self.separatorInset.left = 0 case .beforeImage: if let imageView = self.imageView { self.separatorInset.left = imageView.frame.bottomY + self.layoutMargins.left } else { self.separatorInset.left = 0 } case .none: self.separatorInset.left = self.frame.width case .auto: self.separatorInset.left = self.layoutMargins.left } } }
38.521008
130
0.672557
f9d2ce1538217452adddf43eb0035031f8c21b4e
4,252
// // WindowController.swift // Alcazar // // Created by Jesse Riddle on 3/29/17. // Copyright © 2017 Orkey. All rights reserved. // import Cocoa class MainWindowController: NSWindowController, NSWindowDelegate, WindowControllerDelegate { @IBOutlet weak var palaceSearchField: PalaceSearchField! @IBAction func palaceSearchFieldAction(_ sender: Any) { //let mainViewController = self.presenting as! MainViewController //mainViewController.setPalaceHostname(hostnameTextField.stringValue) //if delegate != nil { let mainVc = self.contentViewController! as! MainViewController //let mainViewController = self.presenting as! MainViewController //mainViewController.setPalaceHostname(hostnameTextField.stringValue) //if delegate != nil { mainVc.Client!.ConnectTo(palaceUrl: palaceSearchField.stringValue) } override func windowDidLoad() { self.window?.titleVisibility = .hidden self.window?.delegate = self let mainVc = self.contentViewController! as! MainViewController mainVc.WindowControllerDelegate = self // TODO show log window at startup if necessary. // TODO also, will need to make log window a toggle at some point. //let storyboard = NSStoryboard(name: "Main", bundle: nil) //let logWc = storyboard!.instantiateController(withIdentifier: "logWindowController") as! NSWindowController //mainVc.Client!.Logger.Add(receiver: logVc.logNotifyCallback, minLogLevel: .Debug, maxLogLevel: .Whitespace) //logWc.showWindow(self) //let logSegue = NSStoryboardSegue(identifier: "logWindowSegue", source: self, destination: self) //self.prepare(for: logSegue, sender: self) self.performSegue(withIdentifier: "logWindowSegue", sender: self) } func windowWillClose(_ notification: Notification) { //NSApp.terminate(self) let vc = self.contentViewController! as! MainViewController vc.Client!.Disconnect() NSApplication.shared().terminate(self) } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier == "logWindowSegue" { let mainVc = self.contentViewController! as! MainViewController let wc = segue.destinationController as! NSWindowController let logVc = wc.contentViewController! as! LogViewController logVc.clientDelegate = mainVc mainVc.Client!.Logger.Add(receiver: logVc.logNotifyCallback, minLogLevel: .Debug, maxLogLevel: .Whitespace) // also update the textfield from store //vc.logTextField } else if segue.identifier == "userListViewSegue" { //print("userListViewSegue") // based on currently active view let mainVc = self.contentViewController! as! MainViewController let destVc = segue.destinationController as! UserListViewController destVc.view.appearance = NSAppearance(appearanceNamed: NSAppearanceNameVibrantLight, bundle: nil) destVc.tableView.appearance = NSAppearance(appearanceNamed: NSAppearanceNameVibrantLight, bundle: nil) destVc.Client = mainVc.Client! //mainVc.Client!.RoomList } else if segue.identifier == "roomListViewSegue" { //print("roomListViewSegue") let mainVc = self.contentViewController! as! MainViewController let destVc = segue.destinationController as! RoomListViewController destVc.view.appearance = NSAppearance(appearanceNamed: NSAppearanceNameVibrantLight, bundle: nil) destVc.tableView.appearance = NSAppearance(appearanceNamed: NSAppearanceNameVibrantLight, bundle: nil) destVc.Client = mainVc.Client! // based on currently active view } } func ResizeWindow(width: CGFloat, height: CGFloat) { let currentFrame = self.window!.frame let newFrame = NSRect(x: currentFrame.origin.x, y: currentFrame.origin.y, width: width, height: height + self.window!.titlebarHeight) self.window!.setFrame(newFrame, display: true) } }
47.244444
141
0.67968
e59b0928a80c80b1a99295208b353647f2ac8086
979
// // PetSwipeTests.swift // PetSwipeTests // // Created by Theresa Marquis on 9/5/18. // Copyright © 2018 Theresa Marquis. All rights reserved. // import XCTest @testable import PetSwipe class PetSwipeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.459459
111
0.635342
22e092d79c3793e4a8475b5784e2a3d981151929
556
// // String+BaseExtension.swift // FCCategorySwiftKit // // Created by 石富才 on 2020/2/1. // import Foundation extension String{ /// 剔除字符串收尾空格 public var fc_trimmingWhitespaceCharacter: String{ get{ return self.trimmingCharacters(in: CharacterSet.whitespaces) } } /// 剔除字符串收尾指定字符 /// - Parameter trimmingString: 要剔除的字符 public func fc_trimmingCustomCharacter(_ trimmingString: String) -> String{ return self.trimmingCharacters(in: CharacterSet(charactersIn: trimmingString)) } }
22.24
86
0.672662
284bca84d646330703391e27275bc6a9d638db38
1,075
// swift-tools-version:4.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "swift-decision-tree", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "SwiftDecisionTree", targets: ["SwiftDecisionTree"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "SwiftDecisionTree", dependencies: []), .testTarget( name: "SwiftDecisionTreeTests", dependencies: ["SwiftDecisionTree"]), ] )
37.068966
122
0.636279
0199edf170c4d474134ad00df490cd17c02a4d8f
641
import Quick import Nimble @testable import Stencil import Foundation class RegexOperatorSpec: QuickSpec { override func spec() { describe("Regex Operator") { it("should return captures if matched") { let regex = try! Regex(pattern: "(\\d+)(\\d+)") let result = regex ~= "1234" expect(result?.captures) == ["123", "4"] } it("should return nil if not matched") { let regex = try! Regex(pattern: "(\\d+)(\\d+)") let result = regex ~= "" expect(result).to(beNil()) } } } }
26.708333
63
0.4883
0334ab15f14ce1aa45fa7426086dd50f7100952c
2,085
// // FirstScreenPresenter.swift // testsPostsApp // // Created by Guillermo Asencio Sanchez on 23/3/21. // import Foundation protocol FirstScreenPresentationLogic { func presentData(response: FirstScreen.Data.Response) func presentSelectPost(response: FirstScreen.SelectPost.Response) } class FirstScreenPresenter: FirstScreenPresentationLogic { // MARK: - Properties weak var viewController: FirstScreenDisplayLogic? // MARK: Public func presentData(response: FirstScreen.Data.Response) { let state: FirstScreenViewState switch response.state { case .loading: state = .loading case .success(let posts, let users, let comments): state = .sucess(cellData: createTableData(posts: posts, users: users, comments: comments)) case .error: state = .error } let viewModel = FirstScreen.Data.ViewModel(state: state) viewController?.displayData(viewModel: viewModel) } func presentSelectPost(response: FirstScreen.SelectPost.Response) { let viewModel = FirstScreen.SelectPost.ViewModel() viewController?.displaySelectPost(viewModel: viewModel) } // MARK: - Private private func createTableData(posts: [PostEntity], users: [UserEntity], comments: [CommentEntity]) -> [PostTableViewCellData] { posts.map({ createTableCellData(post: $0, users: users, comments: comments) }) } private func createTableCellData(post: PostEntity, users: [UserEntity], comments: [CommentEntity]) -> PostTableViewCellData { let username = users.first(where: { $0.identifier == post.userId })?.username ?? "" let viewData = PostViewData(title: post.title, body: post.body, username: username, totalComments: comments.filter({ $0.postId == post.identifier }).count, hideTotalComments: false) return PostTableViewCellData(viewData: viewData) } }
33.629032
103
0.643165
4878e45ef3c29209ecc7ac9e20e90f325bdb763d
4,472
// // ViewController.swift // demo // // Created by deploy on 25/01/2018. // Copyright © 2018 holaspark. All rights reserved. // import UIKit import UserNotifications import MobileCoreServices import SparkPlayer import AVFoundation import SparkLib let NOTIFICATION_DELAY = 10 let AD_TAG = "https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=" struct VideoPage { var video: VideoItem var text: String } class ViewController: UIViewController { // MARK: Properties @IBOutlet weak var generateNotificationButton: UIButton! @IBOutlet weak var playerContainer: UIView! @IBOutlet weak var descriptionLabel: UILabel! var customerID: String! var info: VideoPage! var videoDescription: String! var sparkPlayer: SparkPlayer! // MARK: Actions @IBAction func onGenerateNotification(sender: UIButton){ guard sender.isEnabled else { return } sender.setTitle("loading attachment", for: UIControlState.disabled) sender.isEnabled = false // using the same customer let api = SparkAPI.getAPI(nil) api.sendPreviewNotification( info.video.getUrl(), withTitle: "Watch", withSubtitle: nil, withBody: info.video.getTitle(), withTriggerOn: UNTimeIntervalNotificationTrigger( timeInterval: TimeInterval(NOTIFICATION_DELAY), repeats: false), withBeforeSend: { (content, settings) -> Bool in print("preview successfully loaded"); // add custom user-info to use in notification response handler let info = NSMutableDictionary(dictionary: content.userInfo) info.setValue("vid12345", forKey: "custom-video-id") content.userInfo = info as! [AnyHashable : Any]; // change notification sound if (settings.soundSetting == .enabled) { content.sound = UNNotificationSound.default(); } return true }, withCompletionBlock: { (error) in if (error != nil) { print("notification request failed with error=\(error!)") } DispatchQueue.main.async { let hint = error != nil ? "scheduling failed" : "notification sent (wait \(NOTIFICATION_DELAY) sec)" sender.setTitle(hint, for: UIControlState.disabled) if (error != nil) { self.descriptionLabel.text = "Failure details: \(error!)" } } DispatchQueue.main.asyncAfter( deadline: .now()+TimeInterval(NOTIFICATION_DELAY)) { sender.isEnabled = true self.descriptionLabel.text = self.info.text } }) } override func viewDidLoad() { super.viewDidLoad() sparkPlayer = SparkPlayer(withConfig: [ "googima": ["adTagUrl": AD_TAG] ]) self.addChildViewController(sparkPlayer) self.title = info.video.getTitle() self.descriptionLabel.text = info.text print("selected video url: \(info.video.getUrl())") sparkPlayer.player = AVPlayer(url: info.video.getUrl()) playerContainer.addSubview(sparkPlayer.view) sparkPlayer.view.frame.origin = CGPoint.zero sparkPlayer.view.frame.size = playerContainer.frame.size } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // XXX alexeym: hack to disable swipe-to-back gesture which // conflicting with video slider moving from the left position self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (self.isMovingFromParentViewController) { sparkPlayer.player?.pause() sparkPlayer.player?.replaceCurrentItem(with: nil) self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true } } }
35.212598
264
0.613372
d71ef05632b60f0d451ab4f256b8ce028668b329
3,256
// Copyright 2020 Carton contributors // // 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 ArgumentParser #if canImport(Combine) import Combine #else import OpenCombine #endif import CartonHelpers import CartonKit import SwiftToolchain import TSCBasic private enum Environment: String, CaseIterable, ExpressibleByArgument { case wasmer case defaultBrowser var destination: DestinationEnvironment { switch self { case .defaultBrowser: return .browser case .wasmer: return .other } } } struct Test: ParsableCommand { static let entrypoint = Entrypoint(fileName: "test.js", sha256: testEntrypointSHA256) static let configuration = CommandConfiguration(abstract: "Run the tests in a WASI environment.") @Flag(help: "When specified, build in the release mode.") var release = false @Flag(name: .shortAndLong, help: "When specified, list all available test cases.") var list = false @Argument(help: "The list of test cases to run in the test suite.") var testCases = [String]() @Option(help: "Environment used to run the tests, either a browser, or command-line Wasm host.") private var environment = Environment.wasmer @Option( name: .shortAndLong, help: "Set the HTTP port the testing server will run on for browser environment." ) var port = 8080 @Option( name: .shortAndLong, help: "Set the location where the testing server will run. Default is `127.0.0.1`." ) var host = "127.0.0.1" func run() throws { let terminal = InteractiveWriter.stdout try Self.entrypoint.check(on: localFileSystem, terminal) let toolchain = try Toolchain(localFileSystem, terminal) let testBundlePath = try toolchain.buildTestBundle(isRelease: release, environment.destination) if environment == .wasmer { terminal.write("\nRunning the test bundle with wasmer:\n", inColor: .yellow) var wasmerArguments = ["wasmer", testBundlePath.pathString] if list { wasmerArguments.append(contentsOf: ["--", "-l"]) } else if !testCases.isEmpty { wasmerArguments.append("--") wasmerArguments.append(contentsOf: testCases) } let runner = ProcessRunner(wasmerArguments, parser: TestsParser(), terminal) try runner.waitUntilFinished() } else { try Server( with: .init( builder: nil, mainWasmPath: testBundlePath, verbose: true, skipAutoOpen: false, port: port, host: host, customIndexContent: nil, // swiftlint:disable:next force_try manifest: try! toolchain.manifest.get(), product: nil, entrypoint: Self.entrypoint ), terminal ).run() } } }
30.148148
99
0.687346
1d2ff3876f31946ee2b8a7845dc76bc5d32e866e
11,775
// // BarabaTests.swift // BarabaTests // // Created by Infostride // Copyright © Infostride. All rights reserved. // @testable import Baraba import XCTest class BarabaTests: XCTestCase { var delegate = MockBarabaDelegate() var scrollView = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 2000))) override func setUp() { delegate = MockBarabaDelegate() scrollView = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100))) scrollView.contentSize = CGSize(width: 100, height: 10_000) } func testUnsupportedConfiguration() { let baraba = Baraba(configuration: .unsupported) baraba.scrollView = scrollView baraba.delegate = delegate baraba.resume() let error = delegate.error XCTAssert(Baraba.isConfigurationSupported(.unsupported) == false) XCTAssert(baraba.isActive == false) XCTAssert(error != nil) if let error = error { if case BarabaError.unsupportedConfiguration = error { //Correct case } else { XCTFail("Expected BarabaError.unsupportedConfiguration, but got \(error)") } } else { XCTFail("error must not be nil.") } } func testScrollViewNil() { let baraba = Baraba(configuration: .mock) baraba.delegate = delegate baraba.resume() let error = delegate.error XCTAssert(baraba.isActive == false, "Baraba should not be active if scroll view is nil at resume()") XCTAssert(error == nil, "scroll view being nil does not make an error object") } func testHardwareDenied() { let baraba = Baraba(configuration: .hardwareDenied) baraba.delegate = delegate baraba.scrollView = scrollView baraba.resume() let error = delegate.error XCTAssert(baraba.isActive == false) XCTAssert(error != nil) if let error = error { if case BarabaError.cameraUnauthorized = error { //Correct case } else { XCTFail("Expected BarabaError.cameraUnauthorized, but got \(error)") } } else { XCTFail("error must not be nil.") } } func testSingleScroll() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.delegate = delegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(0_500_000) delegate.trackerDidEndTrackingFace(mockTracker) usleep(0_500_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 2) XCTAssert(baraba.isActive == true) XCTAssert(delegate.numberOfScrollStarts == 1, "numberOfScrollStarts should be 1, instead of \(delegate.numberOfScrollStarts)") XCTAssert(delegate.numberOfScrollStops == 1, "numberOfScrollStarts should be 1, instead of \(delegate.numberOfScrollStarts)") } func testScrollSpeed() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.delegate = delegate baraba.preferredScrollSpeed = 600 let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(2_000_000) delegate.trackerDidEndTrackingFace(mockTracker) usleep(0_050_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 3) XCTAssert(scrollView.contentOffset.y > 1200*0.9, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(scrollView.contentOffset.y < 1200*1.1, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(delegate.numberOfScrollStarts == 1, "numberOfScrollStarts should be 1, instead of \(delegate.numberOfScrollStarts)") XCTAssert(delegate.numberOfScrollStops == 1, "numberOfScrollStarts should be 1, instead of \(delegate.numberOfScrollStarts)") } func testTrackerFail() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.delegate = delegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.tracker(mockTracker, didFailWithError: MockError()) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 1) if let error = delegate.error, case let BarabaError.cameraFailed(underlying) = error { XCTAssert(underlying is MockError, "error: \(error)") XCTAssert(delegate.numberOfScrollStarts == 0) XCTAssert(delegate.numberOfScrollStops == 0) } else { XCTFail("error should not be nil, and be BarabaError.cameraFailed. (\(String(describing: delegate.error)))") } } func testInterruptionWhileLooking() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.preferredScrollSpeed = 240 baraba.delegate = delegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(1_500_000) delegate.trackerWasInterrupted(mockTracker) usleep(0_500_000) delegate.trackerInterruptionEnded(mockTracker) usleep(1_000_000) delegate.trackerDidEndTrackingFace(mockTracker) usleep(0_500_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 5) XCTAssert(baraba.isActive) XCTAssert(scrollView.contentOffset.y > 600*0.9, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(scrollView.contentOffset.y < 600*1.1, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(delegate.numberOfScrollStarts == 2, "numberOfScrollStarts should be 2, instead of \(delegate.numberOfScrollStarts)") XCTAssert(delegate.numberOfScrollStops == 2, "numberOfScrollStops should be 2, instead of \(delegate.numberOfScrollStarts)") } func testInterruptionWhileNotLooking() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.delegate = delegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(2_000_000) delegate.trackerDidEndTrackingFace(mockTracker) delegate.trackerWasInterrupted(mockTracker) usleep(0_050_000) delegate.trackerInterruptionEnded(mockTracker) usleep(0_050_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 3) XCTAssert(baraba.isActive) XCTAssert(scrollView.contentOffset.y > 360*0.9, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(scrollView.contentOffset.y < 360*1.1, "Scroll view's contentOffset is \(scrollView.contentOffset.y)") XCTAssert(delegate.numberOfScrollStarts == 1, "numberOfScrollStarts should be 1, instead of \(delegate.numberOfScrollStarts)") XCTAssert(delegate.numberOfScrollStops == 1, "numberOfScrollStops should be 1, instead of \(delegate.numberOfScrollStarts)") } func testBarabaDelegateExtension() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView let emptyDelegate = EmptyBarabaDelegate() baraba.delegate = emptyDelegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(0_500_000) delegate.trackerDidEndTrackingFace(mockTracker) usleep(0_050_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 3) baraba.pause() let testExpectation2 = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.tracker(mockTracker, didFailWithError: MockError()) usleep(0_500_000) testExpectation2.fulfill() } baraba.resume() waitForExpectations(timeout: 1) XCTAssert(true) } func testResumeOnActiveBaraba() { let baraba = Baraba(configuration: .mock) baraba.scrollView = scrollView baraba.delegate = delegate baraba.resume() XCTAssert(baraba.isActive == true) XCTAssert(delegate.error == nil) baraba.resume() XCTAssert(baraba.isActive == true) XCTAssert(delegate.error == nil) } func testRemoveScrollView() { let mockTracker = MockFaceTracker() let config = BarabaConfiguration(tracker: mockTracker) let baraba = Baraba(configuration: config) baraba.scrollView = scrollView baraba.delegate = delegate let testExpectation = expectation(description: "Baraba expectation") mockTracker.action = { delegate in delegate.trackerDidStartTrackingFace(mockTracker) usleep(0_500_000) baraba.scrollView = nil usleep(0_100_000) testExpectation.fulfill() } baraba.resume() waitForExpectations(timeout: 1) XCTAssert(baraba.isActive == false) XCTAssert(baraba.isScrolling == false) } func testPreferredScrollSpeed() { let baraba = Baraba(configuration: .mock) baraba.preferredScrollSpeed = 100 XCTAssert(baraba.actualScrollSpeed == 120) baraba.preferredScrollSpeed = 150 XCTAssert(baraba.actualScrollSpeed == 180) baraba.preferredScrollSpeed = -10 XCTAssert(baraba.actualScrollSpeed == 60) } } struct MockError: Error {}
35.466867
134
0.616221
911cd864b4b57c6429b78a32159b43a5b51c6735
2,351
// // SceneDelegate.swift // Magic 8 Ball // // Created by Thyme Nawaphanarat on 28/11/19. // Copyright © 2019 Thyme. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.537037
147
0.713313
ebb234b98010bb94b384287bc5aa81e4fa5697e6
3,213
import Dispatch import XCTest import CBGPromise class PromiseTests: XCTestCase { var subject: Promise<String>! override func setUp() { subject = Promise<String>() } func testCallbackBlockRegisteredBeforeResolution() { var result: String! subject.future.then { r in result = r } subject.resolve("My Special Value") XCTAssertEqual(result, "My Special Value") } func testCallbackBlockRegisteredAfterResolution() { var result: String! subject.resolve("My Special Value") subject.future.then { r in result = r } XCTAssertEqual(result, "My Special Value") } func testValueAccessAfterResolution() { subject.resolve("My Special Value") XCTAssertEqual(subject.future.value, "My Special Value") } func testWaitingForResolution() { let queue = DispatchQueue(label: "test") queue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(100)) { self.subject.resolve("My Special Value") } let receivedValue = subject.future.wait() XCTAssertEqual(subject.future.value, "My Special Value") XCTAssertEqual(receivedValue, subject.future.value) } func testMultipleCallbacks() { var valA: String? var valB: String? subject.future.then { v in valA = v } subject.future.then { v in valB = v } subject.resolve("My Special Value") XCTAssertEqual(valA, "My Special Value") XCTAssertEqual(valB, "My Special Value") } func testMapReturnsNewFuture() { var mappedValue: Int? let mappedFuture = subject.future.map { str -> Int? in return Int(str) } mappedFuture.then { num in mappedValue = num } subject.resolve("123") XCTAssertEqual(mappedValue, 123) } func testMapAllowsChaining() { var mappedValue: Int? let mappedPromise = Promise<Int>() let mappedFuture = subject.future.map { str -> Future<Int> in return mappedPromise.future } mappedFuture.then { num in mappedValue = num } subject.resolve("Irrelevant") mappedPromise.resolve(123) XCTAssertEqual(mappedValue, 123) } func testWhenWaitsUntilResolution() { let firstPromise = Promise<String>() let secondPromise = Promise<String>() let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future]) XCTAssertNil(receivedFuture.value) firstPromise.resolve("hello") XCTAssertNil(receivedFuture.value) secondPromise.resolve("goodbye") XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"]) } func testWhenPreservesOrder() { let firstPromise = Promise<String>() let secondPromise = Promise<String>() let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future]) secondPromise.resolve("goodbye") firstPromise.resolve("hello") XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"]) } }
24.715385
94
0.619048
db8f9c234a9802c730ffe5d58f2e73ad9d314cfd
2,504
// // AccountInvitationPinCodeEntryViewController.swift // i2app // // Created by Arcus Team on 5/19/16. /* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // import UIKit import Cornea class AccountInvitationPinCodeEntryViewController: ArcusPinCodeViewController, RegistrationConfigHolder { internal var personModel: PersonModel? internal var pinCode: String? internal var config: RegistrationConfig? class func create(_ config: RegistrationConfig) -> AccountInvitationPinCodeEntryViewController? { let storyboard: UIStoryboard = UIStoryboard.init(name: "CreateAccount", bundle: nil) let vc = storyboard .instantiateViewController(withIdentifier: "AccountInvitationPinCodeEntryViewController") as? AccountInvitationPinCodeEntryViewController vc?.config = config return vc } // MARK: View LifeCycle override func viewDidLoad() { super.viewDidLoad() self.navBar(withCloseButtonAndTitle: NSLocalizedString("Pin Code", comment: "")) self.navigationController?.view.createBlurredBackground(self.presentingViewController) self.view.backgroundColor = self.navigationController?.view.backgroundColor } // MARK: IBActions @IBAction override func numericButtonPressed(_ sender: UIButton!) { super.numericButtonPressed(sender) if self.enteredPin.count == 4 { self.pinCode = self.enteredPin self.performSegue(withIdentifier: "AccountInvitationConfirmPinCodeSegue", sender: self) } } // MARK: PrepareForSegue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AccountInvitationConfirmPinCodeSegue" { if let confirmPinViewController = segue.destination as? AccountInvitationPinCodeConfirmationViewController { confirmPinViewController.personModel = self.personModel confirmPinViewController.pinCode = self.pinCode confirmPinViewController.config = self.config } } } }
33.386667
99
0.753594
8a3e9f06420f1f3e7f8352b43b428f8b88ccbf89
1,265
// // Hangman_GameUITests.swift // Hangman-GameUITests // // Created by Sohardh Chobera on 22/06/18. // Copyright © 2018 Sohardh Chobera. All rights reserved. // import XCTest class Hangman_GameUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.189189
182
0.667194
e2dea5cbdfe6300a0c5277b491776726b2e89f15
164
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(CareKitMongoDBTests.allTests), ] } #endif
16.4
47
0.682927
8f9d04cdc67e82e3f740aebc30ac08a1b7686343
1,474
// // KVOChange.swift // Player // // Created by Fredrik Sjöberg on 2017-04-07. // Copyright © 2017 emp. All rights reserved. // import Foundation internal struct KVOChange { /// The kind of the change. /// /// See also `NSKeyValueChangeKindKey` internal var kind: NSKeyValueChange? { return (self.rawDict?[.kindKey] as? UInt).flatMap(NSKeyValueChange.init) } /// The old value from the change. /// /// See also `NSKeyValueChangeOldKey` internal var old: Any? { return self.rawDict?[.oldKey] } /// The new value from the change. /// /// See also `NSKeyValueChangeNewKey` internal var new: Any? { return self.rawDict?[.newKey] } /// Whether this callback is being sent prior to the change. /// /// See also `NSKeyValueChangeNotificationIsPriorKey` internal var isPrior: Bool { return self.rawDict?[.notificationIsPriorKey] as? Bool ?? false } /// The indexes of the inserted, removed, or replaced objects when relevant. /// /// See also `NSKeyValueChangeIndexesKey` internal var indexes: IndexSet? { return self.rawDict?[.indexesKey] as? IndexSet } /// The raw change dictionary passed to `observeValueForKeyPath(_:ofObject:change:context:)`. internal let rawDict: [NSKeyValueChangeKey: Any]? internal init(rawDict: [NSKeyValueChangeKey: Any]?) { self.rawDict = rawDict } }
27.296296
97
0.636364
87858a7ecb7585c618073159fe3efbf56e13f5bc
21,570
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -enable-swift-name-lookup-tables -I %S/Inputs/custom-modules %s -verify // REQUIRES: objc_interop import AppKit import AVFoundation import objc_ext import TestProtocols import ObjCParseExtras import ObjCParseExtrasToo import ObjCParseExtrasSystem func markUsed<T>(t: T) {} func testAnyObject(obj: AnyObject) { _ = obj.nsstringProperty } // Construction func construction() { _ = B() } // Subtyping func treatBAsA(b: B) -> A { return b } // Instance method invocation func instanceMethods(b: B) { var i = b.method(1, withFloat:2.5) i = i + b.method(1, withDouble:2.5) // BOOL b.setEnabled(true) // SEL b.performSelector("isEqual:", withObject:b) if let result = b.performSelector("getAsProto", withObject:nil) { _ = result.takeUnretainedValue() } // Renaming of redundant parameters. b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}} b.performAdd(1, withValue:2, withValue:4, withValue2: 3) b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }} // Both class and instance methods exist. b.description b.instanceTakesObjectClassTakesFloat(b) b.instanceTakesObjectClassTakesFloat(2.0) // expected-error{{cannot convert value of type 'Double' to expected argument type 'AnyObject!'}} // Instance methods with keyword components var obj = NSObject() var prot = NSObjectProtocol.self b.`protocol`(prot, hasThing:obj) b.doThing(obj, `protocol`: prot) } // Class method invocation func classMethods(b: B, other: NSObject) { var i = B.classMethod() i += B.classMethod(1) i += B.classMethod(1, withInt:2) i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}} // Both class and instance methods exist. B.description() B.instanceTakesObjectClassTakesFloat(2.0) B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}} // Call an instance method of NSObject. var c: AnyClass = B.myClass() // no-warning c = b.myClass() // no-warning } // Instance method invocation on extensions func instanceMethodsInExtensions(b: B) { b.method(1, onCat1:2.5) b.method(1, onExtA:2.5) b.method(1, onExtB:2.5) b.method(1, separateExtMethod:3.5) let m1 = b.method:onCat1: m1(1, onCat1: 2.5) let m2 = b.method:onExtA: m2(1, onExtA: 2.5) let m3 = b.method:onExtB: m3(1, onExtB: 2.5) let m4 = b.method:separateExtMethod: m4(1, separateExtMethod: 2.5) } func dynamicLookupMethod(b: AnyObject) { // FIXME: Syntax will be replaced. if let m5 = b.method:separateExtMethod: { m5(1, separateExtMethod: 2.5) } } // Properties func properties(b: B) { var i = b.counter b.counter = i + 1 i = i + b.readCounter b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}} b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}} // Informal properties in Objective-C map to methods, not variables. b.informalProp() // An informal property cannot be made formal in a subclass. The // formal property is simply ignored. b.informalMadeFormal() b.informalMadeFormal = i // expected-error{{cannot assign to property: 'b' is a 'let' constant}} b.setInformalMadeFormal(5) b.overriddenProp = 17 // Dynamic properties. var obj : AnyObject = b var optStr = obj.nsstringProperty if optStr != nil { var s : String = optStr! } // Properties that are Swift keywords var prot = b.`protocol` } // Construction. func newConstruction(a: A, aproxy: AProxy) { var b : B = B() b = B(int: 17) b = B(int:17) b = B(double:17.5, 3.14159) b = B(BBB:b) b = B(forWorldDomination:()) b = B(int: 17, andDouble : 3.14159) b = B.newWithA(a) B.alloc()._initFoo() b.notAnInit() // init methods are not imported by themselves. b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}} // init methods on non-NSObject-rooted classes AProxy(int: 5) // expected-warning{{unused}} } // Indexed subscripting func indexedSubscripting(b: B, idx: Int, a: A) { b[idx] = a _ = b[idx] as! A } // Keyed subscripting func keyedSubscripting(b: B, idx: A, a: A) { b[a] = a var a2 = b[a] as! A let dict = NSMutableDictionary() dict[NSString()] = a let value = dict[NSString()] dict[nil] = a // expected-error {{nil is not compatible with expected argument type 'NSCopying'}} let q = dict[nil] // expected-error {{nil is not compatible with expected argument type 'NSCopying'}} _ = q } // Typed indexed subscripting func checkHive(hive: Hive, b: Bee) { let b2 = hive.bees[5] as Bee b2.buzz() } // Protocols func testProtocols(b: B, bp: BProto) { var bp2 : BProto = b var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}} bp.method(1, withFloat:2.5) bp.method(1, withDouble:2.5) // expected-error{{incorrect argument label in call (have '_:withDouble:', expected '_:withFloat:')}} {{16-26=withFloat}} bp2 = b.getAsProto() var c1 : Cat1Proto = b var bcat1 = b.getAsProtoWithCat() c1 = bcat1 bcat1 = c1 // expected-error{{cannot assign value of type 'Cat1Proto' to type 'protocol<BProto, Cat1Proto>!'}} } // Methods only defined in a protocol func testProtocolMethods(b: B, p2m: P2.Type) { b.otherMethod(1, withFloat:3.14159) b.p2Method() b.initViaP2(3.14159, second:3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}} // Imported constructor. var b2 = B(viaP2: 3.14159, second:3.14159) p2m.init(viaP2:3.14159, second: 3.14159) } func testId(x: AnyObject) { x.performSelector!("foo:", withObject: x) x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4) x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4) x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4) } class MySubclass : B { // Override a regular method. override func anotherMethodOnB() {} // Override a category method override func anotherCategoryMethod() {} } func getDescription(array: NSArray) { array.description } // Method overriding with unfortunate ordering. func overridingTest(srs: SuperRefsSub) { let rs : RefedSub rs.overridden() } func almostSubscriptableValueMismatch(as1: AlmostSubscriptable, a: A) { as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}} } func almostSubscriptableKeyMismatch(bc: BadCollection, key: NSString) { // FIXME: We end up importing this as read-only due to the mismatch between // getter/setter element types. var _ : AnyObject = bc[key] } func almostSubscriptableKeyMismatchInherited(bc: BadCollectionChild, key: String) { var value : AnyObject = bc[key] // no-warning, inherited from parent bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } func almostSubscriptableKeyMismatchInherited(roc: ReadOnlyCollectionChild, key: String) { var value : AnyObject = roc[key] // no-warning, inherited from parent roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } // Use of 'Class' via dynamic lookup. func classAnyObject(obj: NSObject) { obj.myClass().description!() } // Protocol conformances class Wobbler : NSWobbling { // expected-note{{candidate is not '@objc', but protocol requires it}} {{7-7=@objc }} // expected-error@-1{{type 'Wobbler' does not conform to protocol 'NSWobbling'}} @objc func wobble() { } func returnMyself() -> Self { return self } // expected-note{{candidate is not '@objc', but protocol requires it}} {{3-3=@objc }} } extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}} } @objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{Objective-C method 'init' provided by implicit initializer 'init()' does not match the requirement's selector ('initWithWobble:')}} func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}} } func optionalMemberAccess(w: NSWobbling) { w.wobble() w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}} var x: AnyObject = w[5] // expected-error{{value of optional type 'AnyObject!?' not unwrapped; did you mean to use '!' or '?'?}} {{26-26=!}} } func protocolInheritance(s: NSString) { var _: NSCoding = s } func ivars(hive: Hive) { var d = hive.bees.description hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}} } class NSObjectable : NSObjectProtocol { @objc var description : String { return "" } @objc func conformsToProtocol(_: Protocol) -> Bool { return false } @objc func isKindOfClass(aClass: AnyClass) -> Bool { return false } } // Properties with custom accessors func customAccessors(hive: Hive, bee: Bee) { markUsed(hive.makingHoney) markUsed(hive.isMakingHoney()) // expected-error{{value of type 'Hive' has no member 'isMakingHoney'}} hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}} hive.`guard`.description // okay hive.`guard`.description! // no-warning hive.`guard` = bee // no-warning } // instancetype/Dynamic Self invocation. func testDynamicSelf(queen: Bee, wobbler: NSWobbling) { var hive = Hive() // Factory method with instancetype result. var hive1 = Hive(queen: queen) hive1 = hive hive = hive1 // Instance method with instancetype result. var hive2 = hive.visit() hive2 = hive hive = hive2 // Instance method on a protocol with instancetype result. var wobbler2 = wobbler.returnMyself() var wobbler: NSWobbling = wobbler2 wobbler2 = wobbler // Instance method on a base class with instancetype result, called on the // class itself. // FIXME: This should be accepted. // FIXME: The error is lousy, too. let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error{{missing argument for parameter #1 in call}} } func testRepeatedProtocolAdoption(w: NSWindow) { w.description } class ProtocolAdopter1 : FooProto { @objc var bar: CInt // no-warning init() { bar = 5 } } class ProtocolAdopter2 : FooProto { @objc var bar: CInt { get { return 42 } set { /* do nothing! */ } } } class ProtocolAdopterBad1 : FooProto { // expected-error{{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}} @objc var bar: Int = 0 // expected-note{{candidate has non-matching type 'Int'}} } class ProtocolAdopterBad2 : FooProto { // expected-error{{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}} let bar: CInt = 0 // expected-note{{candidate is not settable, but protocol requires it}} } class ProtocolAdopterBad3 : FooProto { // expected-error{{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}} var bar: CInt { // expected-note{{candidate is not settable, but protocol requires it}} return 42 } } @objc protocol RefinedFooProtocol : FooProto {} func testPreferClassMethodToCurriedInstanceMethod(obj: NSObject) { // FIXME: We shouldn't need the ": Bool" type annotation here. // <rdar://problem/18006008> let _: Bool = NSObject.isEqual(obj) _ = NSObject.isEqual(obj) as (NSObject!) -> Bool // no-warning } func testPropertyAndMethodCollision(obj: PropertyAndMethodCollision, rev: PropertyAndMethodReverseCollision) { obj.object = nil obj.object(obj, doSomething:"action") rev.object = nil rev.object(rev, doSomething:"action") var value: AnyObject = obj.protoProp() value = obj.protoPropRO() _ = value } func testSubscriptAndPropertyRedeclaration(obj: SubscriptAndProperty) { _ = obj.x obj.x = 5 obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}} obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testSubscriptAndPropertyWithProtocols(obj: SubscriptAndPropertyWithProto) { _ = obj.x obj.x = 5 obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testProtocolMappingSameModule(obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) { markUsed(p.enablePostProcessing) markUsed(obj.enablePostProcessing) _ = obj.backgroundColor } func testProtocolMappingDifferentModules(obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) { markUsed(p.thisIsTheProto) markUsed(obj.thisClassHasAnAwfulName) let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}} _ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}} _ = ObjCParseExtrasToo.ProtoInHelper() _ = ObjCParseExtrasTooHelper.ClassInHelper() _ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}} } func testProtocolClassShadowing(obj: ClassInHelper, p: ProtoInHelper) { let _: ObjCParseExtrasToo.ClassInHelper = obj let _: ObjCParseExtrasToo.ProtoInHelper = p } func testDealloc(obj: NSObject) { // dealloc is subsumed by deinit. // FIXME: Special-case diagnostic in the type checker? obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}} } func testConstantGlobals() { markUsed(MAX) markUsed(SomeImageName) markUsed(SomeNumber.description) MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}} SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}} SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}} } func testWeakVariable() { let _: AnyObject = globalWeakVar } class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}} @objc func getObject() -> AnyObject { return self } } func testNullarySelectorPieces(obj: AnyObject) { obj.foo(1, bar: 2, 3) // no-warning obj.foo(1, 2, bar: 3) // expected-error{{cannot call value of non-function type 'AnyObject?!'}} } func testFactoryMethodAvailability() { _ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}} } func testRepeatedMembers(obj: RepeatedMembers) { obj.repeatedMethod() } // rdar://problem/19726164 class FooDelegateImpl : NSObject, FooDelegate { var _started = false var started: Bool { @objc(isStarted) get { return _started } set { _started = newValue } } } class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto { var foo: AnyObject? // no errors about conformance var bar: AnyObject? // no errors about conformance } func testUnusedResults(ur: UnusedResults) { _ = ur.producesResult() ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}} } func testCStyle() { ExtraSelectors.cStyle(0, 1, 2) // expected-error{{type 'ExtraSelectors' has no member 'cStyle'}} } func testProtocolQualified(obj: CopyableNSObject, cell: CopyableSomeCell, plainObj: NSObject, plainCell: SomeCell) { _ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = obj as NSObjectProtocol _ = obj as NSCopying _ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = cell as NSObject _ = cell as NSObjectProtocol _ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}} _ = cell as SomeCell _ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}} _ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe. } extension Printing { func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } static func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } } // <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated. func testSetInitializers() { let a: [AnyObject] = [NSObject()] let _ = NSCountedSet(array: a) let _ = NSMutableSet(array: a) } func testNSUInteger(obj: NSUIntegerTests, uint: UInt, int: Int) { obj.consumeUnsigned(uint) // okay obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(uint, andAnother: int) // okay do { let x = obj.unsignedProducer() let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.unsignedProducer(uint, fromCount: int) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.normalProducer(int, fromUnsigned: uint) let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} } let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} do { testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = testUnsigned(uint, uint) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } // NSNumber NSNumber(unsignedInteger: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let num = NSNumber(unsignedInteger: uint) let _: String = num.unsignedIntegerValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} }
36.435811
214
0.705239
abf1845ff0606b5977f32dc6db5458445a4f7bfc
766
/* Copyright (c) 2017 Mastercard Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation public enum HTTPMethod: String { case get = "GET" case put = "PUT" case post = "POST" case delete = "DELETE" case head = "HEAD" case trace = "TRACE" }
28.37037
73
0.725849
87bea4cf8b33b7f84fcc309e370cf238ec70c406
1,215
// // 🦠 Corona-Warn-App // #if !RELEASE /// App Feature provider decorator to read device time check from store (used for the debug menu) /// class AppFeatureDeviceTimeCheckDecorator: AppFeatureProviding { // MARK: - Init init( _ decorator: AppFeatureProviding, store: AppFeaturesStoring ) { self.decorator = decorator self.store = store } // MARK: - Protocol AppFeaturesProviding func value(for appFeature: SAP_Internal_V2_ApplicationConfigurationIOS.AppFeature) -> Bool { guard appFeature == .disableDeviceTimeCheck, store.dmKillDeviceTimeCheck else { return decorator.value(for: appFeature) } return true } // MARK: - Private private let decorator: AppFeatureProviding private let store: AppFeaturesStoring // mock for testing static func mock( store: AppFeaturesStoring & AppConfigCaching & DeviceTimeCheckStoring, config: SAP_Internal_V2_ApplicationConfigurationIOS = SAP_Internal_V2_ApplicationConfigurationIOS() ) -> AppFeatureProviding { let featureProvider = AppFeatureProvider( appConfigurationProvider: CachedAppConfigurationMock(with: config, store: store) ) return AppFeatureDeviceTimeCheckDecorator(featureProvider, store: store) } } #endif
25.3125
101
0.769547
22b33d61bd5cec0ec18a2f75c6df775fe795cd0e
1,643
// // MockingjayTests.swift // MockingjayTests // // Created by Kyle Fuller on 21/01/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation import XCTest import Mockingjay func toString(_ item:AnyClass) -> String { return "\(item)" } class MockingjaySessionTests: XCTestCase { override func setUp() { super.setUp() } func testEphemeralSessionConfigurationIncludesProtocol() { let configuration = URLSessionConfiguration.ephemeral let protocolClasses = (configuration.protocolClasses!).map(toString) XCTAssertEqual(protocolClasses.first!, "MockingjayProtocol") } func testDefaultSessionConfigurationIncludesProtocol() { let configuration = URLSessionConfiguration.default let protocolClasses = (configuration.protocolClasses!).map(toString) XCTAssertEqual(protocolClasses.first!, "MockingjayProtocol") } func testURLSession() { let expectation = self.expectation(description: "MockingjaySessionTests") let stubbedError = NSError(domain: "Mockingjay Session Tests", code: 0, userInfo: nil) stub(everything, failure(stubbedError)) let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) session.dataTask(with: URL(string: "https://httpbin.org/")!, completionHandler: { data, response, error in DispatchQueue.main.async { XCTAssertNotNil(error) XCTAssertEqual((error as? NSError)?.domain, "Mockingjay Session Tests") expectation.fulfill() } }) .resume() waitForExpectations(timeout: 5) { error in XCTAssertNil(error, "\(error)") } } }
29.339286
110
0.726719
fc1b1c37ccaf0b81feef00edbb5835aa384ea9ed
3,199
// // ViewController.swift // Flix // // Created by Sakib Ahmed on 2/18/22. // import UIKit import AlamofireImage class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var movies = [[String:Any]]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self // Do any additional setup after loading the view. let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let error = error { print(error.localizedDescription) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] self.movies = dataDictionary["results"] as! [[String:Any]] self.tableView.reloadData() print(dataDictionary) // TODO: Get the array of movies // TODO: Store the movies in a property to use elsewhere // TODO: Reload your table view data } } task.resume() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCellTableViewCell") as! MovieCellTableViewCell let movie = movies[indexPath.row] let title = movie["title"] as! String let synopsis = movie["overview"] as! String cell.titleLabel.text = title cell.synopsisLabel.text = synopsis let baseUrl = "https://image.tmdb.org/t/p/w185" let posterPath = movie["poster_path"] as! String let posterUrl = URL(string: baseUrl + posterPath) cell.posterView.af.setImage(withURL: posterUrl!) return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print("Loading details") //Find selected movie let cell = sender as! UITableViewCell let indexPath = tableView.indexPath(for: cell)! let movie = movies[indexPath.row] //Pass the selected movie to the details view controller let detailsViewController = segue.destination as! MovieDetailsViewController detailsViewController.movie = movie tableView.deselectRow(at: indexPath, animated: true) } }
33.673684
121
0.600813
fea4595be02181bc1ae793d9220d9e7731979bd5
216
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d { enum A { deinit { [ ( { class case ,
18
87
0.726852
e0720e1b006efc4e268b56b6de3376b8012e8401
981
/* * Copyright (c) 2016 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 do { try Live.run(withArguments: ProcessInfo.processInfo.arguments) } catch { error.print() }
32.7
66
0.730887
f9587e8349a5ca5b0ef2e2245628bf4c1bf82ba6
632
// // TestHelper.swift // MonalUITests // // Created by Friedrich Altheide on 06.03.21. // Copyright © 2021 Monal.im. All rights reserved. // import Foundation func randomPassword() -> String { let alphabet: NSString = "qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM1234567890!§$%&/()=?,.-;:_*'^" var password: String = "" let passwordLen = Int.random(in: 20..<100) for _ in 0 ..< passwordLen { var charElement = alphabet.character(at: Int(arc4random_uniform(UInt32(alphabet.length)))) password += NSString(characters: &charElement, length: 1) as String } return password }
25.28
112
0.672468
380138e67639b3163d9428f8e99dcf8fa830be6c
1,188
// // PokemonListViewModel.swift // MVVM // // Created by Julian Arias Maetschl on 11-01-21. // import Combine protocol PokemonListViewModelProtocol { var pokemons: [Pokemon] { get set } var selectedFilter: PokemonType { get set } func clearFilter() func filterBy(_ filter: PokemonType) } class PokemonListViewModel: ObservableObject, PokemonListViewModelProtocol { // MARK: Private objects private var model: PokemonListModelProtocol // MARK: Published objects @Published var pokemons: [Pokemon] // MARK: Trigger objects var selectedFilter: PokemonType = .none { didSet { switch selectedFilter { case .none: pokemons = model.pokemons default: pokemons = model.pokemons.filter({ $0.type == selectedFilter }) } } } // MARK: Init init(model: PokemonListModelProtocol = PokemonListModel()) { self.model = model self.pokemons = model.pokemons } // MARK: Methods func clearFilter() { selectedFilter = .none } func filterBy(_ filter: PokemonType) { selectedFilter = .fire } }
22
79
0.619529
e85459744e28fd3c550a20bc88ab9a0af50a5475
634
// // Crosslisting.swift // RedRoster // // Created by Daniel Li on 7/19/16. // Copyright © 2016 dantheli. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON class Crosslisting: Object { dynamic var subject: String = "" dynamic var number: Int = 0 static func create(_ json: JSON) -> Crosslisting { let crosslisting = Crosslisting() crosslisting.subject = json["subject"].stringValue crosslisting.number = Int(json["catalogNbr"].stringValue) ?? 0 return crosslisting } var shortHand: String { return "\(subject) \(number)" } }
22.642857
70
0.64511
e62a84918d430b1d67dc4b706a7d8376fde14201
5,607
// // BuildCommand.swift // Deli // import Foundation import Commandant import Result struct BuildCommand: CommandProtocol { let verb = "build" let function = "Build the Dependency Graph." func run(_ options: BuildOptions) -> Result<(), CommandError> { Logger.isVerbose = options.isVerbose let configuration = Configuration() let configure: Config if let project = options.project { guard let config = configuration.getConfig(project: project, scheme: options.scheme, output: options.output) else { return .failure(.failedToLoadConfigFile) } configure = config } else { guard options.scheme == nil, options.output == nil else { return .failure(.mustBeUsedWithProjectArguments) } guard let config = configuration.getConfig(configPath: options.configFile) else { return .failure(.failedToLoadConfigFile) } configure = config } guard configure.target.count > 0 else { Logger.log(.warn("No targets are active.", nil)) return .success(()) } for target in configure.target { guard let info = configure.config[target] else { Logger.log(.warn("Target not found: `\(target)`", nil)) continue } Logger.log(.info("Set Target `\(target)`")) let outputFile: String let className: String if info.className != nil { className = configuration.getClassName(info: info) outputFile = configuration.getOutputPath(info: info, fileName: "\(className).swift") } else { outputFile = configuration.getOutputPath(info: info) className = configuration.getClassName(info: info) } guard let sourceFiles = try? configuration.getSourceList(info: info) else { continue } if sourceFiles.count == 0 { Logger.log(.warn("No source files for processing.", nil)) } Logger.log(.debug("Source files:")) for source in sourceFiles { Logger.log(.debug(" - \(source)")) } let parser = Parser([ ComponentParser(), ConfigurationParser(), AutowiredParser(), LazyAutowiredParser(), AutowiredFactoryParser(), LazyAutowiredFactoryParser(), InjectParser() ]) let corrector = Corrector([ QualifierCorrector(parser: parser), ScopeCorrector(parser: parser), NotImplementCorrector(parser: parser) ]) let validator = Validator([ FactoryReferenceValidator(parser: parser), CircularDependencyValidator(parser: parser) ]) do { let results = try validator.run( try corrector.run( try parser.run(sourceFiles) ) ) let outputData = try SourceGenerator(className: className, results: results).generate() let url = URL(fileURLWithPath: outputFile) var isDirectory: ObjCBool = false if FileManager.default.fileExists(atPath: outputFile, isDirectory: &isDirectory), isDirectory.boolValue { Logger.log(.error("Cannot overwrite a directory with an output file: \(outputFile)", nil)) throw CommandError.cannotOverwriteDirectory } try? FileManager.default.removeItem(at: url) try outputData.write(to: url, atomically: false, encoding: .utf8) Logger.log(.info("Generate file: \(outputFile)")) } catch let error { return .failure(.runner(error)) } Logger.log(.newLine) } return .success(()) } } struct BuildOptions: OptionsProtocol { let configFile: String? let project: String? let scheme: String? let output: String? let isVerbose: Bool static func create(configFile: String?) -> (_ project: String?) -> (_ scheme: String?) -> (_ output: String?) -> (_ isVerbose: Bool) -> BuildOptions { return { project in { scheme in { output in { isVerbose in self.init(configFile: configFile, project: project, scheme: scheme, output: output, isVerbose: isVerbose) }}}} } static func evaluate(_ mode: CommandMode) -> Result<BuildOptions, CommandantError<CommandError>> { return create <*> mode <| Option( key: "config", defaultValue: nil, usage: "the path of Deli's configuration file" ) <*> mode <| Option( key: "project", defaultValue: nil, usage: "the path of project file" ) <*> mode <| Option( key: "scheme", defaultValue: nil, usage: "using build scheme name" ) <*> mode <| Option( key: "output", defaultValue: nil, usage: "the path of output file" ) <*> mode <| Option( key: "verbose", defaultValue: false, usage: "turn on verbose logging" ) } }
36.647059
154
0.529695
79e420b018b302772242e8b22e46a5bb4301027b
5,234
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public final class SHA1: DigestType { static let digestLength: Int = 20 // 160 / 8 static let blockSize: Int = 64 fileprivate static let hashInitialValue: ContiguousArray<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash: ContiguousArray<UInt32> = SHA1.hashInitialValue public init() { } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash hh: inout ContiguousArray<UInt32>) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into eighty 32-bit words: let M = UnsafeMutablePointer<UInt32>.allocate(capacity: 80) M.initialize(repeating: 0, count: 80) defer { M.deinitialize(count: 80) M.deallocate() } for x in 0..<80 { switch x { case 0...15: let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size M[x] = UInt32(bytes: chunk, fromIndex: start) break default: M[x] = rotateLeft(M[x - 3] ^ M[x - 8] ^ M[x - 14] ^ M[x - 16], by: 1) break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] // Main loop for j in 0...79 { var f: UInt32 = 0 var k: UInt32 = 0 switch j { case 0...19: f = (B & C) | ((~B) & D) k = 0x5a827999 break case 20...39: f = B ^ C ^ D k = 0x6ed9eba1 break case 40...59: f = (B & C) | (B & D) | (C & D) k = 0x8f1bbcdc break case 60...79: f = B ^ C ^ D k = 0xca62c1d6 break default: break } let temp = rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k E = D D = C C = rotateLeft(B, by: 30) B = A A = temp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D hh[4] = hh[4] &+ E } } extension SHA1: Updatable { @discardableResult public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { accumulated += bytes if isLast { let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b // Step 1. Append padding bitPadding(to: &accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8) // Step 2. Append Length a 64-bit representation of lengthInBits accumulated += lengthBytes } var processedBytes = 0 for chunk in accumulated.batched(by: SHA1.blockSize) { if isLast || (accumulated.count - processedBytes) >= SHA1.blockSize { process(block: chunk, currentHash: &accumulatedHash) processedBytes += chunk.count } } accumulated.removeFirst(processedBytes) processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>(repeating: 0, count: SHA1.digestLength) var pos = 0 for idx in 0..<accumulatedHash.count { let h = accumulatedHash[idx].bigEndian result[pos] = UInt8(h & 0xff) result[pos + 1] = UInt8((h >> 8) & 0xff) result[pos + 2] = UInt8((h >> 16) & 0xff) result[pos + 3] = UInt8((h >> 24) & 0xff) pos += 4 } // reset hash value for instance if isLast { accumulatedHash = SHA1.hashInitialValue } return result } }
34.434211
217
0.546809
72454f8353aa8b7dbdc021703f7541b8d1d25cbd
16,090
// // SABoardFilterViewController.swift // Saralin // // Created by zhang on 12/1/16. // Copyright © 2016 zaczh. All rights reserved. // import UIKit protocol SABoardFilterDelegate: NSObjectProtocol { func boardFilterViewController(_: SABoardFilterViewController, didChooseSubBoardID fid: String, categoryID cid: String) } class SABoardFilterViewController: SAUITableViewController { weak var delegate: SABoardFilterDelegate? var isEmpty: Bool = true { didSet { emptyView?.isHidden = !isEmpty } } var emptyView: UILabel? var boards: [(String,String)]! var openedSection: NSInteger = -1 var selectedBoard: String! var selectedCategory: String! var headerConstraints: [Int : (NSLayoutConstraint, NSLayoutConstraint, NSLayoutConstraint, UIView, UIView)] = [:] init(boards: [(String,String)], selectedBoard: String, categories: [(String, String)], selectedCategory: String) { super.init(style: .plain) self.boards = boards self.selectedBoard = selectedBoard self.selectedCategory = selectedCategory } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } else { // Fallback on earlier versions } view.backgroundColor = Theme().backgroundColor.sa_toColor() tableView.backgroundColor = Theme().backgroundColor.sa_toColor() tableView.sectionHeaderHeight = 50 if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 } else { // Fallback on earlier versions } tableView.rowHeight = 50.0 tableView.tableFooterView = UIView() tableView.separatorStyle = .none tableView.register(SABoardFilterTableViewCell.self, forCellReuseIdentifier: "cell") tableView.separatorColor = UIColor.sa_colorFromHexString(Theme().tableCellSeperatorColor) emptyView = UILabel() emptyView!.textAlignment = .center emptyView!.text = NSLocalizedString("THIS_BOARD_HAS_NO_CHILD", comment: "当前版块没有子版块") emptyView!.numberOfLines = 0 emptyView!.textColor = UIColor.sa_colorFromHexString(Theme().globalTintColor) emptyView!.translatesAutoresizingMaskIntoConstraints = false emptyView!.isHidden = true view.addSubview(emptyView!) view.addConstraint(NSLayoutConstraint(item: emptyView!, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0)) view.addConstraint(NSLayoutConstraint(item: emptyView!, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0)) } override func numberOfSections(in tableView: UITableView) -> Int { if boards != nil { if openedSection != -1 { return 1 } else { isEmpty = boards!.count == 0 return boards!.count } } else { isEmpty = true return 0 } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.sa_colorFromHexString(Theme().foregroundColor) header.tag = section let tap = UITapGestureRecognizer(target: self, action: #selector(handleSectionHeaderTap(_:))) header.addGestureRecognizer(tap) let iconLeft = UIButton() iconLeft.isUserInteractionEnabled = false iconLeft.isHidden = openedSection == -1 iconLeft.tintColor = UIColor.sa_colorFromHexString(Theme().tableCellTintColor) if openedSection != -1 { iconLeft.setBackgroundImage(UIImage.imageWithSystemName("chevron.down", fallbackName:"Expand_Arrow_50")?.withRenderingMode(.alwaysTemplate), for: UIControl.State.normal) } else { iconLeft.setBackgroundImage(UIImage.imageWithSystemName("chevron.up", fallbackName:"Collapse_Arrow_50")?.withRenderingMode(.alwaysTemplate), for: UIControl.State.normal) } iconLeft.translatesAutoresizingMaskIntoConstraints = false header.addSubview(iconLeft) header.addConstraint(NSLayoutConstraint(item: iconLeft, attribute: .centerY, relatedBy: .equal, toItem: header, attribute: .centerY, multiplier: 1.0, constant: 0)) header.addConstraint(NSLayoutConstraint(item: iconLeft, attribute: .left, relatedBy: .equal, toItem: header.safeAreaLayoutGuide, attribute: .left, multiplier: 1.0, constant: 16)) let iconRight = UIButton() iconRight.isUserInteractionEnabled = false if openedSection != -1 { iconRight.isHidden = true iconRight.setBackgroundImage(UIImage.imageWithSystemName("chevron.up", fallbackName:"Collapse_Arrow_50")?.withRenderingMode(.alwaysTemplate), for: UIControl.State.normal) } else { iconRight.isHidden = false iconRight.setBackgroundImage(UIImage.imageWithSystemName("chevron.down", fallbackName:"Expand_Arrow_50")?.withRenderingMode(.alwaysTemplate), for: UIControl.State.normal) } iconRight.translatesAutoresizingMaskIntoConstraints = false iconRight.tintColor = UIColor.sa_colorFromHexString(Theme().tableCellTintColor) header.addSubview(iconRight) header.addConstraint(NSLayoutConstraint(item: iconRight, attribute: .centerY, relatedBy: .equal, toItem: header, attribute: .centerY, multiplier: 1.0, constant: 0)) header.addConstraint(NSLayoutConstraint(item: iconRight, attribute: .right, relatedBy: .equal, toItem: header.safeAreaLayoutGuide, attribute: .right, multiplier: 1.0, constant: -16)) let label = UILabel() label.font = UIFont.sa_preferredFont(forTextStyle: UIFont.TextStyle.headline) label.textAlignment = .center label.textColor = UIColor.sa_colorFromHexString(Theme().tableHeaderTextColor) if openedSection != -1 { let name = boards![openedSection].1 label.text = name } else { let name = boards![section].1 label.text = name } label.translatesAutoresizingMaskIntoConstraints = false header.addSubview(label) header.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: header, attribute: .centerY, multiplier: 1.0, constant: 0)) let labelLeftConstraint = NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: header.safeAreaLayoutGuide, attribute: .left, multiplier: 1.0, constant: 16) labelLeftConstraint.isActive = true let labelCenterConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: header, attribute: .centerX, multiplier: 1.0, constant: 16) labelCenterConstraint.isActive = false let line = UIView() line.translatesAutoresizingMaskIntoConstraints = false line.backgroundColor = UIColor.sa_colorFromHexString(Theme().tableCellSeperatorColor) header.addSubview(line) header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[l]|", options: [], metrics: nil, views: ["l":line])) header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[l(==1)]|", options: [], metrics: nil, views: ["l":line])) let lineLeftConstraint = NSLayoutConstraint(item: line, attribute: .left, relatedBy: .equal, toItem: header, attribute: .left, multiplier: 1.0, constant: 16) lineLeftConstraint.isActive = true headerConstraints[section] = (labelLeftConstraint, labelCenterConstraint, lineLeftConstraint, iconLeft, iconRight) updateHeaderView(header) return header } fileprivate func updateHeaderView(_ header: UIView) { let section = header.tag guard headerConstraints.count > section else { return } guard let constraint = headerConstraints[section] else { return } if openedSection != -1 { constraint.0.isActive = false constraint.1.isActive = true constraint.2.constant = 0 constraint.3.isHidden = false constraint.4.isHidden = true } else { constraint.0.isActive = true constraint.1.isActive = false constraint.2.constant = 16 constraint.3.isHidden = true constraint.4.isHidden = false } header.setNeedsLayout() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if openedSection != -1 { if section == 0 { let fid = boards[openedSection].0 var forum: NSDictionary! = nil let forumInfo = NSDictionary(contentsOf: AppController.current.forumInfoConfigFileURL)! as! [String:AnyObject] let forumList = forumInfo["items"] as! [[String:AnyObject]] for obj in forumList { let aFid = obj["fid"] as! String if aFid == fid { forum = obj as NSDictionary break } } guard forum != nil else { sa_log_v2("forum is nil. Showing all", log: .ui, type: .debug) return 1 } let categorylist = forum["types"] as! [[String:String]] return categorylist.count + 1 // `+ 1` for "No Filter" option } return 0 } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SABoardFilterTableViewCell cell.customLine.isHidden = (indexPath as NSIndexPath).row == tableView.numberOfRows(inSection: (indexPath as NSIndexPath).section) - 1 if (indexPath as NSIndexPath).row == 0 { if openedSection == (indexPath as NSIndexPath).section && selectedCategory == "0" { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } cell.textLabel?.text = NSLocalizedString("ALL", comment: "全部") return cell } let fid = boards[openedSection].0 var forum: NSDictionary! = nil let forumInfo = NSDictionary(contentsOf: AppController.current.forumInfoConfigFileURL)! as! [String:AnyObject] let forumList = forumInfo["items"] as! [[String:AnyObject]] for obj in forumList { let aFid = obj["fid"] as! String if aFid == fid { forum = obj as NSDictionary break } } guard forum != nil else { sa_log_v2("forum is nil", log: .ui, type: .debug) return cell } let categorylist = forum["types"] as! [[String:String]] let categoryID = categorylist[(indexPath as NSIndexPath).row - 1]["typeid"] let categoryName = categorylist[(indexPath as NSIndexPath).row - 1]["typename"] if openedSection == (indexPath as NSIndexPath).section && selectedCategory == categoryID { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } cell.textLabel?.text = categoryName return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let fid = boards![openedSection].0 if (indexPath as NSIndexPath).row == 0 { delegate?.boardFilterViewController(self, didChooseSubBoardID: fid, categoryID: "0") dismiss(animated: true, completion: nil) return } let forumInfo = NSDictionary(contentsOf: AppController.current.forumInfoConfigFileURL)! as! [String:AnyObject] let forumList = forumInfo["items"] as! [[String:AnyObject]] var forum: NSDictionary! = nil for obj in forumList { let aFid = obj["fid"] as! String if aFid == fid { forum = obj as NSDictionary break } } guard forum != nil else { sa_log_v2("forum is nil", log: .ui, type: .debug) return } let categorylist = forum["types"] as! [[String:String]] let categoryID = categorylist[(indexPath as NSIndexPath).row - 1]["typeid"] delegate?.boardFilterViewController(self, didChooseSubBoardID: fid, categoryID: categoryID!) dismiss(animated: true, completion: nil) } @objc func handleSectionHeaderTap(_ tap: UITapGestureRecognizer) { let header = tap.view! let section = header.tag var indexPathes = [IndexPath]() let fid = boards![section].0 var forum: NSDictionary! = nil let forumInfo = NSDictionary(contentsOf: AppController.current.forumInfoConfigFileURL)! as! [String:AnyObject] let defaultList = forumInfo["items"] as! [[String:AnyObject]] for obj in defaultList { let aFid = obj["fid"] as! String if aFid == fid { forum = obj as NSDictionary break } } var categorylist: [[String:String]]! if forum == nil { sa_log_v2("forum is nil", log: .ui, type: .debug) categorylist = [] } else { categorylist = (forum["types"] as! [[String:String]]) } for i in 0 ... categorylist.count { indexPathes.append(IndexPath(row: i, section: 0)) } if openedSection == -1 { let sectionsDeleteTop = NSMutableIndexSet() if section - 1 >= 0 { for i in 0 ... section - 1 { sectionsDeleteTop.add(i) } } let sectionsDeleteBottom = NSMutableIndexSet() if section + 1 <= boards.count - 1 { for i in section + 1 ... boards.count - 1 { sectionsDeleteBottom.add(i) } } openedSection = section tableView.beginUpdates() tableView.insertRows(at: indexPathes, with: .automatic) tableView.deleteSections(sectionsDeleteTop as IndexSet, with: .top) tableView.deleteSections(sectionsDeleteBottom as IndexSet, with: .bottom) tableView.endUpdates() } else { let sectionsInsertBottom = NSMutableIndexSet() if section - 1 >= 0 { for i in 0 ... section - 1 { //make reverse sectionsInsertBottom.add(section - 1 - i) } } let sectionsInsertTop = NSMutableIndexSet() if section + 1 <= boards.count - 1 { for i in section + 1 ... boards.count - 1 { sectionsInsertTop.add(i) } } openedSection = -1 tableView.beginUpdates() tableView.deleteRows(at: indexPathes, with: .automatic) tableView.insertSections(sectionsInsertTop as IndexSet, with: .top) tableView.insertSections(sectionsInsertBottom as IndexSet, with: .bottom) tableView.endUpdates() } updateHeaderView(header) } }
42.906667
190
0.604413