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
29fb91455d87d27d19970919807fc8279bcd2218
3,449
// // HCIDisconnect.swift // Bluetooth // // Created by Carlos Duclos on 7/26/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// Disconnect Command /// /// The Disconnection command is used to terminate an existing connection. The Connection_Handle command parameter indicates which connection is to be disconnected. The Reason command parameter indicates the reason for ending the connection. The remote Controller will receive the Reason command parameter in the Disconnection Complete event. All synchronous connections on a physical link should be disconnected before the ACL connection on the same physical connection is disconnected. func disconnect(connectionHandle: UInt16, error: HCIError, timeout: HCICommandTimeout = .default) throws -> HCIDisconnectionComplete { let disconnect = HCIDisconnect(connectionHandle: connectionHandle, error: error) return try deviceRequest(disconnect, HCIDisconnectionComplete.self, timeout: timeout) } } // MARK: - Command /// Disconnect Command /// /// The Disconnection command is used to terminate an existing connection. All synchronous connections on a physical link should be disconnected before the ACL connection on the same physical connection is disconnected. public struct HCIDisconnect: HCICommandParameter { public static let command = LinkControlCommand.disconnect /// Connection_Handle for the connection being disconnected. public var connectionHandle: UInt16 /// The Reason command parameter indicates the reason for ending the connection. The remote Controller will receive the Reason command parameter in the Disconnection Complete event. public var error: HCIError public init(connectionHandle: UInt16, error: HCIError) { self.connectionHandle = connectionHandle self.error = error } public var data: Data { let connectionBytes = connectionHandle.littleEndian.bytes return Data([connectionBytes.0, connectionBytes.1, error.rawValue]) } } extension HCIDisconnect { /// The Reason command parameter indicates the reason for ending the connection. The remote Controller will receive the Reason command parameter in the Disconnection Complete event. public struct Reason { /// Authentication Failure public static let authenticationFailure: HCIError = .authenticationFailure /// Other End Terminated Connection public static let otherEndTerminatedConnection: [HCIError] = [ .remoteUserEndedConnection, .remoteLowResources, .remotePowerOff ] /// Unsupported Remote Feature public static let unsupportedRemoteFeature: HCIError = .unsupportedRemoteFeature /// Pairing with Unit Key Not Supported public static let pairingWithUnitKeyNotSupported: HCIError = .pairingWithUnitKeyNotSupported /// All the cases of the enum. public static let allCases: Set<HCIError> = Set([ Reason.authenticationFailure, Reason.unsupportedRemoteFeature, Reason.pairingWithUnitKeyNotSupported] + Reason.otherEndTerminatedConnection) } }
39.643678
491
0.704552
8f97adb7f75ae16fcc6940087b0b9af58a2555e8
4,929
/** Copyright (c) 2020 David Seek, LLC 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. https://leetcode.com/problems/reconstruct-itinerary/ Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] Example 2: Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. */ /** Big O Annotation Time complexity O(n log m). I would argue that we have n log m time complexity. "n" for the iteration. "log m" for the sort (Swift Array.sort has O(log n) complexity). We iterate through the tickets and we need to sort the destinations in our adjency list alphabetically. "n" is the number of source airports, "m" is the total number of destinations per airports. Afterwards we just DFS through the graph what has a time complexity of O(V+E) Vertex+Edge but since n of above explanation already stands for all the verticies and their m for all their edges and O(n log m) is the dominant term over O(V+E), we drop "V+E" Space complexity O(V+E) for all verticies and edges aka all airports and their destinations in the adjency list. */ func findItinerary(_ tickets: [[String]]) -> [String] { /** Create an adjency list graph to represent the tickets relations */ var graph = getGraph(of: tickets) /** The stack that will be the final result itinerary */ var stack: [String] = [] // DFS through the graph setItinerary(into: &stack, from: &graph) // Return the stack in reversed order return stack.reversed() } /** - parameters: - stack: The itinerary final stack - graph: Adjacency list graph representation - source: The current airport */ func setItinerary(into stack: inout [String], from graph: inout [String:[String]], for source: String = "JFK") { /** We need to make sure NOT to create a reference variable as we want to manipulate the graph itself. Otherwise we might get stackoverflow ATL-SFO SFO-ATL ATL-SFO... */ if graph[source] != nil { // While we still have airports to visit while !graph[source]!.isEmpty { // ...do so... setItinerary(into: &stack, from: &graph, for: graph[source]!.removeFirst()) } } // And add the current source to the stack stack.append(source) } func getGraph(of tickets: [[String]]) -> [String:[String]] { // Adjancency list graph var adjancencyList: [ String : [String] ] = [:] // Iterate through the tickets for ticket in tickets { // Get the source and destination let source = ticket[0] let destination = ticket[1] // Check if we have already mapped the source if let mapped = adjancencyList[source] { /** If so add the airports in alphabetically sorted order to the array. */ let destinations = mapped + [destination] adjancencyList[source] = destinations.sorted() } else { // Otherwise create the array adjancencyList[source] = [destination] } } return adjancencyList }
32.215686
232
0.682897
e2b885f37c578edec4692f566b31c8b8c33022b8
1,654
// The MIT License (MIT) // Copyright © 2022 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 extension SFSymbol { public static var gearshape: Gearshape { .init(name: "gearshape") } open class Gearshape: SFSymbol { open var fill: SFSymbol { ext(.start.fill) } open var circle: SFSymbol { ext(.start.circle) } open var circleFill: SFSymbol { ext(.start.circle.fill) } open var second: SFSymbol { ext(.start + ".2") } open var secondFill: SFSymbol { ext(.start + ".2".fill) } } }
41.35
81
0.704353
bba128c803caa6b070cde1c567d99b981da19e95
2,509
// // Status.swift // moretwitter // // Created by Faheem Hussain on 11/5/16. // Copyright © 2016 Faheem Hussain. All rights reserved. // import UIKit class Status: NSObject { var text: String? var timestamp: Date? var retweetCount: Int = 0 var favoritesCount: Int = 0 var favorited: Bool? var reTweeted: Bool? var id: Int? var user: User! var retweetStatus: Status? var hasRetweetStatus: Bool = false var idStr: String? init(dictionary: NSDictionary){ super.init() setFrom(dictionary: dictionary) } func setFrom(dictionary: NSDictionary){ //print("\(dictionary)") var tweetDictionary: NSDictionary = dictionary idStr = tweetDictionary["created_at"] as? String id = (tweetDictionary["id"] as? Int) ?? 0 idStr = tweetDictionary["id_str"] as? String favoritesCount = (tweetDictionary["favorite_count"] as? Int) ?? 0 favorited = tweetDictionary["favorited"] as? Bool reTweeted = tweetDictionary["retweeted"] as? Bool user = User(dictionary: tweetDictionary["user"] as! NSDictionary) let timestampString = tweetDictionary["created_at"] as? String if let timestampString = timestampString { let formatter = DateFormatter() formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" timestamp = formatter.date(from: timestampString) } if let retweetedStatus = tweetDictionary["retweeted_status"] as? NSDictionary{ hasRetweetStatus = true retweetStatus = Status(dictionary: retweetedStatus) tweetDictionary = retweetedStatus } text = tweetDictionary["text"] as? String retweetCount = (tweetDictionary["retweet_count"] as? Int) ?? 0 } class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Status]{ var tweets : [Status] = [] var minId: Int64 = (dictionaries[0]["id"] as! NSNumber).int64Value for dictionary in dictionaries { let tweet = Status(dictionary: dictionary) if tweet.user.screenname == "codepath" { //print("\(dictionary)") } let tid = (dictionary["id"] as! NSNumber).int64Value if tid < minId { minId = tid } tweets.append(tweet) } return tweets } func replaceWith(dictionary: NSDictionary){ setFrom(dictionary: dictionary) } }
33.453333
86
0.60821
3aa73a5ce1588d0787a70557b0c8c1628d3d8839
16,727
// // DeltaRequestLoop.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 16.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Class that handles HTTP-requests sending by SDK with internal requested actions (initialization and chat updates). - seealso: `DeltaCallback` `DeltaResponse` - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ class DeltaRequestLoop: AbstractRequestLoop { // MARK: - Properties private static var providedAuthenticationTokenErrorCount = 0 private let appVersion: String? private let baseURL: String private let deltaCallback: DeltaCallback private let deviceID: String private let sessionParametersListener: SessionParametersListener? private let title: String var authorizationData: AuthorizationData? var queue: DispatchQueue? var since: Int64 = 0 private var deviceToken: String? private var location: String private var providedAuthenticationToken: String? private weak var providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener? private var sessionID: String? private var visitorFieldsJSONString: String? private var visitorJSONString: String? private var prechat: String? // MARK: - Initialization init(deltaCallback: DeltaCallback, completionHandlerExecutor: ExecIfNotDestroyedHandlerExecutor, sessionParametersListener: SessionParametersListener?, internalErrorListener: InternalErrorListener, baseURL: String, title: String, location: String, appVersion: String?, visitorFieldsJSONString: String?, providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener?, providedAuthenticationToken: String?, deviceID: String, deviceToken: String?, visitorJSONString: String?, sessionID: String?, prechat:String?, authorizationData: AuthorizationData?) { self.deltaCallback = deltaCallback self.sessionParametersListener = sessionParametersListener self.baseURL = baseURL self.title = title self.location = location self.appVersion = appVersion self.visitorFieldsJSONString = visitorFieldsJSONString self.deviceID = deviceID self.deviceToken = deviceToken self.visitorJSONString = visitorJSONString self.sessionID = sessionID self.authorizationData = authorizationData self.providedAuthenticationTokenStateListener = providedAuthenticationTokenStateListener self.providedAuthenticationToken = providedAuthenticationToken self.prechat = prechat super.init(completionHandlerExecutor: completionHandlerExecutor, internalErrorListener: internalErrorListener) } // MARK: - Methods override func start() { guard queue == nil else { return } queue = DispatchQueue(label: "ru.webim.DeltaDispatchQueue") guard let queue = queue else { WebimInternalLogger.shared.log(entry: "DispatchQueue initialisation failure in DeltaRequestLoop.\(#function)") return } queue.async { self.run() } } override func stop() { super.stop() queue = nil } func set(deviceToken: String) { self.deviceToken = deviceToken } func change(location: String) throws { self.location = location authorizationData = nil since = 0 requestInitialization() } func getAuthorizationData() -> AuthorizationData? { return authorizationData } func run() { while isRunning() { if authorizationData != nil && since != 0 { requestDelta() } else { requestInitialization() } } } func requestInitialization() { let url = URL(string: getDeltaServerURLString() + "?" + getInitializationParameterString()) var request = URLRequest(url: url!) request.setValue("3.35.0", forHTTPHeaderField: Parameter.webimSDKVersion.rawValue) request.httpMethod = AbstractRequestLoop.HTTPMethods.get.rawValue do { let data = try perform(request: request) if let dataJSON = try? (JSONSerialization.jsonObject(with: data) as? [String: Any]) { if let error = dataJSON[AbstractRequestLoop.ResponseFields.error.rawValue] as? String { handleInitialization(error: error) } else { DeltaRequestLoop.providedAuthenticationTokenErrorCount = 0 let deltaResponse = DeltaResponse(jsonDictionary: dataJSON) if let deltaList = deltaResponse.getDeltaList() { if deltaList.count > 0 { handleIncorrectServerAnswer() return } } guard let fullUpdate = deltaResponse.getFullUpdate() else { handleIncorrectServerAnswer() return } if let since = deltaResponse.getRevision() { self.since = since } process(fullUpdate: fullUpdate) } } else { WebimInternalLogger.shared.log(entry: "Error de-serializing server response: \(String(data: data, encoding: .utf8) ?? "unreadable data").", verbosityLevel: .warning) } } catch let unknownError as UnknownError { handleRequestLoop(error: unknownError) } catch { WebimInternalLogger.shared.log(entry: "Request failed with unknown error: \(error.localizedDescription)", verbosityLevel: .warning) } } func requestDelta() { guard let url = URL(string: getDeltaServerURLString() + "?" + getDeltaParameterString()) else { WebimInternalLogger.shared.log(entry: "Initialize URL failure in DeltaRequestLoop.\(#function)") return } var request = URLRequest(url: url) request.httpMethod = AbstractRequestLoop.HTTPMethods.get.rawValue do { let data = try perform(request: request) if let dataJSON = try? (JSONSerialization.jsonObject(with: data) as? [String: Any]) { if let error = dataJSON[AbstractRequestLoop.ResponseFields.error.rawValue] as? String { handleDeltaRequest(error: error) } else { let deltaResponse = DeltaResponse(jsonDictionary: dataJSON) guard let revision = deltaResponse.getRevision() else { // Delta timeout. return } since = revision if let fullUpdate = deltaResponse.getFullUpdate() { completionHandlerExecutor?.execute(task: DispatchWorkItem { self.process(fullUpdate: fullUpdate) }) } else if let deltaList = deltaResponse.getDeltaList() { if deltaList.count > 0 { completionHandlerExecutor?.execute(task: DispatchWorkItem { self.deltaCallback.process(deltaList: deltaList) }) } } } } else { WebimInternalLogger.shared.log(entry: "Error de-serializing server response: \(String(data: data, encoding: .utf8) ?? "unreadable data").", verbosityLevel: .warning) } } catch let unknownError as UnknownError { handleRequestLoop(error: unknownError) } catch { WebimInternalLogger.shared.log(entry: "Request failed with unknown error: \(error.localizedDescription).", verbosityLevel: .warning) } } // MARK: Private methods private func getDeltaServerURLString() -> String { return (baseURL + ServerPathSuffix.getDelta.rawValue) } private func getInitializationParameterString() -> String { var parameterDictionary = [Parameter.deviceID.rawValue: deviceID, Parameter.event.rawValue: Event.initialization.rawValue, Parameter.location.rawValue: location, Parameter.platform.rawValue: Platform.ios.rawValue, Parameter.respondImmediately.rawValue: true, Parameter.since.rawValue: 0, Parameter.title.rawValue: title] as [String: Any] if let appVersion = appVersion { parameterDictionary[Parameter.applicationVersion.rawValue] = appVersion } if let deviceToken = deviceToken { parameterDictionary[Parameter.deviceToken.rawValue] = deviceToken } if let sessionID = sessionID { parameterDictionary[Parameter.visitSessionID.rawValue] = sessionID } if let visitorJSONString = visitorJSONString { parameterDictionary[Parameter.visitor.rawValue] = visitorJSONString } if let visitorFieldsJSONString = visitorFieldsJSONString { parameterDictionary[Parameter.visitorExt.rawValue] = visitorFieldsJSONString } if let providedAuthenticationToken = providedAuthenticationToken { parameterDictionary[Parameter.providedAuthenticationToken.rawValue] = providedAuthenticationToken } if let prechat = prechat { parameterDictionary[Parameter.prechat.rawValue] = prechat } return parameterDictionary.stringFromHTTPParameters() } private func getDeltaParameterString() -> String { let currentTimestamp = Int64(CFAbsoluteTimeGetCurrent() * 1000) var parameterDictionary = [Parameter.since.rawValue: String(since), Parameter.timestamp.rawValue: currentTimestamp] as [String: Any] if let authorizationData = authorizationData { parameterDictionary[Parameter.pageID.rawValue] = authorizationData.getPageID() parameterDictionary[Parameter.authorizationToken.rawValue] = authorizationData.getAuthorizationToken() } return parameterDictionary.stringFromHTTPParameters() } private func sleepBetweenInitializationAttempts() { authorizationData = nil since = 0 usleep(1_000_000) // 1s } private func handleIncorrectServerAnswer() { WebimInternalLogger.shared.log(entry: "Incorrect server answer while requesting initialization.", verbosityLevel: .debug) usleep(1_000_000) // 1s } private func handleInitialization(error: String) { switch error { case WebimInternalError.reinitializationRequired.rawValue: handleReinitializationRequiredError() break case WebimInternalError.providedAuthenticationTokenNotFound.rawValue: handleProvidedAuthenticationTokenNotFoundError() break default: running = false completionHandlerExecutor?.execute(task: DispatchWorkItem { self.internalErrorListener?.on(error: error) }) break } } private func handleDeltaRequest(error: String) { if error == WebimInternalError.reinitializationRequired.rawValue { handleReinitializationRequiredError() } else { completionHandlerExecutor?.execute(task: DispatchWorkItem { self.internalErrorListener?.on(error: error) }) } } private func handleReinitializationRequiredError() { authorizationData = nil since = 0 } private func handleProvidedAuthenticationTokenNotFoundError() { DeltaRequestLoop.providedAuthenticationTokenErrorCount += 1 if DeltaRequestLoop.providedAuthenticationTokenErrorCount < 5 { sleepBetweenInitializationAttempts() } else { guard let token = providedAuthenticationToken else { WebimInternalLogger.shared.log(entry: "Provided Authentication Token is nil in DeltaRequestLoop.\(#function)") return } providedAuthenticationTokenStateListener?.update(providedAuthorizationToken: token) DeltaRequestLoop.providedAuthenticationTokenErrorCount = 0 sleepBetweenInitializationAttempts() } } private func process(fullUpdate: FullUpdate) { let visitorJSONString = fullUpdate.getVisitorJSONString() let sessionID = fullUpdate.getSessionID() let authorizationData = AuthorizationData(pageID: fullUpdate.getPageID(), authorizationToken: fullUpdate.getAuthorizationToken()) let isNecessaryToUpdateVisitorFieldJSONString = (self.visitorFieldsJSONString == nil) || (self.visitorFieldsJSONString != visitorFieldsJSONString) let isNecessaryToUpdateSessionID = (self.sessionID == nil) || (self.sessionID != sessionID) let isNecessaryToUpdateAuthorizationData = (self.authorizationData == nil) || ((self.authorizationData?.getPageID() != fullUpdate.getPageID()) || (self.authorizationData?.getAuthorizationToken() != fullUpdate.getAuthorizationToken())) if (isNecessaryToUpdateVisitorFieldJSONString || isNecessaryToUpdateSessionID) || isNecessaryToUpdateAuthorizationData { self.visitorJSONString = visitorJSONString self.sessionID = sessionID self.authorizationData = authorizationData DispatchQueue.global(qos: .background).async { [weak self] in guard let `self` = self, let visitorJSONString = self.visitorJSONString, let sessionID = self.sessionID, let authorizationData = self.authorizationData else { WebimInternalLogger.shared.log(entry: "Changing parameters failure while unwrpping in DeltaRequestLoop.\(#function)") return } self.sessionParametersListener?.onSessionParametersChanged(visitorFieldsJSONString: visitorJSONString, sessionID: sessionID, authorizationData: authorizationData) } } completionHandlerExecutor?.execute(task: DispatchWorkItem { self.deltaCallback.process(fullUpdate: fullUpdate) }) } }
41.506203
155
0.607282
b9d2a85efe47cae8e5dbc63bf4c1fcb17703fcf0
553
// // ViewController.swift // FBMoviePlayer // // Created by chongling.liu on 2021/5/12. // import UIKit class MainViewController: UIViewController { private lazy var subFlutterVC: FBFlutterViewController = FBFlutterViewController(withEntrypoint: nil) override func viewDidLoad() { addChild(subFlutterVC) let safeFrame = self.view.safeAreaLayoutGuide.layoutFrame subFlutterVC.view.frame = safeFrame self.view.addSubview(subFlutterVC.view) subFlutterVC.didMove(toParent: self) } }
23.041667
105
0.703436
e6e6e37b70f7e8747f92ebd5bcc4d3295c2c6bef
25,436
// // MySQLStmt.swift // PerfectMySQL // // Created by Kyle Jessup on 2018-03-07. // #if os(Linux) import SwiftGlibc #else import Darwin #endif import mysqlclient /// handles mysql prepared statements public final class MySQLStmt { private let ptr: UnsafeMutablePointer<MYSQL_STMT> private var paramBinds: UnsafeMutablePointer<MYSQL_BIND>? private var paramBindsOffset = 0 var meta: UnsafeMutablePointer<MYSQL_RES>? /// initialize mysql statement structure public init(_ mysql: MySQL) { ptr = mysql_stmt_init(mysql.mysqlPtr) } deinit { clearBinds() if let meta = self.meta { mysql_free_result(meta) } mysql_stmt_close(ptr) } public func fieldNames() -> [Int: String] { let columnCount = Int(fieldCount()) guard columnCount > 0 else { return [:] } var fieldDictionary = [Int: String]() let fields = mysql_fetch_fields(mysql_stmt_result_metadata(ptr)) var i = 0 while i != columnCount { fieldDictionary[i] = String(cString: fields![i].name) i += 1 } return fieldDictionary } public enum FieldType { case integer, double, bytes, string, date, null } public struct FieldInfo { public let name: String public let type: FieldType } public func fieldInfo(index: Int) -> FieldInfo? { let fieldCount = Int(self.fieldCount()) guard index < fieldCount else { return nil } guard let field = mysql_fetch_field_direct(meta, UInt32(index)) else { return nil } let f: MYSQL_FIELD = field.pointee return FieldInfo(name: String(validatingUTF8: f.name) ?? "invalid field name", type: mysqlTypeToFieldType(field)) } func mysqlTypeToFieldType(_ field: UnsafeMutablePointer<MYSQL_FIELD>) -> FieldType { switch field.pointee.type { case MYSQL_TYPE_NULL: return .null case MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE: return .double case MYSQL_TYPE_TINY, MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, MYSQL_TYPE_INT24, MYSQL_TYPE_LONGLONG: return .integer case MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, MYSQL_TYPE_NEWDATE: return .date case MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL: return .string case MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB: if field.pointee.charsetnr == 63 /* binary */ { return .bytes } fallthrough default: return .string } } /// Possible status for fetch results public enum FetchResult { case OK, Error, NoData, DataTruncated } @available(*, deprecated) public func close() {} /// Resets the statement buffers in the server public func reset() { mysql_stmt_reset(ptr) resetBinds() } public func resetBinds() { let count = paramBindsOffset if let paramBinds = self.paramBinds, count > 0 { for i in 0..<count { let bind = paramBinds[i] switch bind.buffer_type.rawValue { case MYSQL_TYPE_DOUBLE.rawValue: bind.buffer.assumingMemoryBound(to: Double.self).deallocate() case MYSQL_TYPE_FLOAT.rawValue: bind.buffer.assumingMemoryBound(to: Float.self).deallocate() case MYSQL_TYPE_LONGLONG.rawValue: bind.buffer.assumingMemoryBound(to: UInt64.self).deallocate() case MYSQL_TYPE_LONG.rawValue: bind.buffer.assumingMemoryBound(to: UInt32.self).deallocate() case MYSQL_TYPE_SHORT.rawValue: bind.buffer.assumingMemoryBound(to: UInt16.self).deallocate() case MYSQL_TYPE_TINY.rawValue: bind.buffer.assumingMemoryBound(to: UInt8.self).deallocate() case MYSQL_TYPE_VAR_STRING.rawValue, MYSQL_TYPE_DATE.rawValue, MYSQL_TYPE_DATETIME.rawValue: bind.buffer.assumingMemoryBound(to: Int8.self).deallocate() case MYSQL_TYPE_LONG_BLOB.rawValue, MYSQL_TYPE_NULL.rawValue: () default: assertionFailure("Unhandled MySQL type \(bind.buffer_type)") } if bind.length != nil { bind.length.deallocate() } paramBinds[i] = MYSQL_BIND() } paramBindsOffset = 0 } } public func clearBinds() { let count = paramBindsOffset if count > 0, nil != paramBinds { resetBinds() paramBinds?.deallocate() paramBinds = nil paramBindsOffset = 0 } } /// Free the resources allocated to a statement handle public func freeResult() { mysql_stmt_free_result(ptr) } /// Returns the error number for the last statement execution public func errorCode() -> UInt32 { return mysql_stmt_errno(ptr) } /// Returns the error message for the last statement execution public func errorMessage() -> String { return String(validatingUTF8: mysql_stmt_error(ptr)) ?? "" } /// Prepares an SQL statement string for execution public func prepare(statement query: String) -> Bool { let utf8Chars = query.utf8 let r = mysql_stmt_prepare(ptr, query, UInt(utf8Chars.count)) guard r == 0 else { return false } if let m = meta { mysql_free_result(m) } meta = mysql_stmt_result_metadata(ptr) let count = paramCount() if count > 0 { paramBinds = UnsafeMutablePointer<MYSQL_BIND>.allocate(capacity: count) let initBind = MYSQL_BIND() for i in 0..<count { paramBinds?.advanced(by: i).initialize(to: initBind) } } return true } /// Executes a prepared statement, binding parameters if needed public func execute() -> Bool { if paramBindsOffset > 0 { guard let paramBinds = self.paramBinds else { return false } var res = mysql_stmt_bind_param(ptr, paramBinds) var FALSE = 0 let cmp = memcmp(&res, &FALSE, MemoryLayout.size(ofValue: res)) guard cmp == 0 else { return false } } let r = mysql_stmt_execute(ptr) return r == 0 } /// returns current results public func results() -> MySQLStmt.Results { return Results(self) } /// Fetches the next row of data from a result set and returns status public func fetch() -> FetchResult { let r = mysql_stmt_fetch(ptr) switch r { case 0: return .OK case 1: return .Error case MYSQL_NO_DATA: return .NoData case MYSQL_DATA_TRUNCATED: return .DataTruncated default: return .Error } } /// Returns the row count from a buffered statement result set public func numRows() -> UInt { return UInt(mysql_stmt_num_rows(ptr)) } /// Returns the number of rows changed, deleted, or inserted by prepared UPDATE, DELETE, or INSERT statement public func affectedRows() -> UInt { return UInt(mysql_stmt_affected_rows(ptr)) } /// Returns the ID generated for an AUTO_INCREMENT column by a prepared statement public func insertId() -> UInt { return UInt(mysql_stmt_insert_id(ptr)) } /// Returns the number of result columns for the most recent statement public func fieldCount() -> UInt { return UInt(mysql_stmt_field_count(ptr)) } /// Returns/initiates the next result in a multiple-result execution public func nextResult() -> Int { let r = mysql_stmt_next_result(ptr) return Int(r) } /// Seeks to an arbitrary row number in a statement result set public func dataSeek(offset: Int) { mysql_stmt_data_seek(ptr, my_ulonglong(offset)) } /// Returns the number of parameters in a prepared statement public func paramCount() -> Int { let r = mysql_stmt_param_count(ptr) return Int(r) } private func allocated(_ a: [UInt8]) -> UnsafeMutableRawBufferPointer? { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: a.count, alignment: 0) buffer.copyBytes(from: a) return buffer } private func allocated(_ a: [Int8]) -> UnsafeMutableRawBufferPointer? { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: a.count, alignment: 0) let u = UnsafeRawPointer(a) if let p = buffer.baseAddress { memcpy(p, u, a.count) } return buffer } private func allocated(_ s: String) -> UnsafeMutableRawBufferPointer? { let utf8 = Array(s.utf8) + [0] return allocated(utf8) } private func allocated(_ b: UnsafePointer<Int8>, length: Int) -> UnsafeMutableRawBufferPointer? { let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: length, alignment: 0) if let p = buffer.baseAddress { memcpy(p, b, length) } return buffer } func bindParam(_ s: String, type: enum_field_types) { guard let allocd = allocated(s) else { return } paramBinds?[paramBindsOffset].buffer_type = type paramBinds?[paramBindsOffset].buffer_length = UInt(allocd.count-1) paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBinds?[paramBindsOffset].length.initialize(to: UInt(allocd.count-1)) paramBinds?[paramBindsOffset].buffer = allocd.baseAddress paramBindsOffset += 1 } /// create Double parameter binding public func bindParam(_ d: Double) { paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_DOUBLE paramBinds?[paramBindsOffset].buffer_length = UInt(MemoryLayout<Double>.size) let a = UnsafeMutablePointer<Double>.allocate(capacity: 1) a.initialize(to: d) paramBinds?[paramBindsOffset].buffer = UnsafeMutableRawPointer(a) paramBindsOffset += 1 } /// create Float parameter binding public func bindParam(_ d: Float) { paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_FLOAT paramBinds?[paramBindsOffset].buffer_length = UInt(MemoryLayout<Float>.size) let a = UnsafeMutablePointer<Float>.allocate(capacity: 1) a.initialize(to: d) paramBinds?[paramBindsOffset].buffer = UnsafeMutableRawPointer(a) paramBindsOffset += 1 } private func genBind<T>(type: enum_field_types, value: T) -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = type bind.buffer_length = UInt(MemoryLayout<T>.size) let b = UnsafeMutablePointer<T>.allocate(capacity: 1) b.initialize(to: value) bind.buffer = UnsafeMutableRawPointer(b) return bind } private func genBind<T: UnsignedInteger>(type: enum_field_types, value: T) -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = type memset(&(bind.is_unsigned), 1, MemoryLayout.size(ofValue: bind.is_unsigned)) bind.buffer_length = UInt(MemoryLayout<T>.size) let b = UnsafeMutablePointer<T>.allocate(capacity: 1) b.initialize(to: value) bind.buffer = UnsafeMutableRawPointer(b) return bind } /// create Int parameter binding public func bindParam(_ i: Int) { bindParam(Int64(i)) } /// create UInt parameter binding public func bindParam(_ i: UInt) { bindParam(UInt64(i)) } /// create Int64 parameter binding public func bindParam(_ i: Int64) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_LONGLONG, value: i) paramBindsOffset += 1 } /// create UInt64 parameter binding public func bindParam(_ i: UInt64) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_LONGLONG, value: i) paramBindsOffset += 1 } /// create Int32 parameter binding public func bindParam(_ i: Int32) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_LONG, value: i) paramBindsOffset += 1 } /// create UInt32 parameter binding public func bindParam(_ i: UInt32) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_LONG, value: i) paramBindsOffset += 1 } /// create Int16 parameter binding public func bindParam(_ i: Int16) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_SHORT, value: i) paramBindsOffset += 1 } /// create UInt16 parameter binding public func bindParam(_ i: UInt16) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_SHORT, value: i) paramBindsOffset += 1 } /// create Int16 parameter binding public func bindParam(_ i: Int8) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_TINY, value: i) paramBindsOffset += 1 } /// create UInt16 parameter binding public func bindParam(_ i: UInt8) { paramBinds?[paramBindsOffset] = genBind(type: MYSQL_TYPE_TINY, value: i) paramBindsOffset += 1 } /// create String parameter binding public func bindParam(_ s: String) { guard let allocd = allocated(s) else { return } paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_VAR_STRING paramBinds?[paramBindsOffset].buffer_length = UInt(allocd.count-1) paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBinds?[paramBindsOffset].length.initialize(to: UInt(allocd.count-1)) paramBinds?[paramBindsOffset].buffer = allocd.baseAddress paramBindsOffset += 1 } /// create String parameter binding public func bindParam(_ a: [UInt8]) { guard let allocd = allocated(a) else { return } paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_LONG_BLOB paramBinds?[paramBindsOffset].buffer_length = UInt(allocd.count) paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBinds?[paramBindsOffset].length.initialize(to: UInt(allocd.count)) paramBinds?[paramBindsOffset].buffer = allocd.baseAddress paramBindsOffset += 1 } /// create String parameter binding public func bindParam(_ a: [Int8]) { guard let allocd = allocated(a) else { return } paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_LONG_BLOB paramBinds?[paramBindsOffset].buffer_length = UInt(allocd.count) paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBinds?[paramBindsOffset].length.initialize(to: UInt(allocd.count)) paramBinds?[paramBindsOffset].buffer = allocd.baseAddress paramBindsOffset += 1 } /// create Blob parameter binding /// The memory is copied. public func bindParam(_ b: UnsafePointer<Int8>, length: Int) { guard let allocd = allocated(b, length: length) else { return } paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_LONG_BLOB paramBinds?[paramBindsOffset].buffer_length = UInt(length) paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBinds?[paramBindsOffset].length.initialize(to: UInt(length)) paramBinds?[paramBindsOffset].buffer = allocd.baseAddress paramBindsOffset += 1 } /// create null parameter binding public func bindParam() { paramBinds?[paramBindsOffset].buffer_type = MYSQL_TYPE_NULL paramBinds?[paramBindsOffset].length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) paramBindsOffset += 1 } /// manage results sets for MysqlStmt public final class Results: IteratorProtocol { let _UNSIGNED_FLAG = UInt32(UNSIGNED_FLAG) public typealias Element = [Any?] let stmt: MySQLStmt /// Field count for result set public let numFields: Int /// Row count for current set public var numRows: Int { return Int(stmt.numRows()) } var meta: UnsafeMutablePointer<MYSQL_RES>? { return stmt.meta } let binds: UnsafeMutablePointer<MYSQL_BIND> let lengthBuffers: UnsafeMutablePointer<UInt> let isNullBuffers: UnsafeMutablePointer<my_bool> private var closed = false init(_ s: MySQLStmt) { stmt = s numFields = Int(stmt.fieldCount()) binds = UnsafeMutablePointer<MYSQL_BIND>.allocate(capacity: numFields) lengthBuffers = UnsafeMutablePointer<UInt>.allocate(capacity: numFields) isNullBuffers = UnsafeMutablePointer<my_bool>.allocate(capacity: numFields) mysql_stmt_store_result(stmt.ptr) bind() } deinit { unbind() binds.deallocate() lengthBuffers.deallocate() isNullBuffers.deallocate() } public func fetchRow() -> Bool { let fetchRes = mysql_stmt_fetch(stmt.ptr) if fetchRes == MYSQL_NO_DATA || fetchRes == 1 { return false } return true } public func currentRow() -> [Any?]? { let r = (0..<numFields).map { self.valueForField($0) } return r } public func next() -> Element? { if !fetchRow() { return nil } return currentRow() } enum GeneralType { case integer(enum_field_types), double(enum_field_types), bytes(enum_field_types), string(enum_field_types), date(enum_field_types), null } func mysqlTypeToGeneralType(_ field: UnsafeMutablePointer<MYSQL_FIELD>) -> GeneralType { let type = field.pointee.type switch type { case MYSQL_TYPE_NULL: return .null case MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE: return .double(type) case MYSQL_TYPE_TINY, MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, MYSQL_TYPE_INT24, MYSQL_TYPE_LONGLONG: return .integer(type) case MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, MYSQL_TYPE_NEWDATE: return .date(type) case MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL: return .string(type) case MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB: if field.pointee.charsetnr == 63 /* binary */ { return .bytes(type) } fallthrough default: return .string(type) } } func mysqlTypeToGeneralType(_ type: enum_field_types) -> GeneralType { switch type { case MYSQL_TYPE_NULL: return .null case MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE: return .double(type) case MYSQL_TYPE_TINY, MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, MYSQL_TYPE_INT24, MYSQL_TYPE_LONGLONG: return .integer(type) case MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, MYSQL_TYPE_NEWDATE: return .date(type) case MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL: return .string(type) case MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB: return .bytes(type) default: return .string(type) } } func bindField(_ field: UnsafeMutablePointer<MYSQL_FIELD>) -> MYSQL_BIND { let generalType = mysqlTypeToGeneralType(field) let bind = bindToType(generalType) return bind } func bindBuffer<T>(_ sourceBind: MYSQL_BIND, type: T) -> MYSQL_BIND { var bind = sourceBind bind.buffer = UnsafeMutableRawPointer(UnsafeMutablePointer<T>.allocate(capacity: 1)) bind.buffer_length = UInt(MemoryLayout<T>.size) return bind } private func valueForField(_ n: Int) -> Any? { var bind = binds[n] var FALSE = 0 var cmp = memcmp(bind.is_null, &FALSE, MemoryLayout.size(ofValue: bind.is_null.pointee)) guard cmp == 0 else { return nil } let genType = mysqlTypeToGeneralType(bind.buffer_type) let length = Int(bind.length.pointee) switch genType { case .double: switch bind.buffer_type { case MYSQL_TYPE_FLOAT: return bind.buffer.assumingMemoryBound(to: Float.self).pointee case MYSQL_TYPE_DOUBLE: return bind.buffer.assumingMemoryBound(to: Double.self).pointee default: return nil } case .integer: cmp = memcmp(&(bind.is_unsigned), &FALSE, MemoryLayout.size(ofValue: bind.is_unsigned)) if cmp != 0 { switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: return bind.buffer.assumingMemoryBound(to: UInt64.self).pointee case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: return bind.buffer.assumingMemoryBound(to: UInt32.self).pointee case MYSQL_TYPE_SHORT: return bind.buffer.assumingMemoryBound(to: UInt16.self).pointee case MYSQL_TYPE_TINY: return bind.buffer.assumingMemoryBound(to: UInt8.self).pointee default: return nil } } else { switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: return bind.buffer.assumingMemoryBound(to: Int64.self).pointee case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: return bind.buffer.assumingMemoryBound(to: Int32.self).pointee case MYSQL_TYPE_SHORT: return bind.buffer.assumingMemoryBound(to: Int16.self).pointee case MYSQL_TYPE_TINY: return bind.buffer.assumingMemoryBound(to: Int8.self).pointee default: return nil } } case .bytes: let raw = UnsafeMutablePointer<UInt8>.allocate(capacity: length) defer { raw.deallocate() } bind.buffer = UnsafeMutableRawPointer(raw) bind.buffer_length = UInt(length) let res = mysql_stmt_fetch_column(stmt.ptr, &bind, UInt32(n), 0) guard res == 0 else { return nil } let a = (0..<length).map { raw[$0] } return a case .string, .date: let raw = UnsafeMutablePointer<UInt8>.allocate(capacity: length) defer { raw.deallocate() } bind.buffer = UnsafeMutableRawPointer(raw) bind.buffer_length = UInt(length) let res = mysql_stmt_fetch_column(stmt.ptr, &bind, UInt32(n), 0) guard res == 0 else { return nil } let s = UTF8Encoding.encode(generator: GenerateFromPointer(from: raw, count: length)) return s case .null: return nil } } /// Retrieve and process each row with the provided callback public func forEachRow(callback: (Element) -> ()) -> Bool { while let row = next() { callback(row) } return true } func bindToType(_ type: GeneralType) -> MYSQL_BIND { switch type { case .double(let s): return bindToIntegral(s) case .integer(let s): return bindToIntegral(s) case .bytes: return bindToBlob() case .string, .date: return bindToString() case .null: return bindToNull() } } func bindToBlob() -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = MYSQL_TYPE_LONG_BLOB return bind } func bindToString() -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = MYSQL_TYPE_VAR_STRING return bind } func bindToNull() -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = MYSQL_TYPE_NULL return bind } func bindToIntegral(_ type: enum_field_types) -> MYSQL_BIND { var bind = MYSQL_BIND() bind.buffer_type = type return bind } private func bind() { // empty buffer shared by .bytes, .string, .date, .null types let scratch = UnsafeMutableRawPointer(UnsafeMutablePointer<Int8>.allocate(capacity: 0)) defer { scratch.deallocate() } for i in 0..<numFields { guard let field = mysql_fetch_field_direct(meta, UInt32(i)) else { continue } let f: MYSQL_FIELD = field.pointee var bind = bindField(field) bind.length = lengthBuffers.advanced(by: i) bind.length.initialize(to: 0) bind.is_null = unsafeBitCast(isNullBuffers.advanced(by: i), to: type(of: bind.is_null)) memset(bind.is_null, 0, MemoryLayout.size(ofValue: bind.is_null.pointee)) let genType = mysqlTypeToGeneralType(field) switch genType { case .double: switch bind.buffer_type { case MYSQL_TYPE_FLOAT: bind = bindBuffer(bind, type: Float.self); case MYSQL_TYPE_DOUBLE: bind = bindBuffer(bind, type: Double.self); default: break } case .integer: if (f.flags & _UNSIGNED_FLAG) == _UNSIGNED_FLAG { memset(&(bind.is_unsigned), 1, MemoryLayout.size(ofValue: bind.is_unsigned)) switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: bind = bindBuffer(bind, type: UInt64.self); case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: bind = bindBuffer(bind, type: UInt32.self); case MYSQL_TYPE_SHORT: bind = bindBuffer(bind, type: UInt16.self); case MYSQL_TYPE_TINY: bind = bindBuffer(bind, type: UInt8.self); default: break } } else { switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: bind = bindBuffer(bind, type: Int64.self); case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: bind = bindBuffer(bind, type: Int32.self); case MYSQL_TYPE_SHORT: bind = bindBuffer(bind, type: Int16.self); case MYSQL_TYPE_TINY: bind = bindBuffer(bind, type: Int8.self); default: break } } case .bytes, .string, .date, .null: bind.buffer = scratch bind.buffer_length = 0 } binds.advanced(by: i).initialize(to: bind) } mysql_stmt_bind_result(stmt.ptr, binds) } private func unbind() { for i in 0..<numFields { let bind = binds[i] let genType = mysqlTypeToGeneralType(bind.buffer_type) switch genType { case .double: switch bind.buffer_type { case MYSQL_TYPE_FLOAT: bind.buffer.assumingMemoryBound(to: Float.self).deallocate() case MYSQL_TYPE_DOUBLE: bind.buffer.assumingMemoryBound(to: Double.self).deallocate() default: break } case .integer: var FALSE = 0 var res = bind.is_unsigned let cmp = memcmp(&res, &FALSE, MemoryLayout.size(ofValue: res)) if cmp != 0 { switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: bind.buffer.assumingMemoryBound(to: UInt64.self).deallocate() case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: bind.buffer.assumingMemoryBound(to: UInt32.self).deallocate() case MYSQL_TYPE_SHORT: bind.buffer.assumingMemoryBound(to: UInt16.self).deallocate() case MYSQL_TYPE_TINY: bind.buffer.assumingMemoryBound(to: UInt8.self).deallocate() default: break } } else { switch bind.buffer_type { case MYSQL_TYPE_LONGLONG: bind.buffer.assumingMemoryBound(to: Int64.self).deallocate() case MYSQL_TYPE_LONG, MYSQL_TYPE_INT24: bind.buffer.assumingMemoryBound(to: Int32.self).deallocate() case MYSQL_TYPE_SHORT: bind.buffer.assumingMemoryBound(to: Int16.self).deallocate() case MYSQL_TYPE_TINY: bind.buffer.assumingMemoryBound(to: Int8.self).deallocate() default: break } } case .bytes, .string, .date, .null: () // do nothing. these were cleaned right after use or not allocated at all } } } } }
29.069714
115
0.702823
fba88de49a1b25d55e1f828916114d4083bd59e3
53,905
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ // This file was generated from JSON Schema. Do not modify it directly. internal protocol RUMDataModel: Codable {} /// Schema of all properties of a View event public struct RUMViewEvent: RUMDataModel { /// Internal properties public let dd: DD /// Application properties public let application: Application /// CI Visibility properties public let ciTest: CiTest? /// Device connectivity properties public let connectivity: RUMConnectivity? /// User provided context public internal(set) var context: RUMEventAttributes? /// Start of the event in ms from epoch public let date: Int64 /// The service name for this application public let service: String? /// Session properties public let session: Session /// The source of this event public let source: Source? /// Synthetics properties public let synthetics: Synthetics? /// RUM event type public let type: String = "view" /// User properties public internal(set) var usr: RUMUser? /// View properties public var view: View enum CodingKeys: String, CodingKey { case dd = "_dd" case application = "application" case ciTest = "ci_test" case connectivity = "connectivity" case context = "context" case date = "date" case service = "service" case session = "session" case source = "source" case synthetics = "synthetics" case type = "type" case usr = "usr" case view = "view" } /// Internal properties public struct DD: Codable { /// Browser SDK version public let browserSdkVersion: String? /// Version of the update of the view event public let documentVersion: Int64 /// Version of the RUM event format public let formatVersion: Int64 = 2 /// Session-related internal properties public let session: Session? enum CodingKeys: String, CodingKey { case browserSdkVersion = "browser_sdk_version" case documentVersion = "document_version" case formatVersion = "format_version" case session = "session" } /// Session-related internal properties public struct Session: Codable { /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public let plan: Plan enum CodingKeys: String, CodingKey { case plan = "plan" } /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public enum Plan: Int, Codable { case plan1 = 1 case plan2 = 2 } } } /// Application properties public struct Application: Codable { /// UUID of the application public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// CI Visibility properties public struct CiTest: Codable { /// The identifier of the current CI Visibility test execution public let testExecutionId: String enum CodingKeys: String, CodingKey { case testExecutionId = "test_execution_id" } } /// Session properties public struct Session: Codable { /// Whether this session has a replay public let hasReplay: Bool? /// UUID of the session public let id: String /// Type of the session public let type: SessionType enum CodingKeys: String, CodingKey { case hasReplay = "has_replay" case id = "id" case type = "type" } /// Type of the session public enum SessionType: String, Codable { case user = "user" case synthetics = "synthetics" case ciTest = "ci_test" } } /// The source of this event public enum Source: String, Codable { case android = "android" case ios = "ios" case browser = "browser" case flutter = "flutter" case reactNative = "react-native" } /// Synthetics properties public struct Synthetics: Codable { /// Whether the event comes from a SDK instance injected by Synthetics public let injected: Bool? /// The identifier of the current Synthetics test results public let resultId: String /// The identifier of the current Synthetics test public let testId: String enum CodingKeys: String, CodingKey { case injected = "injected" case resultId = "result_id" case testId = "test_id" } } /// View properties public struct View: Codable { /// Properties of the actions of the view public let action: Action /// Total number of cpu ticks during the view’s lifetime public let cpuTicksCount: Double? /// Average number of cpu ticks per second during the view’s lifetime public let cpuTicksPerSecond: Double? /// Properties of the crashes of the view public let crash: Crash? /// Total layout shift score that occured on the view public let cumulativeLayoutShift: Double? /// User custom timings of the view. As timing name is used as facet path, it must contain only letters, digits, or the characters - _ . @ $ public let customTimings: [String: Int64]? /// Duration in ns to the complete parsing and loading of the document and its sub resources public let domComplete: Int64? /// Duration in ns to the complete parsing and loading of the document without its sub resources public let domContentLoaded: Int64? /// Duration in ns to the end of the parsing of the document public let domInteractive: Int64? /// Properties of the errors of the view public let error: Error /// Duration in ns to the first rendering public let firstContentfulPaint: Int64? /// Duration in ns of the first input event delay public let firstInputDelay: Int64? /// Duration in ns to the first input public let firstInputTime: Int64? /// Properties of the frozen frames of the view public let frozenFrame: FrozenFrame? /// UUID of the view public let id: String /// List of the periods of time the user had the view in foreground (focused in the browser) public let inForegroundPeriods: [InForegroundPeriods]? /// Whether the View corresponding to this event is considered active public let isActive: Bool? /// Whether the View had a low average refresh rate public let isSlowRendered: Bool? /// Duration in ns to the largest contentful paint public let largestContentfulPaint: Int64? /// Duration in ns to the end of the load event handler execution public let loadEvent: Int64? /// Duration in ns to the view is considered loaded public let loadingTime: Int64? /// Type of the loading of the view public let loadingType: LoadingType? /// Properties of the long tasks of the view public let longTask: LongTask? /// Average memory used during the view lifetime (in bytes) public let memoryAverage: Double? /// Peak memory used during the view lifetime (in bytes) public let memoryMax: Double? /// User defined name of the view public var name: String? /// URL that linked to the initial view of the page public var referrer: String? /// Average refresh rate during the view’s lifetime (in frames per second) public let refreshRateAverage: Double? /// Minimum refresh rate during the view’s lifetime (in frames per second) public let refreshRateMin: Double? /// Properties of the resources of the view public let resource: Resource /// Time spent on the view in ns public let timeSpent: Int64 /// URL of the view public var url: String enum CodingKeys: String, CodingKey { case action = "action" case cpuTicksCount = "cpu_ticks_count" case cpuTicksPerSecond = "cpu_ticks_per_second" case crash = "crash" case cumulativeLayoutShift = "cumulative_layout_shift" case customTimings = "custom_timings" case domComplete = "dom_complete" case domContentLoaded = "dom_content_loaded" case domInteractive = "dom_interactive" case error = "error" case firstContentfulPaint = "first_contentful_paint" case firstInputDelay = "first_input_delay" case firstInputTime = "first_input_time" case frozenFrame = "frozen_frame" case id = "id" case inForegroundPeriods = "in_foreground_periods" case isActive = "is_active" case isSlowRendered = "is_slow_rendered" case largestContentfulPaint = "largest_contentful_paint" case loadEvent = "load_event" case loadingTime = "loading_time" case loadingType = "loading_type" case longTask = "long_task" case memoryAverage = "memory_average" case memoryMax = "memory_max" case name = "name" case referrer = "referrer" case refreshRateAverage = "refresh_rate_average" case refreshRateMin = "refresh_rate_min" case resource = "resource" case timeSpent = "time_spent" case url = "url" } /// Properties of the actions of the view public struct Action: Codable { /// Number of actions that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the crashes of the view public struct Crash: Codable { /// Number of crashes that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the errors of the view public struct Error: Codable { /// Number of errors that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the frozen frames of the view public struct FrozenFrame: Codable { /// Number of frozen frames that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the foreground period of the view public struct InForegroundPeriods: Codable { /// Duration in ns of the view foreground period public let duration: Int64 /// Duration in ns between start of the view and start of foreground period public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// Type of the loading of the view public enum LoadingType: String, Codable { case initialLoad = "initial_load" case routeChange = "route_change" case activityDisplay = "activity_display" case activityRedisplay = "activity_redisplay" case fragmentDisplay = "fragment_display" case fragmentRedisplay = "fragment_redisplay" case viewControllerDisplay = "view_controller_display" case viewControllerRedisplay = "view_controller_redisplay" } /// Properties of the long tasks of the view public struct LongTask: Codable { /// Number of long tasks that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the resources of the view public struct Resource: Codable { /// Number of resources that occurred on the view public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } } } /// Schema of all properties of a Resource event public struct RUMResourceEvent: RUMDataModel { /// Internal properties public let dd: DD /// Action properties public let action: Action? /// Application properties public let application: Application /// CI Visibility properties public let ciTest: CiTest? /// Device connectivity properties public let connectivity: RUMConnectivity? /// User provided context public internal(set) var context: RUMEventAttributes? /// Start of the event in ms from epoch public let date: Int64 /// Resource properties public var resource: Resource /// The service name for this application public let service: String? /// Session properties public let session: Session /// The source of this event public let source: Source? /// Synthetics properties public let synthetics: Synthetics? /// RUM event type public let type: String = "resource" /// User properties public internal(set) var usr: RUMUser? /// View properties public var view: View enum CodingKeys: String, CodingKey { case dd = "_dd" case action = "action" case application = "application" case ciTest = "ci_test" case connectivity = "connectivity" case context = "context" case date = "date" case resource = "resource" case service = "service" case session = "session" case source = "source" case synthetics = "synthetics" case type = "type" case usr = "usr" case view = "view" } /// Internal properties public struct DD: Codable { /// Browser SDK version public let browserSdkVersion: String? /// Version of the RUM event format public let formatVersion: Int64 = 2 /// Session-related internal properties public let session: Session? /// span identifier in decimal format public let spanId: String? /// trace identifier in decimal format public let traceId: String? enum CodingKeys: String, CodingKey { case browserSdkVersion = "browser_sdk_version" case formatVersion = "format_version" case session = "session" case spanId = "span_id" case traceId = "trace_id" } /// Session-related internal properties public struct Session: Codable { /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public let plan: Plan enum CodingKeys: String, CodingKey { case plan = "plan" } /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public enum Plan: Int, Codable { case plan1 = 1 case plan2 = 2 } } } /// Action properties public struct Action: Codable { /// UUID of the action public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// Application properties public struct Application: Codable { /// UUID of the application public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// CI Visibility properties public struct CiTest: Codable { /// The identifier of the current CI Visibility test execution public let testExecutionId: String enum CodingKeys: String, CodingKey { case testExecutionId = "test_execution_id" } } /// Resource properties public struct Resource: Codable { /// Connect phase properties public let connect: Connect? /// DNS phase properties public let dns: DNS? /// Download phase properties public let download: Download? /// Duration of the resource public let duration: Int64 /// First Byte phase properties public let firstByte: FirstByte? /// UUID of the resource public let id: String? /// HTTP method of the resource public let method: RUMMethod? /// The provider for this resource public let provider: Provider? /// Redirect phase properties public let redirect: Redirect? /// Size in octet of the resource response body public let size: Int64? /// SSL phase properties public let ssl: SSL? /// HTTP status code of the resource public let statusCode: Int64? /// Resource type public let type: ResourceType /// URL of the resource public var url: String enum CodingKeys: String, CodingKey { case connect = "connect" case dns = "dns" case download = "download" case duration = "duration" case firstByte = "first_byte" case id = "id" case method = "method" case provider = "provider" case redirect = "redirect" case size = "size" case ssl = "ssl" case statusCode = "status_code" case type = "type" case url = "url" } /// Connect phase properties public struct Connect: Codable { /// Duration in ns of the resource connect phase public let duration: Int64 /// Duration in ns between start of the request and start of the connect phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// DNS phase properties public struct DNS: Codable { /// Duration in ns of the resource dns phase public let duration: Int64 /// Duration in ns between start of the request and start of the dns phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// Download phase properties public struct Download: Codable { /// Duration in ns of the resource download phase public let duration: Int64 /// Duration in ns between start of the request and start of the download phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// First Byte phase properties public struct FirstByte: Codable { /// Duration in ns of the resource first byte phase public let duration: Int64 /// Duration in ns between start of the request and start of the first byte phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// The provider for this resource public struct Provider: Codable { /// The domain name of the provider public let domain: String? /// The user friendly name of the provider public let name: String? /// The type of provider public let type: ProviderType? enum CodingKeys: String, CodingKey { case domain = "domain" case name = "name" case type = "type" } /// The type of provider public enum ProviderType: String, Codable { case ad = "ad" case advertising = "advertising" case analytics = "analytics" case cdn = "cdn" case content = "content" case customerSuccess = "customer-success" case firstParty = "first party" case hosting = "hosting" case marketing = "marketing" case other = "other" case social = "social" case tagManager = "tag-manager" case utility = "utility" case video = "video" } } /// Redirect phase properties public struct Redirect: Codable { /// Duration in ns of the resource redirect phase public let duration: Int64 /// Duration in ns between start of the request and start of the redirect phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// SSL phase properties public struct SSL: Codable { /// Duration in ns of the resource ssl phase public let duration: Int64 /// Duration in ns between start of the request and start of the ssl phase public let start: Int64 enum CodingKeys: String, CodingKey { case duration = "duration" case start = "start" } } /// Resource type public enum ResourceType: String, Codable { case document = "document" case xhr = "xhr" case beacon = "beacon" case fetch = "fetch" case css = "css" case js = "js" case image = "image" case font = "font" case media = "media" case other = "other" case native = "native" } } /// Session properties public struct Session: Codable { /// Whether this session has a replay public let hasReplay: Bool? /// UUID of the session public let id: String /// Type of the session public let type: SessionType enum CodingKeys: String, CodingKey { case hasReplay = "has_replay" case id = "id" case type = "type" } /// Type of the session public enum SessionType: String, Codable { case user = "user" case synthetics = "synthetics" case ciTest = "ci_test" } } /// The source of this event public enum Source: String, Codable { case android = "android" case ios = "ios" case browser = "browser" case flutter = "flutter" case reactNative = "react-native" } /// Synthetics properties public struct Synthetics: Codable { /// Whether the event comes from a SDK instance injected by Synthetics public let injected: Bool? /// The identifier of the current Synthetics test results public let resultId: String /// The identifier of the current Synthetics test public let testId: String enum CodingKeys: String, CodingKey { case injected = "injected" case resultId = "result_id" case testId = "test_id" } } /// View properties public struct View: Codable { /// UUID of the view public let id: String /// User defined name of the view public var name: String? /// URL that linked to the initial view of the page public var referrer: String? /// URL of the view public var url: String enum CodingKeys: String, CodingKey { case id = "id" case name = "name" case referrer = "referrer" case url = "url" } } } /// Schema of all properties of an Action event public struct RUMActionEvent: RUMDataModel { /// Internal properties public let dd: DD /// Action properties public var action: Action /// Application properties public let application: Application /// CI Visibility properties public let ciTest: CiTest? /// Device connectivity properties public let connectivity: RUMConnectivity? /// User provided context public internal(set) var context: RUMEventAttributes? /// Start of the event in ms from epoch public let date: Int64 /// The service name for this application public let service: String? /// Session properties public let session: Session /// The source of this event public let source: Source? /// Synthetics properties public let synthetics: Synthetics? /// RUM event type public let type: String = "action" /// User properties public internal(set) var usr: RUMUser? /// View properties public var view: View enum CodingKeys: String, CodingKey { case dd = "_dd" case action = "action" case application = "application" case ciTest = "ci_test" case connectivity = "connectivity" case context = "context" case date = "date" case service = "service" case session = "session" case source = "source" case synthetics = "synthetics" case type = "type" case usr = "usr" case view = "view" } /// Internal properties public struct DD: Codable { /// Browser SDK version public let browserSdkVersion: String? /// Version of the RUM event format public let formatVersion: Int64 = 2 /// Session-related internal properties public let session: Session? enum CodingKeys: String, CodingKey { case browserSdkVersion = "browser_sdk_version" case formatVersion = "format_version" case session = "session" } /// Session-related internal properties public struct Session: Codable { /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public let plan: Plan enum CodingKeys: String, CodingKey { case plan = "plan" } /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public enum Plan: Int, Codable { case plan1 = 1 case plan2 = 2 } } } /// Action properties public struct Action: Codable { /// Properties of the crashes of the action public let crash: Crash? /// Properties of the errors of the action public let error: Error? /// UUID of the action public let id: String? /// Duration in ns to the action is considered loaded public let loadingTime: Int64? /// Properties of the long tasks of the action public let longTask: LongTask? /// Properties of the resources of the action public let resource: Resource? /// Action target properties public var target: Target? /// Type of the action public let type: ActionType enum CodingKeys: String, CodingKey { case crash = "crash" case error = "error" case id = "id" case loadingTime = "loading_time" case longTask = "long_task" case resource = "resource" case target = "target" case type = "type" } /// Properties of the crashes of the action public struct Crash: Codable { /// Number of crashes that occurred on the action public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the errors of the action public struct Error: Codable { /// Number of errors that occurred on the action public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the long tasks of the action public struct LongTask: Codable { /// Number of long tasks that occurred on the action public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Properties of the resources of the action public struct Resource: Codable { /// Number of resources that occurred on the action public let count: Int64 enum CodingKeys: String, CodingKey { case count = "count" } } /// Action target properties public struct Target: Codable { /// Target name public var name: String enum CodingKeys: String, CodingKey { case name = "name" } } /// Type of the action public enum ActionType: String, Codable { case custom = "custom" case click = "click" case tap = "tap" case scroll = "scroll" case swipe = "swipe" case applicationStart = "application_start" case back = "back" } } /// Application properties public struct Application: Codable { /// UUID of the application public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// CI Visibility properties public struct CiTest: Codable { /// The identifier of the current CI Visibility test execution public let testExecutionId: String enum CodingKeys: String, CodingKey { case testExecutionId = "test_execution_id" } } /// Session properties public struct Session: Codable { /// Whether this session has a replay public let hasReplay: Bool? /// UUID of the session public let id: String /// Type of the session public let type: SessionType enum CodingKeys: String, CodingKey { case hasReplay = "has_replay" case id = "id" case type = "type" } /// Type of the session public enum SessionType: String, Codable { case user = "user" case synthetics = "synthetics" case ciTest = "ci_test" } } /// The source of this event public enum Source: String, Codable { case android = "android" case ios = "ios" case browser = "browser" case flutter = "flutter" case reactNative = "react-native" } /// Synthetics properties public struct Synthetics: Codable { /// Whether the event comes from a SDK instance injected by Synthetics public let injected: Bool? /// The identifier of the current Synthetics test results public let resultId: String /// The identifier of the current Synthetics test public let testId: String enum CodingKeys: String, CodingKey { case injected = "injected" case resultId = "result_id" case testId = "test_id" } } /// View properties public struct View: Codable { /// UUID of the view public let id: String /// Is the action starting in the foreground (focus in browser) public let inForeground: Bool? /// User defined name of the view public var name: String? /// URL that linked to the initial view of the page public var referrer: String? /// URL of the view public var url: String enum CodingKeys: String, CodingKey { case id = "id" case inForeground = "in_foreground" case name = "name" case referrer = "referrer" case url = "url" } } } /// Schema of all properties of an Error event public struct RUMErrorEvent: RUMDataModel { /// Internal properties public let dd: DD /// Action properties public let action: Action? /// Application properties public let application: Application /// CI Visibility properties public let ciTest: CiTest? /// Device connectivity properties public let connectivity: RUMConnectivity? /// User provided context public internal(set) var context: RUMEventAttributes? /// Start of the event in ms from epoch public let date: Int64 /// Error properties public var error: Error /// The service name for this application public let service: String? /// Session properties public let session: Session /// The source of this event public let source: Source? /// Synthetics properties public let synthetics: Synthetics? /// RUM event type public let type: String = "error" /// User properties public internal(set) var usr: RUMUser? /// View properties public var view: View enum CodingKeys: String, CodingKey { case dd = "_dd" case action = "action" case application = "application" case ciTest = "ci_test" case connectivity = "connectivity" case context = "context" case date = "date" case error = "error" case service = "service" case session = "session" case source = "source" case synthetics = "synthetics" case type = "type" case usr = "usr" case view = "view" } /// Internal properties public struct DD: Codable { /// Browser SDK version public let browserSdkVersion: String? /// Version of the RUM event format public let formatVersion: Int64 = 2 /// Session-related internal properties public let session: Session? enum CodingKeys: String, CodingKey { case browserSdkVersion = "browser_sdk_version" case formatVersion = "format_version" case session = "session" } /// Session-related internal properties public struct Session: Codable { /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public let plan: Plan enum CodingKeys: String, CodingKey { case plan = "plan" } /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public enum Plan: Int, Codable { case plan1 = 1 case plan2 = 2 } } } /// Action properties public struct Action: Codable { /// UUID of the action public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// Application properties public struct Application: Codable { /// UUID of the application public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// CI Visibility properties public struct CiTest: Codable { /// The identifier of the current CI Visibility test execution public let testExecutionId: String enum CodingKeys: String, CodingKey { case testExecutionId = "test_execution_id" } } /// Error properties public struct Error: Codable { /// Whether the error has been handled manually in the source code or not public let handling: Handling? /// Handling call stack public let handlingStack: String? /// UUID of the error public let id: String? /// Whether this error crashed the host application public let isCrash: Bool? /// Error message public var message: String /// Resource properties of the error public var resource: Resource? /// Source of the error public let source: Source /// Source type of the error (the language or platform impacting the error stacktrace format) public let sourceType: SourceType? /// Stacktrace of the error public var stack: String? /// The type of the error public let type: String? enum CodingKeys: String, CodingKey { case handling = "handling" case handlingStack = "handling_stack" case id = "id" case isCrash = "is_crash" case message = "message" case resource = "resource" case source = "source" case sourceType = "source_type" case stack = "stack" case type = "type" } /// Whether the error has been handled manually in the source code or not public enum Handling: String, Codable { case handled = "handled" case unhandled = "unhandled" } /// Resource properties of the error public struct Resource: Codable { /// HTTP method of the resource public let method: RUMMethod /// The provider for this resource public let provider: Provider? /// HTTP Status code of the resource public let statusCode: Int64 /// URL of the resource public var url: String enum CodingKeys: String, CodingKey { case method = "method" case provider = "provider" case statusCode = "status_code" case url = "url" } /// The provider for this resource public struct Provider: Codable { /// The domain name of the provider public let domain: String? /// The user friendly name of the provider public let name: String? /// The type of provider public let type: ProviderType? enum CodingKeys: String, CodingKey { case domain = "domain" case name = "name" case type = "type" } /// The type of provider public enum ProviderType: String, Codable { case ad = "ad" case advertising = "advertising" case analytics = "analytics" case cdn = "cdn" case content = "content" case customerSuccess = "customer-success" case firstParty = "first party" case hosting = "hosting" case marketing = "marketing" case other = "other" case social = "social" case tagManager = "tag-manager" case utility = "utility" case video = "video" } } } /// Source of the error public enum Source: String, Codable { case network = "network" case source = "source" case console = "console" case logger = "logger" case agent = "agent" case webview = "webview" case custom = "custom" } /// Source type of the error (the language or platform impacting the error stacktrace format) public enum SourceType: String, Codable { case android = "android" case browser = "browser" case ios = "ios" case reactNative = "react-native" case flutter = "flutter" } } /// Session properties public struct Session: Codable { /// Whether this session has a replay public let hasReplay: Bool? /// UUID of the session public let id: String /// Type of the session public let type: SessionType enum CodingKeys: String, CodingKey { case hasReplay = "has_replay" case id = "id" case type = "type" } /// Type of the session public enum SessionType: String, Codable { case user = "user" case synthetics = "synthetics" case ciTest = "ci_test" } } /// The source of this event public enum Source: String, Codable { case android = "android" case ios = "ios" case browser = "browser" case flutter = "flutter" case reactNative = "react-native" } /// Synthetics properties public struct Synthetics: Codable { /// Whether the event comes from a SDK instance injected by Synthetics public let injected: Bool? /// The identifier of the current Synthetics test results public let resultId: String /// The identifier of the current Synthetics test public let testId: String enum CodingKeys: String, CodingKey { case injected = "injected" case resultId = "result_id" case testId = "test_id" } } /// View properties public struct View: Codable { /// UUID of the view public let id: String /// Is the error starting in the foreground (focus in browser) public let inForeground: Bool? /// User defined name of the view public var name: String? /// URL that linked to the initial view of the page public var referrer: String? /// URL of the view public var url: String enum CodingKeys: String, CodingKey { case id = "id" case inForeground = "in_foreground" case name = "name" case referrer = "referrer" case url = "url" } } } /// Schema of all properties of a Long Task event public struct RUMLongTaskEvent: RUMDataModel { /// Internal properties public let dd: DD /// Action properties public let action: Action? /// Application properties public let application: Application /// CI Visibility properties public let ciTest: CiTest? /// Device connectivity properties public let connectivity: RUMConnectivity? /// User provided context public internal(set) var context: RUMEventAttributes? /// Start of the event in ms from epoch public let date: Int64 /// Long Task properties public let longTask: LongTask /// The service name for this application public let service: String? /// Session properties public let session: Session /// The source of this event public let source: Source? /// Synthetics properties public let synthetics: Synthetics? /// RUM event type public let type: String = "long_task" /// User properties public internal(set) var usr: RUMUser? /// View properties public var view: View enum CodingKeys: String, CodingKey { case dd = "_dd" case action = "action" case application = "application" case ciTest = "ci_test" case connectivity = "connectivity" case context = "context" case date = "date" case longTask = "long_task" case service = "service" case session = "session" case source = "source" case synthetics = "synthetics" case type = "type" case usr = "usr" case view = "view" } /// Internal properties public struct DD: Codable { /// Browser SDK version public let browserSdkVersion: String? /// Version of the RUM event format public let formatVersion: Int64 = 2 /// Session-related internal properties public let session: Session? enum CodingKeys: String, CodingKey { case browserSdkVersion = "browser_sdk_version" case formatVersion = "format_version" case session = "session" } /// Session-related internal properties public struct Session: Codable { /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public let plan: Plan enum CodingKeys: String, CodingKey { case plan = "plan" } /// Session plan: 1 is the 'lite' plan, 2 is the 'replay' plan public enum Plan: Int, Codable { case plan1 = 1 case plan2 = 2 } } } /// Action properties public struct Action: Codable { /// UUID of the action public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// Application properties public struct Application: Codable { /// UUID of the application public let id: String enum CodingKeys: String, CodingKey { case id = "id" } } /// CI Visibility properties public struct CiTest: Codable { /// The identifier of the current CI Visibility test execution public let testExecutionId: String enum CodingKeys: String, CodingKey { case testExecutionId = "test_execution_id" } } /// Long Task properties public struct LongTask: Codable { /// Duration in ns of the long task public let duration: Int64 /// UUID of the long task public let id: String? /// Whether this long task is considered a frozen frame public let isFrozenFrame: Bool? enum CodingKeys: String, CodingKey { case duration = "duration" case id = "id" case isFrozenFrame = "is_frozen_frame" } } /// Session properties public struct Session: Codable { /// Whether this session has a replay public let hasReplay: Bool? /// UUID of the session public let id: String /// Type of the session public let type: SessionType enum CodingKeys: String, CodingKey { case hasReplay = "has_replay" case id = "id" case type = "type" } /// Type of the session public enum SessionType: String, Codable { case user = "user" case synthetics = "synthetics" case ciTest = "ci_test" } } /// The source of this event public enum Source: String, Codable { case android = "android" case ios = "ios" case browser = "browser" case flutter = "flutter" case reactNative = "react-native" } /// Synthetics properties public struct Synthetics: Codable { /// Whether the event comes from a SDK instance injected by Synthetics public let injected: Bool? /// The identifier of the current Synthetics test results public let resultId: String /// The identifier of the current Synthetics test public let testId: String enum CodingKeys: String, CodingKey { case injected = "injected" case resultId = "result_id" case testId = "test_id" } } /// View properties public struct View: Codable { /// UUID of the view public let id: String /// User defined name of the view public var name: String? /// URL that linked to the initial view of the page public var referrer: String? /// URL of the view public var url: String enum CodingKeys: String, CodingKey { case id = "id" case name = "name" case referrer = "referrer" case url = "url" } } } /// Device connectivity properties public struct RUMConnectivity: Codable { /// Cellular connectivity properties public let cellular: Cellular? /// The list of available network interfaces public let interfaces: [Interfaces] /// Status of the device connectivity public let status: Status enum CodingKeys: String, CodingKey { case cellular = "cellular" case interfaces = "interfaces" case status = "status" } /// Cellular connectivity properties public struct Cellular: Codable { /// The name of the SIM carrier public let carrierName: String? /// The type of a radio technology used for cellular connection public let technology: String? enum CodingKeys: String, CodingKey { case carrierName = "carrier_name" case technology = "technology" } } public enum Interfaces: String, Codable { case bluetooth = "bluetooth" case cellular = "cellular" case ethernet = "ethernet" case wifi = "wifi" case wimax = "wimax" case mixed = "mixed" case other = "other" case unknown = "unknown" case none = "none" } /// Status of the device connectivity public enum Status: String, Codable { case connected = "connected" case notConnected = "not_connected" case maybe = "maybe" } } /// User provided context public struct RUMEventAttributes: Codable { public internal(set) var contextInfo: [String: Encodable] struct DynamicCodingKey: CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { return nil } init(_ string: String) { self.stringValue = string } } } extension RUMEventAttributes { public func encode(to encoder: Encoder) throws { // Encode dynamic properties: var dynamicContainer = encoder.container(keyedBy: DynamicCodingKey.self) try contextInfo.forEach { let key = DynamicCodingKey($0) try dynamicContainer.encode(CodableValue($1), forKey: key) } } public init(from decoder: Decoder) throws { // Decode other properties into [String: Codable] dictionary: let dynamicContainer = try decoder.container(keyedBy: DynamicCodingKey.self) let dynamicKeys = dynamicContainer.allKeys var dictionary: [String: Codable] = [:] try dynamicKeys.forEach { codingKey in dictionary[codingKey.stringValue] = try dynamicContainer.decode(CodableValue.self, forKey: codingKey) } self.contextInfo = dictionary } } /// User properties public struct RUMUser: Codable { /// Email of the user public let email: String? /// Identifier of the user public let id: String? /// Name of the user public let name: String? public internal(set) var usrInfo: [String: Encodable] enum StaticCodingKeys: String, CodingKey { case email = "email" case id = "id" case name = "name" } struct DynamicCodingKey: CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { return nil } init(_ string: String) { self.stringValue = string } } } extension RUMUser { public func encode(to encoder: Encoder) throws { // Encode static properties: var staticContainer = encoder.container(keyedBy: StaticCodingKeys.self) try staticContainer.encodeIfPresent(email, forKey: .email) try staticContainer.encodeIfPresent(id, forKey: .id) try staticContainer.encodeIfPresent(name, forKey: .name) // Encode dynamic properties: var dynamicContainer = encoder.container(keyedBy: DynamicCodingKey.self) try usrInfo.forEach { let key = DynamicCodingKey($0) try dynamicContainer.encode(CodableValue($1), forKey: key) } } public init(from decoder: Decoder) throws { // Decode static properties: let staticContainer = try decoder.container(keyedBy: StaticCodingKeys.self) self.email = try staticContainer.decodeIfPresent(String.self, forKey: .email) self.id = try staticContainer.decodeIfPresent(String.self, forKey: .id) self.name = try staticContainer.decodeIfPresent(String.self, forKey: .name) // Decode other properties into [String: Codable] dictionary: let dynamicContainer = try decoder.container(keyedBy: DynamicCodingKey.self) let allStaticKeys = Set(staticContainer.allKeys.map { $0.stringValue }) let dynamicKeys = dynamicContainer.allKeys.filter { !allStaticKeys.contains($0.stringValue) } var dictionary: [String: Codable] = [:] try dynamicKeys.forEach { codingKey in dictionary[codingKey.stringValue] = try dynamicContainer.decode(CodableValue.self, forKey: codingKey) } self.usrInfo = dictionary } } /// HTTP method of the resource public enum RUMMethod: String, Codable { case post = "POST" case get = "GET" case head = "HEAD" case put = "PUT" case delete = "DELETE" case patch = "PATCH" } // Generated from https://github.com/DataDog/rum-events-format/tree/114c173caac5ea15446a157b666acbab05431361
29.536986
148
0.577386
fe31bef85c08894f2466eb419702798fd646be5b
71
import Foundation protocol RuuviTagRouterInput { func dismiss() }
11.833333
30
0.760563
4a64e4ba88ba33a992f978605cc974bb7d65f8c0
643
// // ItemCell.swift // HomePwner // // Created by Charles Kang on 7/1/16. // Copyright © 2016 Charles Kang. All rights reserved. // import UIKit class ItemCell: UITableViewCell { @IBOutlet var nameLabel: UILabel! @IBOutlet var serialNumberLabel: UILabel! @IBOutlet var valueLabel: UILabel! func updateLabels() { let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) nameLabel.font = bodyFont valueLabel.font = bodyFont let caption1Font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) serialNumberLabel.font = caption1Font } }
23.814815
84
0.684292
9c4fe531e9ac33b0c7b9777b353b4b4ffa66b2f7
2,833
// // NVActivityIndicatorAnimationLineScalePulseOutRapid.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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(UIKit) import UIKit class NVActivityIndicatorAnimationLineScalePulseOutRapid: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 0.9 let beginTime = CACurrentMediaTime() let beginTimes = [0.5, 0.25, 0, 0.25, 0.5] let timingFunction = CAMediaTimingFunction(controlPoints: 0.11, 0.49, 0.38, 0.78) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.8, 0.9] animation.timingFunctions = [timingFunction, timingFunction] animation.beginTime = beginTime animation.values = [1, 0.3, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw lines for i in 0 ..< 5 { let line = NVActivityIndicatorShape.line.layerWith(x: 0, y: 0, size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } } #endif
41.057971
140
0.671726
29ad3934347417092be59d43586b3dd4752ce3a7
362
// // CharacterSet.ext.swift // FoundationExt // // Created by chapayGhub on 12/24/17. // import Foundation extension CharacterSet { public static var spaceCharacterSet: CharacterSet = { let set = NSMutableCharacterSet(charactersIn: "\u{00a0}") set.formUnion(with: CharacterSet.whitespacesAndNewlines) return set as CharacterSet }() }
19.052632
61
0.712707
14b9adf3456b951059f1545d94c4993c49cf942b
1,073
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Koalas", platforms: [ .macOS(.v10_15), .iOS(.v8) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Koalas", targets: ["Koalas"]), ], 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: "Koalas", dependencies: []), .testTarget( name: "KoalasTests", dependencies: ["Koalas"]), ] )
31.558824
122
0.599254
01df5327d5f897fcf2f0b1b03e71076ae7c08a63
4,208
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() final class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod(message: dataSourceNotSet) } } /// For more information take a look at `DelegateProxyType`. public class RxCollectionViewDataSourceProxy : DelegateProxy , UICollectionViewDataSource , DelegateProxyType { /// Typed parent object. public weak private(set) var collectionView: UICollectionView? private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet /// Initializes `RxCollectionViewDataSourceProxy` /// /// - parameter parentObject: Parent object for delegate proxy. public required init(parentObject: AnyObject) { self.collectionView = castOrFatalError(parentObject) super.init(parentObject: parentObject) } // MARK: delegate /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) } /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) } // MARK: proxy /// For more information take a look at `DelegateProxyType`. public override class func createProxyForObject(_ object: AnyObject) -> AnyObject { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.createRxDataSourceProxy() } /// For more information take a look at `DelegateProxyType`. public override class func delegateAssociatedObjectTag() -> UnsafeRawPointer { return dataSourceAssociatedTag } /// For more information take a look at `DelegateProxyType`. public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UICollectionView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } /// For more information take a look at `DelegateProxyType`. public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.dataSource } /// For more information take a look at `DelegateProxyType`. public override func setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UICollectionViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) self.refreshCollectionViewDataSource() } private func refreshCollectionViewDataSource() { if self.collectionView?.dataSource === self { if _requiredMethodsDataSource != nil && _requiredMethodsDataSource !== collectionViewDataSourceNotSet { self.collectionView?.dataSource = self } else { self.collectionView?.dataSource = nil } } } } #endif
37.90991
141
0.735266
6abf787700fc459062cab59721b23a4f2a7a0129
7,181
import UIKit /// View controller used for showing info text and loading animation. public final class MessageViewController: UIViewController { // Image tint color for all the states, except for `.notFound`. public var regularTintColor: UIColor = .black // Image tint color for `.notFound` state. public var errorTintColor: UIColor = .red // Customizable state messages. public var messages = StateMessageProvider() // MARK: - UI properties /// Text label. public private(set) lazy var textLabel: UILabel = self.makeTextLabel() /// Info image view. public private(set) lazy var imageView: UIImageView = self.makeImageView() /// Border view. public private(set) lazy var borderView: UIView = self.makeBorderView() /// Blur effect view. private lazy var blurView: UIVisualEffectView = .init(effect: UIBlurEffect(style: .extraLight)) // Constraints that are activated when the view is used as a footer. private lazy var collapsedConstraints: [NSLayoutConstraint] = self.makeCollapsedConstraints() // Constraints that are activated when the view is used for loading animation and error messages. private lazy var expandedConstraints: [NSLayoutConstraint] = self.makeExpandedConstraints() var status = Status(state: .scanning) { didSet { handleStatusUpdate() } } // MARK: - View lifecycle public override func viewDidLoad() { super.viewDidLoad() view.addSubview(blurView) blurView.contentView.addSubviews(textLabel, imageView, borderView) handleStatusUpdate() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() blurView.frame = CGRect.zero } // MARK: - Animations /// Animates blur and border view. func animateLoading() { animate(blurStyle: .light) animate(borderViewAngle: CGFloat(Double.pi/2)) } /** Animates blur to make pulsating effect. - Parameter style: The current blur style. */ private func animate(blurStyle: UIBlurEffect.Style) { guard status.state == .processing else { return } UIView.animate( withDuration: 2.0, delay: 0.5, options: [.beginFromCurrentState], animations: ({ [weak self] in self?.blurView.effect = UIBlurEffect(style: blurStyle) }), completion: ({ [weak self] _ in self?.animate(blurStyle: blurStyle == .light ? .extraLight : .light) })) } /** Animates border view with a given angle. - Parameter angle: Rotation angle. */ private func animate(borderViewAngle: CGFloat) { guard status.state == .processing else { borderView.transform = .identity return } UIView.animate( withDuration: 0.8, delay: 0.5, usingSpringWithDamping: 0.6, initialSpringVelocity: 1.0, options: [.beginFromCurrentState], animations: ({ [weak self] in self?.borderView.transform = CGAffineTransform(rotationAngle: borderViewAngle) }), completion: ({ [weak self] _ in self?.animate(borderViewAngle: borderViewAngle + CGFloat(Double.pi / 2)) })) } // MARK: - State handling private func handleStatusUpdate() { borderView.isHidden = true borderView.layer.removeAllAnimations() textLabel.text = status.text ?? messages.makeText(for: status.state) switch status.state { case .scanning, .unauthorized: textLabel.numberOfLines = 3 textLabel.textAlignment = .left imageView.tintColor = regularTintColor case .processing: textLabel.numberOfLines = 10 textLabel.textAlignment = .center borderView.isHidden = false imageView.tintColor = regularTintColor case .notFound: textLabel.font = UIFont.boldSystemFont(ofSize: 16) textLabel.numberOfLines = 10 textLabel.textAlignment = .center imageView.tintColor = errorTintColor } if status.state == .scanning || status.state == .unauthorized { expandedConstraints.deactivate() collapsedConstraints.activate() } else { collapsedConstraints.deactivate() expandedConstraints.activate() } } } // MARK: - Subviews factory private extension MessageViewController { func makeTextLabel() -> UILabel { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .black label.numberOfLines = 3 label.font = UIFont.boldSystemFont(ofSize: 14) return label } func makeImageView() -> UIImageView { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = imageNamed("info").withRenderingMode(.alwaysTemplate) imageView.tintColor = .black return imageView } func makeBorderView() -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .clear view.layer.borderWidth = 2 view.layer.cornerRadius = 10 view.layer.borderColor = UIColor.black.cgColor return view } } // MARK: - Layout extension MessageViewController { private func makeExpandedConstraints() -> [NSLayoutConstraint] { let padding: CGFloat = 10 let borderSize: CGFloat = 51 return [ imageView.centerYAnchor.constraint(equalTo: blurView.centerYAnchor, constant: -60), imageView.centerXAnchor.constraint(equalTo: blurView.centerXAnchor), imageView.widthAnchor.constraint(equalToConstant: 30), imageView.heightAnchor.constraint(equalToConstant: 27), textLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 18), textLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding), textLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding), borderView.topAnchor.constraint(equalTo: imageView.topAnchor, constant: -12), borderView.centerXAnchor.constraint(equalTo: blurView.centerXAnchor), borderView.widthAnchor.constraint(equalToConstant: borderSize), borderView.heightAnchor.constraint(equalToConstant: borderSize) ] } private func makeCollapsedConstraints() -> [NSLayoutConstraint] { let padding: CGFloat = 10 var constraints = [ imageView.topAnchor.constraint(equalTo: blurView.topAnchor, constant: 18), imageView.widthAnchor.constraint(equalToConstant: 30), imageView.heightAnchor.constraint(equalToConstant: 27), textLabel.topAnchor.constraint(equalTo: imageView.topAnchor, constant: -3), textLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10) ] if #available(iOS 11.0, *) { constraints += [ imageView.leadingAnchor.constraint( equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: padding ), textLabel.trailingAnchor.constraint( equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -padding ) ] } else { constraints += [ imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding), textLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding) ] } return constraints } }
32.346847
99
0.701852
d726d0e4d520cbff28a7229885743599732f9f0b
2,864
import UIKit public struct VKpageTitleStyleLine{ public var color = UIColor.red public var margin:CGFloat = 0 public var lineWidth:CGFloat = 2 public var isShadowAvailable = false public init(color:UIColor = .red,margin:CGFloat = 0,lineWidth:CGFloat = 2,isShadow:Bool = false) { self.color = color self.margin = margin self.lineWidth = lineWidth self.isShadowAvailable = isShadow } } public enum VKpageTitleStyle{ case none // (line color,margin,lineWidth,is shadow available) case line(VKpageTitleStyleLine) // ( image,image size ) case image(UIImage?,CGSize) } public class VKpageTitleStyleManager:CALayer{ var types = [VKpageTitleStyle].init() lazy var bottomImageLayer:CALayer = { let layer = CALayer.init() return layer }() public var hadAnimation = true var offsetY:CGFloat = 0 var bottomSingleLine:CALayer? public init(styles:[VKpageTitleStyle],size:CGSize,offsetY:CGFloat = 0) { super.init() self.frame = CGRect.init(origin: CGPoint.zero, size: size) backgroundColor = UIColor.clear.cgColor zPosition = -1 self.offsetY = offsetY self.types.append(contentsOf: styles) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public static func view(with styles:[VKpageTitleStyle]?,size:CGSize,offsetY:CGFloat = 0)->VKpageTitleStyleManager?{ guard let typs = styles else { return nil } return VKpageTitleStyleManager.init(styles: typs, size: size,offsetY: offsetY) } func setup(){ for style in types{ switch style { case .image(let image, let size): addSublayer(bottomImageLayer) let point = CGPoint.init(x: 0, y: self.frame.height - size.height - offsetY) bottomImageLayer.frame = CGRect.init(origin: point, size: size) bottomImageLayer.contents = image?.cgImage case .line(let style): let y = bounds.height-style.lineWidth/2-offsetY let start = CGPoint.init(x: style.margin, y: y) let end = CGPoint.init(x: bounds.width - style.margin, y: y) bottomSingleLine = CAShapeLayer.init(from: start, to: end, strokeColor: style.color, fillColor: style.color,lineWidth: style.lineWidth) if style.isShadowAvailable{ bottomSingleLine?.shadowColor = style.color.cgColor bottomSingleLine?.shadowOpacity = 0.7 bottomSingleLine?.shadowRadius = 5 } addSublayer(bottomSingleLine!) default: break } } } }
32.91954
151
0.604399
185d3a4a22026576a50f686ae8bdbba1e1e30302
210
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { let a { init<T { class case c,
21
87
0.742857
8f62e99bb6756f9887a7a44fb974bc9f081654dc
759
// // ViewController.swift // lista_compra // // Created by Yaser on 20/11/2020. // Copyright © 2020 Yaser . All rights reserved. // import UIKit class ListViewController: UIViewController { @IBOutlet weak var table: UITableView! var listHelper = ListDataSource() override func viewDidLoad() { super.viewDidLoad() self.table.dataSource = listHelper self.table.delegate = listHelper } @IBAction func unwind(_ unwindSegue: UIStoryboardSegue) { let sourceViewController = unwindSegue.source as! ItemViewController let name = sourceViewController.name let item = Item(name: name, isBought: false) listHelper.list.append(item) self.table.reloadData() } }
23
76
0.666667
de97b2e83fa05532601a7aff7255e9ce7b762c7b
1,632
// // CityListDialogView.swift // SmartMacOSUILibrary // // Created by Michael Rommel on 12.09.21. // import SwiftUI import SmartAILibrary struct CityListDialogView: View { @ObservedObject var viewModel: CityListDialogViewModel private var gridItemLayout = [GridItem(.fixed(250))] public init(viewModel: CityListDialogViewModel) { self.viewModel = viewModel } var body: some View { BaseDialogView(title: "Cities", mode: .portrait, viewModel: self.viewModel) { ScrollView(.vertical, showsIndicators: true, content: { LazyVStack(spacing: 4) { ForEach(self.viewModel.cityViewModels, id: \.self) { cityViewModel in CityView(viewModel: cityViewModel) .onTapGesture { cityViewModel.selectCity() } .padding(.top, 8) } } }) } } } #if DEBUG struct CityListDialogView_Previews: PreviewProvider { static var previews: some View { // swiftlint:disable:next redundant_discardable_let let _ = GameViewModel(preloadAssets: true) let player = Player(leader: .alexander) let city0 = City(name: "Berlin", at: HexPoint.invalid, capital: true, owner: player) let city1 = City(name: "Paris", at: HexPoint.invalid, capital: false, owner: player) let viewModel = CityListDialogViewModel( with: [city0, city1] ) CityListDialogView(viewModel: viewModel) } } #endif
25.5
92
0.584559
d7991c7352fdeec62a2b57195e65f0eddda946cf
8,818
// // MutableCharacteristic.swift // BlueCap // // Created by Troy Stribling on 8/9/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import CoreBluetooth // MARK: - MutableCharacteristic - public class MutableCharacteristic : NSObject { // MARK: Properties let profile: CharacteristicProfile fileprivate var centrals = [UUID : CBCentralInjectable]() fileprivate var queuedUpdates = [Data]() internal fileprivate(set) var _isUpdating = false fileprivate var processWriteRequestPromise: StreamPromise<(request: CBATTRequestInjectable, central: CBCentralInjectable)>? internal var _value: Data? let cbMutableChracteristic: CBMutableCharacteristicInjectable public internal(set) weak var service: MutableService? fileprivate var peripheralQueue: Queue? { return service?.peripheralManager?.peripheralQueue } public let uuid: CBUUID public var value: Data? { get { return peripheralQueue?.sync { return self._value } } set { peripheralQueue?.sync { self._value = newValue } } } public var isUpdating: Bool { get { return peripheralQueue?.sync { return self._isUpdating } ?? false } } public var name: String { return profile.name } public var stringValues: [String] { return profile.stringValues } public var permissions: CBAttributePermissions { return cbMutableChracteristic.permissions } public var properties: CBCharacteristicProperties { return cbMutableChracteristic.properties } public var subscribers: [CBCentralInjectable] { return peripheralQueue?.sync { return Array(self.centrals.values) } ?? [CBCentralInjectable]() } public var pendingUpdates : [Data] { return peripheralQueue?.sync { return Array(self.queuedUpdates) } ?? [Data]() } public var stringValue: [String:String]? { if let value = self.value { return self.profile.stringValue(value) } else { return nil } } public var canNotify : Bool { return self.propertyEnabled(.notify) || self.propertyEnabled(.indicate) || self.propertyEnabled(.notifyEncryptionRequired) || self.propertyEnabled(.indicateEncryptionRequired) } // MARK: Initializers public convenience init(profile: CharacteristicProfile) { self.init(cbMutableCharacteristic: CBMutableCharacteristic(type: profile.uuid, properties: profile.properties, value: nil, permissions: profile.permissions), profile: profile) } internal init(cbMutableCharacteristic: CBMutableCharacteristicInjectable, profile: CharacteristicProfile) { self.profile = profile self._value = profile.initialValue self.cbMutableChracteristic = cbMutableCharacteristic uuid = CBUUID(data: cbMutableCharacteristic.uuid.data) } internal init(cbMutableCharacteristic: CBMutableCharacteristicInjectable) { self.profile = CharacteristicProfile(uuid: cbMutableCharacteristic.uuid.uuidString) self._value = profile.initialValue self.cbMutableChracteristic = cbMutableCharacteristic uuid = CBUUID(data: cbMutableCharacteristic.uuid.data) } public init(UUID: String, properties: CBCharacteristicProperties, permissions: CBAttributePermissions, value: Data?) { self.profile = CharacteristicProfile(uuid: UUID) self._value = value self.cbMutableChracteristic = CBMutableCharacteristic(type: self.profile.uuid, properties: properties, value: nil, permissions: permissions) uuid = CBUUID(data: self.profile.uuid.data) } public convenience init(UUID: String) { self.init(profile: CharacteristicProfile(uuid: UUID)) } public class func withProfiles(_ profiles: [CharacteristicProfile]) -> [MutableCharacteristic] { return profiles.map{ MutableCharacteristic(profile: $0) } } public class func withProfiles(_ profiles: [CharacteristicProfile], cbCharacteristics: [CBMutableCharacteristic]) -> [MutableCharacteristic] { return profiles.map{ MutableCharacteristic(profile: $0) } } // MARK: Properties & Permissions public func propertyEnabled(_ property:CBCharacteristicProperties) -> Bool { return (self.properties.rawValue & property.rawValue) > 0 } public func permissionEnabled(_ permission:CBAttributePermissions) -> Bool { return (self.permissions.rawValue & permission.rawValue) > 0 } // MARK: Data public func data(fromString data: [String:String]) -> Data? { return self.profile.data(fromString: data) } // MARK: Manage Writes public func startRespondingToWriteRequests(capacity: Int = Int.max) -> FutureStream<(request: CBATTRequestInjectable, central: CBCentralInjectable)> { return peripheralQueue?.sync { if let processWriteRequestPromise = self.processWriteRequestPromise { return processWriteRequestPromise.stream } self.processWriteRequestPromise = StreamPromise<(request: CBATTRequestInjectable, central: CBCentralInjectable)>(capacity: capacity) return self.processWriteRequestPromise!.stream } ?? FutureStream(error: MutableCharacteristicError.unconfigured) } public func stopRespondingToWriteRequests() { peripheralQueue?.sync { self.processWriteRequestPromise = nil } } public func respondToRequest(_ request: CBATTRequestInjectable, withResult result: CBATTError.Code) { self.service?.peripheralManager?.respondToRequest(request, withResult: result) } internal func didRespondToWriteRequest(_ request: CBATTRequestInjectable, central: CBCentralInjectable) -> Bool { guard let processWriteRequestPromise = self.processWriteRequestPromise else { return false } processWriteRequestPromise.success((request, central)) return true } // MARK: Manage Notification Updates public func update(withString value: [String:String]) throws { guard let data = self.profile.data(fromString: value) else { throw MutableCharacteristicError.notSerializable } return try update(withData: data) } public func update(withData value: Data) throws { guard let peripheralQueue = peripheralQueue else { throw MutableCharacteristicError.unconfigured } guard canNotify else { throw MutableCharacteristicError.notifyNotSupported } peripheralQueue.sync { self.updateValues([value]) } } public func update<T: Deserializable>(_ value: T) throws { try update(withData: SerDe.serialize(value)) } public func update<T: RawDeserializable>(_ value: T) throws { try update(withData: SerDe.serialize(value)) } public func update<T: RawArrayDeserializable>(_ value: T) throws { try update(withData: SerDe.serialize(value)) } public func update<T: RawPairDeserializable>(_ value: T) throws { try update(withData: SerDe.serialize(value)) } public func update<T: RawArrayPairDeserializable>(_ value: T) throws { try update(withData: SerDe.serialize(value)) } // MARK: CBPeripheralManagerDelegate Shims internal func peripheralManagerIsReadyToUpdateSubscribers() { self._isUpdating = true _ = self.updateValues(self.queuedUpdates) self.queuedUpdates.removeAll() } internal func didSubscribeToCharacteristic(_ central: CBCentralInjectable) { self._isUpdating = true self.centrals[central.identifier] = central _ = self.updateValues(self.queuedUpdates) self.queuedUpdates.removeAll() } internal func didUnsubscribeFromCharacteristic(_ central: CBCentralInjectable) { self.centrals.removeValue(forKey: central.identifier) if self.centrals.keys.count == 0 { self._isUpdating = false } } // MARK: Utils fileprivate func updateValues(_ values: [Data]) { guard let value = values.last else { return } _value = value if let peripheralManager = service?.peripheralManager, _isUpdating { for value in values { _isUpdating = peripheralManager.updateValue(value, forCharacteristic: self) if !_isUpdating { queuedUpdates.append(value) } } } else { _isUpdating = false queuedUpdates.append(value) } } }
34.046332
183
0.672828
39785bda3d9c58357dcd455a3f69e42d3d148ebc
1,252
// // FirstDemoUITests.swift // FirstDemoUITests // // Created by Edward Chiang on 10/26/15. // Copyright © 2015 Soleil Studio. All rights reserved. // import XCTest class FirstDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.837838
182
0.664537
ded5efa7cfd4609c0da26826b5feb96eba3a2429
1,325
#if os(iOS) || os(tvOS) import UIKit import RxSwift import AlertReactor enum MyAlertAction: AlertActionType { case edit case share case delete case cancel var title: String { switch self { case .edit: return "Edit" case .share: return "Share" case .delete: return "Delete" case .cancel: return "Cancel" } } var style: UIAlertAction.Style { switch self { case .edit: return .default case .share: return .default case .delete: return .destructive case .cancel: return .cancel } } } final class MyAlertReactor: AlertReactor<MyAlertAction> { let scheduler: SchedulerType init(scheduler: SchedulerType) { self.scheduler = scheduler super.init() } override func mutate(action: Action) -> Observable<Mutation> { switch action { case .prepare: return Observable.concat([ Observable.just(.setActions([.cancel])), Observable.just(.setActions([.edit, .cancel])).delay(.seconds(100), scheduler: self.scheduler), Observable.just(.setActions([.edit, .delete, .cancel])).delay(.seconds(100), scheduler: self.scheduler), Observable.just(.setActions([.edit, .share, .delete, .cancel])).delay(.seconds(100), scheduler: self.scheduler), ]) case .selectAction: return .empty() } } } #endif
24.090909
120
0.659623
080d4e0316256cf8386c84e3d87f91858964efbe
1,562
import Foundation func describe<T>(value: T) -> String { if let stringArray = value as? [String] { return joinDescriptions(stringArray.map {describe($0)}) } if let string = value as? String { return "\"\(string)\"" } return String(value) } func describeAddress<T: AnyObject>(object: T) -> String { return String(format: "%p", unsafeBitCast(object, Int.self)) } func describeMismatch<T>(value: T, description: String, mismatchDescription: String?) -> String { return "GOT: " + describeActualValue(value, mismatchDescription: mismatchDescription) + ", EXPECTED: \(description)" } func describeActualValue<T>(value: T, mismatchDescription: String?) -> String { return describe(value) + (mismatchDescription != nil ? " (\(mismatchDescription!))" : "") } func joinDescriptions(descriptions: [String]) -> String { return joinStrings(descriptions) } func joinDescriptions(descriptions: [String?]) -> String? { let notNil = filterNotNil(descriptions) return notNil.isEmpty ? nil : joinStrings(notNil) } func joinMatcherDescriptions<T>(matchers: [Matcher<T>], prefix: String = "all of") -> String { if matchers.count == 1 { return matchers[0].description } else { return prefix + " " + joinDescriptions(matchers.map({$0.description})) } } private func joinStrings(strings: [String]) -> String { switch (strings.count) { case 0: return "none" case 1: return strings[0] default: return "[" + strings.joinWithSeparator(", ") + "]" } }
30.627451
120
0.65557
69bc08ac3c8f37a20a0d5ba4d1ebb52092333877
2,361
// // AppDelegate.swift // YXSwiftKitUtil // // Created by Mr-Jesson on 02/23/2022. // Copyright (c) 2022 Mr-Jesson. All rights reserved. // import UIKit import YXSwiftKitUtil @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { YXNetRequestManager.manager.configNetRequst(); // YXNetworkManager // YXNetworkManager // YXNetworkManager.share.requestlist // 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:. } }
44.54717
285
0.747988
ff009cd9513c52e8c328b3aeaaa5f6ecdbc67202
172
// // CompletitionDelegate.swift // Posts // // Created by yespinoza on 7/25/20. // import Foundation protocol CompletitionDelegate { func didFinish(data:Data?) }
13.230769
36
0.697674
4b9f369534864ec1a8d3ee4a6f943c60ccf2e854
2,497
import CXShim import CXTestUtility import Nimble import Quick class RecordSpec: QuickSpec { override func spec() { // MARK: - Recording describe("Recording") { typealias Recording = Record<Int, TestError>.Recording // MARK: 1.1 should record events it("should record events") { var recording = Recording() recording.receive(1) recording.receive(2) recording.receive(completion: .failure(.e2)) expect(recording.output) == [1, 2] expect(recording.completion) == .failure(.e2) } // MARK: 1.2 should use finish temporarily it("should use finish temporarily") { let recording = Recording() expect(recording.completion) == .finished } #if arch(x86_64) && canImport(Darwin) // MARK: 1.3 should fatal if receiving value after receiving completion it("should fatal if receiving value after receiving completion") { expect { var recording = Recording() recording.receive(completion: .finished) recording.receive(1) }.to(throwAssertion()) } // MARK: 1.4 should fatal if receiving completion after receiving completion it("should fatal if receiving completion after receiving completion") { expect { var recording = Recording() recording.receive(completion: .finished) recording.receive(completion: .finished) }.to(throwAssertion()) } #endif } // MARK: - Replay describe("Replay") { // MARK: 2.1 should replay its events it("should replay its events") { let record = Record<Int, TestError> { $0.receive(1) $0.receive(2) $0.receive(completion: .failure(.e2)) } let sub = record.subscribeTracingSubscriber(initialDemand: .unlimited) expect(sub.eventsWithoutSubscription) == [.value(1), .value(2), .completion(.failure(.e2))] } } } }
34.680556
107
0.485382
14d102e150b860d1270fbb4bc0e84f3442594793
228
import Cocoa let applicationDelegate = AppDelegate() let application = NSApplication.shared application.setActivationPolicy(NSApplication.ActivationPolicy.accessory) application.delegate = applicationDelegate application.run()
28.5
73
0.864035
670a4ab23ef51b7712dbf751b3062b5e97424800
785
// // TYPEPersistenceStrategy.swift // import AmberBase import Foundation public class Dictionary_C_Data_String_D_PersistenceStrategy: PersistenceStrategy { public var types: Types { return Types.generic("Dictionary", [Types.type("Data"), Types.type("String")]) } public func save(_ object: Any) throws -> Data { guard let typedObject = object as? Dictionary<Data, String> else { throw AmberError.wrongTypes(self.types, AmberBase.types(of: object)) } let encoder = JSONEncoder() return try encoder.encode(typedObject) } public func load(_ data: Data) throws -> Any { let decoder = JSONDecoder() return try decoder.decode(Dictionary<Data, String>.self, from: data) } }
25.322581
86
0.652229
fb20c77eaad9f21b0db4f79e7e0c8194801092d8
1,765
// // SCSortType.swift // ElsevierKit // // Created by Yuto Mizutani on 2018/09/18. // import Foundation /** Represents the sort field name and order. A plus in front of the sort field name indicates ascending order, a minus indicates descending order. If sort order is not specified (i.e. no + or -) then the order defaults to ascending (ASC). Up to three fields can be specified, each delimited by a comma. The precedence is determined by their order (i.e. first is primary, second is secondary, and third is tertiary). +/-{field name}[,+/-{field name} ex. sort=coverDate,-title - SeeAlso: https://dev.elsevier.com/documentation/ScopusSearchAPI.wadl */ public enum SCSortType: String { case artnumAscending = "+artnum" case artnumDescending = "-artnum" case citedByCountAscending = "+citedby-count" case citedByCountDescending = "-citedby-count" case coverDateAscending = "+coverDate" case coverDateDescending = "-coverDate" case creatorAscending = "+creator" case creatorDescending = "-creator" case origLoadDateAscending = "+orig-load-date" case origLoadDateDescending = "-orig-load-date" case pageCountAscending = "+pagecount" case pageCountDescending = "-pagecount" case pageFirstAscending = "+pagefirst" case pageFirstDescending = "-pagefirst" case pageRangeAscending = "+pageRange" case pageRangeDescending = "-pageRange" case publicationNameAscending = "+publicationName" case publicationNameDescending = "-publicationName" case pubYearAscending = "+pubyear" case pubYearDescending = "-pubyear" case relevancyAscending = "+relevancy" case relevancyDescending = "-relevancy" case volumeAscending = "+volume" case volumeDescending = "-volume" }
36.020408
236
0.724646
ab1e630111bfecae71209c4b44eb160fab287525
61,424
// // ZLEditImageViewController.swift // ZLPhotoBrowser // // Created by long on 2020/8/26. // // Copyright (c) 2020 Long Zhang <[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 public class ZLEditImageModel: NSObject { public let drawPaths: [ZLDrawPath] public let mosaicPaths: [ZLMosaicPath] public let editRect: CGRect? public let angle: CGFloat public let selectRatio: ZLImageClipRatio? public let selectFilter: ZLFilter? public let textStickers: [(state: ZLTextStickerState, index: Int)]? public let imageStickers: [(state: ZLImageStickerState, index: Int)]? init(drawPaths: [ZLDrawPath], mosaicPaths: [ZLMosaicPath], editRect: CGRect?, angle: CGFloat, selectRatio: ZLImageClipRatio?, selectFilter: ZLFilter, textStickers: [(state: ZLTextStickerState, index: Int)]?, imageStickers: [(state: ZLImageStickerState, index: Int)]?) { self.drawPaths = drawPaths self.mosaicPaths = mosaicPaths self.editRect = editRect self.angle = angle self.selectRatio = selectRatio self.selectFilter = selectFilter self.textStickers = textStickers self.imageStickers = imageStickers super.init() } } public class ZLEditImageViewController: UIViewController { static let filterColViewH: CGFloat = 80 static let maxDrawLineImageWidth: CGFloat = 600 static let ashbinNormalBgColor = zlRGB(40, 40, 40).withAlphaComponent(0.8) var animate = false var originalImage: UIImage // 第一次进入界面时,布局后frame,裁剪dimiss动画使用 var originalFrame: CGRect = .zero // 图片可编辑rect var editRect: CGRect let tools: [ZLEditImageViewController.EditImageTool] var selectRatio: ZLImageClipRatio? var editImage: UIImage var cancelBtn: UIButton! var scrollView: UIScrollView! var containerView: UIView! // Show image. var imageView: UIImageView! // Show draw lines. var drawingImageView: UIImageView! // Show text and image stickers. var stickersContainer: UIView! // 处理好的马赛克图片 var mosaicImage: UIImage? // 显示马赛克图片的layer var mosaicImageLayer: CALayer? // 显示马赛克图片的layer的mask var mosaicImageLayerMaskLayer: CAShapeLayer? // 上方渐变阴影层 var topShadowView: UIView! var topShadowLayer: CAGradientLayer! // 下方渐变阴影层 var bottomShadowView: UIView! var bottomShadowLayer: CAGradientLayer! var doneBtn: UIButton! var revokeBtn: UIButton! var selectedTool: ZLEditImageViewController.EditImageTool? var editToolCollectionView: UICollectionView! var drawColorCollectionView: UICollectionView! var filterCollectionView: UICollectionView! var ashbinView: UIView! var ashbinImgView: UIImageView! let drawColors: [UIColor] var currentDrawColor = ZLPhotoConfiguration.default().editImageDefaultDrawColor var drawPaths: [ZLDrawPath] var drawLineWidth: CGFloat = 5 var mosaicPaths: [ZLMosaicPath] var mosaicLineWidth: CGFloat = 25 // collectionview 中的添加滤镜的小图 var thumbnailFilterImages: [UIImage] = [] // 选择滤镜后对原图添加滤镜后的图片 var filterImages: [String: UIImage] = [:] var currentFilter: ZLFilter var stickers: [UIView] = [] var isScrolling = false var shouldLayout = true var imageStickerContainerIsHidden = true var angle: CGFloat var panGes: UIPanGestureRecognizer! var imageSize: CGSize { if self.angle == -90 || self.angle == -270 { return CGSize(width: self.originalImage.size.height, height: self.originalImage.size.width) } return self.originalImage.size } @objc public var editFinishBlock: ( (UIImage, ZLEditImageModel?) -> Void )? public override var prefersStatusBarHidden: Bool { return true } public override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } deinit { zl_debugPrint("ZLEditImageViewController deinit") } @objc public class func showEditImageVC(parentVC: UIViewController?, animate: Bool = false, image: UIImage, editModel: ZLEditImageModel? = nil, completion: ( (UIImage, ZLEditImageModel?) -> Void )? ) { let tools = ZLPhotoConfiguration.default().editImageTools if ZLPhotoConfiguration.default().showClipDirectlyIfOnlyHasClipTool, tools.count == 1, tools.contains(.clip) { let vc = ZLClipImageViewController(image: image, editRect: editModel?.editRect, angle: editModel?.angle ?? 0, selectRatio: editModel?.selectRatio) vc.clipDoneBlock = { (angle, editRect, ratio) in let m = ZLEditImageModel(drawPaths: [], mosaicPaths: [], editRect: editRect, angle: angle, selectRatio: ratio, selectFilter: .normal, textStickers: nil, imageStickers: nil) completion?(image.clipImage(angle: angle, editRect: editRect, isCircle: ratio.isCircle) ?? image, m) } vc.animate = animate vc.modalPresentationStyle = .fullScreen parentVC?.present(vc, animated: animate, completion: nil) } else { let vc = ZLEditImageViewController(image: image, editModel: editModel) vc.editFinishBlock = { (ei, editImageModel) in completion?(ei, editImageModel) } vc.animate = animate vc.modalPresentationStyle = .fullScreen parentVC?.present(vc, animated: animate, completion: nil) } } @objc public init(image: UIImage, editModel: ZLEditImageModel? = nil) { self.originalImage = image.fixOrientation() self.editImage = self.originalImage self.editRect = editModel?.editRect ?? CGRect(origin: .zero, size: image.size) self.drawColors = ZLPhotoConfiguration.default().editImageDrawColors self.currentFilter = editModel?.selectFilter ?? .normal self.drawPaths = editModel?.drawPaths ?? [] self.mosaicPaths = editModel?.mosaicPaths ?? [] self.angle = editModel?.angle ?? 0 self.selectRatio = editModel?.selectRatio var ts = ZLPhotoConfiguration.default().editImageTools if ts.contains(.imageSticker), ZLPhotoConfiguration.default().imageStickerContainerView == nil { ts.removeAll { $0 == .imageSticker } } self.tools = ts super.init(nibName: nil, bundle: nil) if !self.drawColors.contains(self.currentDrawColor) { self.currentDrawColor = self.drawColors.first! } let teStic = editModel?.textStickers ?? [] let imStic = editModel?.imageStickers ?? [] var stickers: [UIView?] = Array(repeating: nil, count: teStic.count + imStic.count) teStic.forEach { (cache) in let v = ZLTextStickerView(from: cache.state) stickers[cache.index] = v } imStic.forEach { (cache) in let v = ZLImageStickerView(from: cache.state) stickers[cache.index] = v } self.stickers = stickers.compactMap { $0 } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.setupUI() self.rotationImageView() if self.tools.contains(.filter) { self.generateFilterImages() } } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard self.shouldLayout else { return } self.shouldLayout = false zl_debugPrint("edit image layout subviews") var insets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) if #available(iOS 11.0, *) { insets = self.view.safeAreaInsets } insets.top = max(20, insets.top) self.scrollView.frame = self.view.bounds self.resetContainerViewFrame() self.topShadowView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 150) self.topShadowLayer.frame = self.topShadowView.bounds self.cancelBtn.frame = CGRect(x: 30, y: insets.top+10, width: 28, height: 28) self.bottomShadowView.frame = CGRect(x: 0, y: self.view.frame.height-140-insets.bottom, width: self.view.frame.width, height: 140+insets.bottom) self.bottomShadowLayer.frame = self.bottomShadowView.bounds self.drawColorCollectionView.frame = CGRect(x: 20, y: 20, width: self.view.frame.width - 80, height: 50) self.revokeBtn.frame = CGRect(x: self.view.frame.width - 15 - 35, y: 30, width: 35, height: 30) self.filterCollectionView.frame = CGRect(x: 20, y: 0, width: self.view.frame.width-40, height: ZLEditImageViewController.filterColViewH) let toolY: CGFloat = 85 let doneBtnH = ZLLayout.bottomToolBtnH let doneBtnW = localLanguageTextValue(.editFinish).boundingRect(font: ZLLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: doneBtnH)).width + 20 self.doneBtn.frame = CGRect(x: self.view.frame.width-20-doneBtnW, y: toolY-2, width: doneBtnW, height: doneBtnH) self.editToolCollectionView.frame = CGRect(x: 20, y: toolY, width: self.view.bounds.width - 20 - 20 - doneBtnW - 20, height: 30) if !self.drawPaths.isEmpty { self.drawLine() } if !self.mosaicPaths.isEmpty { self.generateNewMosaicImage() } if let index = self.drawColors.firstIndex(where: { $0 == self.currentDrawColor}) { self.drawColorCollectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false) } } func generateFilterImages() { let size: CGSize let ratio = (self.originalImage.size.width / self.originalImage.size.height) let fixLength: CGFloat = 200 if ratio >= 1 { size = CGSize(width: fixLength * ratio, height: fixLength) } else { size = CGSize(width: fixLength, height: fixLength / ratio) } let thumbnailImage = self.originalImage.resize_vI(size) ?? self.originalImage DispatchQueue.global().async { self.thumbnailFilterImages = ZLPhotoConfiguration.default().filters.map { $0.applier?(thumbnailImage) ?? thumbnailImage } DispatchQueue.main.async { self.filterCollectionView.reloadData() self.filterCollectionView.performBatchUpdates { } completion: { (_) in if let index = ZLPhotoConfiguration.default().filters.firstIndex(where: { $0 == self.currentFilter }) { self.filterCollectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false) } } } } } func resetContainerViewFrame() { self.scrollView.setZoomScale(1, animated: true) self.imageView.image = self.editImage let editSize = self.editRect.size let scrollViewSize = self.scrollView.frame.size let ratio = min(scrollViewSize.width / editSize.width, scrollViewSize.height / editSize.height) let w = ratio * editSize.width * self.scrollView.zoomScale let h = ratio * editSize.height * self.scrollView.zoomScale self.containerView.frame = CGRect(x: max(0, (scrollViewSize.width-w)/2), y: max(0, (scrollViewSize.height-h)/2), width: w, height: h) if self.selectRatio?.isCircle == true { let mask = CAShapeLayer() let path = UIBezierPath(arcCenter: CGPoint(x: w / 2, y: h / 2), radius: w / 2, startAngle: 0, endAngle: .pi * 2, clockwise: true) mask.path = path.cgPath self.containerView.layer.mask = mask } else { self.containerView.layer.mask = nil } let scaleImageOrigin = CGPoint(x: -self.editRect.origin.x*ratio, y: -self.editRect.origin.y*ratio) let scaleImageSize = CGSize(width: self.imageSize.width * ratio, height: self.imageSize.height * ratio) self.imageView.frame = CGRect(origin: scaleImageOrigin, size: scaleImageSize) self.mosaicImageLayer?.frame = self.imageView.bounds self.mosaicImageLayerMaskLayer?.frame = self.imageView.bounds self.drawingImageView.frame = self.imageView.frame self.stickersContainer.frame = self.imageView.frame // 针对于长图的优化 if (self.editRect.height / self.editRect.width) > (self.view.frame.height / self.view.frame.width * 1.1) { let widthScale = self.view.frame.width / w self.scrollView.maximumZoomScale = widthScale self.scrollView.zoomScale = widthScale self.scrollView.contentOffset = .zero } else if self.editRect.width / self.editRect.height > 1 { self.scrollView.maximumZoomScale = max(3, self.view.frame.height / h) } self.originalFrame = self.view.convert(self.containerView.frame, from: self.scrollView) self.isScrolling = false } func setupUI() { self.view.backgroundColor = .black self.scrollView = UIScrollView() self.scrollView.backgroundColor = .black self.scrollView.minimumZoomScale = 1 self.scrollView.maximumZoomScale = 3 self.scrollView.delegate = self self.view.addSubview(self.scrollView) self.containerView = UIView() self.containerView.clipsToBounds = true self.scrollView.addSubview(self.containerView) self.imageView = UIImageView(image: self.originalImage) self.imageView.contentMode = .scaleAspectFit self.imageView.clipsToBounds = true self.imageView.backgroundColor = .black self.containerView.addSubview(self.imageView) self.drawingImageView = UIImageView() self.drawingImageView.contentMode = .scaleAspectFit self.drawingImageView.isUserInteractionEnabled = true self.containerView.addSubview(self.drawingImageView) self.stickersContainer = UIView() self.containerView.addSubview(self.stickersContainer) let color1 = UIColor.black.withAlphaComponent(0.35).cgColor let color2 = UIColor.black.withAlphaComponent(0).cgColor self.topShadowView = UIView() self.view.addSubview(self.topShadowView) self.topShadowLayer = CAGradientLayer() self.topShadowLayer.colors = [color1, color2] self.topShadowLayer.locations = [0, 1] self.topShadowView.layer.addSublayer(self.topShadowLayer) self.cancelBtn = UIButton(type: .custom) self.cancelBtn.setImage(getImage("zl_retake"), for: .normal) self.cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside) self.cancelBtn.adjustsImageWhenHighlighted = false self.cancelBtn.zl_enlargeValidTouchArea(inset: 30) self.topShadowView.addSubview(self.cancelBtn) self.bottomShadowView = UIView() self.view.addSubview(self.bottomShadowView) self.bottomShadowLayer = CAGradientLayer() self.bottomShadowLayer.colors = [color2, color1] self.bottomShadowLayer.locations = [0, 1] self.bottomShadowView.layer.addSublayer(self.bottomShadowLayer) let editToolLayout = UICollectionViewFlowLayout() editToolLayout.itemSize = CGSize(width: 30, height: 30) editToolLayout.minimumLineSpacing = 20 editToolLayout.minimumInteritemSpacing = 20 editToolLayout.scrollDirection = .horizontal self.editToolCollectionView = UICollectionView(frame: .zero, collectionViewLayout: editToolLayout) self.editToolCollectionView.backgroundColor = .clear self.editToolCollectionView.delegate = self self.editToolCollectionView.dataSource = self self.editToolCollectionView.showsHorizontalScrollIndicator = false self.bottomShadowView.addSubview(self.editToolCollectionView) ZLEditToolCell.zl_register(self.editToolCollectionView) self.doneBtn = UIButton(type: .custom) self.doneBtn.titleLabel?.font = ZLLayout.bottomToolTitleFont self.doneBtn.backgroundColor = .bottomToolViewBtnNormalBgColor self.doneBtn.setTitle(localLanguageTextValue(.editFinish), for: .normal) self.doneBtn.addTarget(self, action: #selector(doneBtnClick), for: .touchUpInside) self.doneBtn.layer.masksToBounds = true self.doneBtn.layer.cornerRadius = ZLLayout.bottomToolBtnCornerRadius self.bottomShadowView.addSubview(self.doneBtn) let drawColorLayout = UICollectionViewFlowLayout() drawColorLayout.itemSize = CGSize(width: 30, height: 30) drawColorLayout.minimumLineSpacing = 15 drawColorLayout.minimumInteritemSpacing = 15 drawColorLayout.scrollDirection = .horizontal drawColorLayout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) self.drawColorCollectionView = UICollectionView(frame: .zero, collectionViewLayout: drawColorLayout) self.drawColorCollectionView.backgroundColor = .clear self.drawColorCollectionView.delegate = self self.drawColorCollectionView.dataSource = self self.drawColorCollectionView.isHidden = true self.drawColorCollectionView.showsHorizontalScrollIndicator = false self.bottomShadowView.addSubview(self.drawColorCollectionView) ZLDrawColorCell.zl_register(self.drawColorCollectionView) let filterLayout = UICollectionViewFlowLayout() filterLayout.itemSize = CGSize(width: ZLEditImageViewController.filterColViewH-20, height: ZLEditImageViewController.filterColViewH) filterLayout.minimumLineSpacing = 15 filterLayout.minimumInteritemSpacing = 15 filterLayout.scrollDirection = .horizontal self.filterCollectionView = UICollectionView(frame: .zero, collectionViewLayout: filterLayout) self.filterCollectionView.backgroundColor = .clear self.filterCollectionView.delegate = self self.filterCollectionView.dataSource = self self.filterCollectionView.isHidden = true self.filterCollectionView.showsHorizontalScrollIndicator = false self.bottomShadowView.addSubview(self.filterCollectionView) ZLFilterImageCell.zl_register(self.filterCollectionView) self.revokeBtn = UIButton(type: .custom) self.revokeBtn.setImage(getImage("zl_revoke_disable"), for: .disabled) self.revokeBtn.setImage(getImage("zl_revoke"), for: .normal) self.revokeBtn.adjustsImageWhenHighlighted = false self.revokeBtn.isEnabled = false self.revokeBtn.isHidden = true self.revokeBtn.addTarget(self, action: #selector(revokeBtnClick), for: .touchUpInside) self.bottomShadowView.addSubview(self.revokeBtn) let ashbinSize = CGSize(width: 160, height: 80) self.ashbinView = UIView(frame: CGRect(x: (self.view.frame.width-ashbinSize.width)/2, y: self.view.frame.height-ashbinSize.height-40, width: ashbinSize.width, height: ashbinSize.height)) self.ashbinView.backgroundColor = ZLEditImageViewController.ashbinNormalBgColor self.ashbinView.layer.cornerRadius = 15 self.ashbinView.layer.masksToBounds = true self.ashbinView.isHidden = true self.view.addSubview(self.ashbinView) self.ashbinImgView = UIImageView(image: getImage("zl_ashbin"), highlightedImage: getImage("zl_ashbin_open")) self.ashbinImgView.frame = CGRect(x: (ashbinSize.width-25)/2, y: 15, width: 25, height: 25) self.ashbinView.addSubview(self.ashbinImgView) let asbinTipLabel = UILabel(frame: CGRect(x: 0, y: ashbinSize.height-34, width: ashbinSize.width, height: 34)) asbinTipLabel.font = getFont(12) asbinTipLabel.textAlignment = .center asbinTipLabel.textColor = .white asbinTipLabel.text = localLanguageTextValue(.textStickerRemoveTips) asbinTipLabel.numberOfLines = 2 asbinTipLabel.lineBreakMode = .byCharWrapping self.ashbinView.addSubview(asbinTipLabel) if self.tools.contains(.mosaic) { // 之前选择过滤镜 if let applier = self.currentFilter.applier { let image = applier(self.originalImage) self.editImage = image self.filterImages[self.currentFilter.name] = image self.mosaicImage = self.editImage.mosaicImage() } else { self.mosaicImage = self.originalImage.mosaicImage() } self.mosaicImageLayer = CALayer() self.mosaicImageLayer?.contents = self.mosaicImage?.cgImage self.imageView.layer.addSublayer(self.mosaicImageLayer!) self.mosaicImageLayerMaskLayer = CAShapeLayer() self.mosaicImageLayerMaskLayer?.strokeColor = UIColor.blue.cgColor self.mosaicImageLayerMaskLayer?.fillColor = nil self.mosaicImageLayerMaskLayer?.lineCap = .round self.mosaicImageLayerMaskLayer?.lineJoin = .round self.imageView.layer.addSublayer(self.mosaicImageLayerMaskLayer!) self.mosaicImageLayer?.mask = self.mosaicImageLayerMaskLayer } if self.tools.contains(.imageSticker) { ZLPhotoConfiguration.default().imageStickerContainerView?.hideBlock = { [weak self] in self?.setToolView(show: true) self?.imageStickerContainerIsHidden = true } ZLPhotoConfiguration.default().imageStickerContainerView?.selectImageBlock = { [weak self] (image) in self?.addImageStickerView(image) } } let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:))) tapGes.delegate = self self.view.addGestureRecognizer(tapGes) self.panGes = UIPanGestureRecognizer(target: self, action: #selector(drawAction(_:))) self.panGes.maximumNumberOfTouches = 1 self.panGes.delegate = self self.view.addGestureRecognizer(self.panGes) self.scrollView.panGestureRecognizer.require(toFail: self.panGes) self.stickers.forEach { (view) in self.stickersContainer.addSubview(view) if let tv = view as? ZLTextStickerView { tv.frame = tv.originFrame self.configTextSticker(tv) } else if let iv = view as? ZLImageStickerView { iv.frame = iv.originFrame self.configImageSticker(iv) } } } func rotationImageView() { let transform = CGAffineTransform(rotationAngle: self.angle.toPi) self.imageView.transform = transform self.drawingImageView.transform = transform self.stickersContainer.transform = transform } @objc func cancelBtnClick() { self.dismiss(animated: self.animate, completion: nil) } func drawBtnClick() { let isSelected = self.selectedTool != .draw if isSelected { self.selectedTool = .draw } else { self.selectedTool = nil } self.drawColorCollectionView.isHidden = !isSelected self.revokeBtn.isHidden = !isSelected self.revokeBtn.isEnabled = self.drawPaths.count > 0 self.filterCollectionView.isHidden = true } func clipBtnClick() { let currentEditImage = self.buildImage() let vc = ZLClipImageViewController(image: currentEditImage, editRect: self.editRect, angle: self.angle, selectRatio: self.selectRatio) let rect = self.scrollView.convert(self.containerView.frame, to: self.view) vc.presentAnimateFrame = rect vc.presentAnimateImage = currentEditImage.clipImage(angle: self.angle, editRect: self.editRect, isCircle: self.selectRatio?.isCircle ?? false) vc.modalPresentationStyle = .fullScreen vc.clipDoneBlock = { [weak self] (angle, editFrame, selectRatio) in guard let `self` = self else { return } let oldAngle = self.angle let oldContainerSize = self.stickersContainer.frame.size if self.angle != angle { self.angle = angle self.rotationImageView() } self.editRect = editFrame self.selectRatio = selectRatio self.resetContainerViewFrame() self.reCalculateStickersFrame(oldContainerSize, oldAngle, angle) } vc.cancelClipBlock = { [weak self] () in self?.resetContainerViewFrame() } self.present(vc, animated: false) { self.scrollView.alpha = 0 self.topShadowView.alpha = 0 self.bottomShadowView.alpha = 0 } } func imageStickerBtnClick() { ZLPhotoConfiguration.default().imageStickerContainerView?.show(in: self.view) self.setToolView(show: false) self.imageStickerContainerIsHidden = false } func textStickerBtnClick() { self.showInputTextVC { [weak self] (text, textColor, bgColor) in self?.addTextStickersView(text, textColor: textColor, bgColor: bgColor) } } func mosaicBtnClick() { let isSelected = self.selectedTool != .mosaic if isSelected { self.selectedTool = .mosaic } else { self.selectedTool = nil } self.drawColorCollectionView.isHidden = true self.filterCollectionView.isHidden = true self.revokeBtn.isHidden = !isSelected self.revokeBtn.isEnabled = self.mosaicPaths.count > 0 } func filterBtnClick() { let isSelected = self.selectedTool != .filter if isSelected { self.selectedTool = .filter } else { self.selectedTool = nil } self.drawColorCollectionView.isHidden = true self.revokeBtn.isHidden = true self.filterCollectionView.isHidden = !isSelected } @objc func doneBtnClick() { var textStickers: [(ZLTextStickerState, Int)] = [] var imageStickers: [(ZLImageStickerState, Int)] = [] for (index, view) in self.stickersContainer.subviews.enumerated() { if let ts = view as? ZLTextStickerView, let _ = ts.label.text { textStickers.append((ts.state, index)) } else if let ts = view as? ZLImageStickerView { imageStickers.append((ts.state, index)) } } var hasEdit = true if self.drawPaths.isEmpty, self.editRect.size == self.imageSize, self.angle == 0, self.mosaicPaths.isEmpty, imageStickers.isEmpty, textStickers.isEmpty, self.currentFilter.applier == nil { hasEdit = false } var resImage = self.originalImage var editModel: ZLEditImageModel? = nil if hasEdit { resImage = self.buildImage() resImage = resImage.clipImage(angle: self.angle, editRect: self.editRect, isCircle: self.selectRatio?.isCircle ?? false) ?? resImage editModel = ZLEditImageModel(drawPaths: self.drawPaths, mosaicPaths: self.mosaicPaths, editRect: self.editRect, angle: self.angle, selectRatio: self.selectRatio, selectFilter: self.currentFilter, textStickers: textStickers, imageStickers: imageStickers) } self.editFinishBlock?(resImage, editModel) self.dismiss(animated: self.animate, completion: nil) } @objc func revokeBtnClick() { if self.selectedTool == .draw { guard !self.drawPaths.isEmpty else { return } self.drawPaths.removeLast() self.revokeBtn.isEnabled = self.drawPaths.count > 0 self.drawLine() } else if self.selectedTool == .mosaic { guard !self.mosaicPaths.isEmpty else { return } self.mosaicPaths.removeLast() self.revokeBtn.isEnabled = self.mosaicPaths.count > 0 self.generateNewMosaicImage() } } @objc func tapAction(_ tap: UITapGestureRecognizer) { if self.bottomShadowView.alpha == 1 { self.setToolView(show: false) } else { self.setToolView(show: true) } } @objc func drawAction(_ pan: UIPanGestureRecognizer) { if self.selectedTool == .draw { let point = pan.location(in: self.drawingImageView) if pan.state == .began { self.setToolView(show: false) let originalRatio = min(self.scrollView.frame.width / self.originalImage.size.width, self.scrollView.frame.height / self.originalImage.size.height) let ratio = min(self.scrollView.frame.width / self.editRect.width, self.scrollView.frame.height / self.editRect.height) let scale = ratio / originalRatio // 缩放到最初的size var size = self.drawingImageView.frame.size size.width /= scale size.height /= scale if self.angle == -90 || self.angle == -270 { swap(&size.width, &size.height) } var toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.width if self.editImage.size.width / self.editImage.size.height > 1 { toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.height } let path = ZLDrawPath(pathColor: self.currentDrawColor, pathWidth: self.drawLineWidth / self.scrollView.zoomScale, ratio: ratio / originalRatio / toImageScale, startPoint: point) self.drawPaths.append(path) } else if pan.state == .changed { let path = self.drawPaths.last path?.addLine(to: point) self.drawLine() } else if pan.state == .cancelled || pan.state == .ended { self.setToolView(show: true) self.revokeBtn.isEnabled = self.drawPaths.count > 0 } } else if self.selectedTool == .mosaic { let point = pan.location(in: self.imageView) if pan.state == .began { self.setToolView(show: false) var actualSize = self.editRect.size if self.angle == -90 || self.angle == -270 { swap(&actualSize.width, &actualSize.height) } let ratio = min(self.scrollView.frame.width / self.editRect.width, self.scrollView.frame.height / self.editRect.height) let pathW = self.mosaicLineWidth / self.scrollView.zoomScale let path = ZLMosaicPath(pathWidth: pathW, ratio: ratio, startPoint: point) self.mosaicImageLayerMaskLayer?.lineWidth = pathW self.mosaicImageLayerMaskLayer?.path = path.path.cgPath self.mosaicPaths.append(path) } else if pan.state == .changed { let path = self.mosaicPaths.last path?.addLine(to: point) self.mosaicImageLayerMaskLayer?.path = path?.path.cgPath } else if pan.state == .cancelled || pan.state == .ended { self.setToolView(show: true) self.revokeBtn.isEnabled = self.mosaicPaths.count > 0 self.generateNewMosaicImage() } } } func setToolView(show: Bool) { self.topShadowView.layer.removeAllAnimations() self.bottomShadowView.layer.removeAllAnimations() if show { UIView.animate(withDuration: 0.25) { self.topShadowView.alpha = 1 self.bottomShadowView.alpha = 1 } } else { UIView.animate(withDuration: 0.25) { self.topShadowView.alpha = 0 self.bottomShadowView.alpha = 0 } } } func showInputTextVC(_ text: String? = nil, textColor: UIColor? = nil, bgColor: UIColor? = nil, completion: @escaping ( (String, UIColor, UIColor) -> Void )) { // Calculate image displayed frame on the screen. var r = self.scrollView.convert(self.view.frame, to: self.containerView) r.origin.x += self.scrollView.contentOffset.x / self.scrollView.zoomScale r.origin.y += self.scrollView.contentOffset.y / self.scrollView.zoomScale let scale = self.imageSize.width / self.imageView.frame.width r.origin.x *= scale r.origin.y *= scale r.size.width *= scale r.size.height *= scale let isCircle = self.selectRatio?.isCircle ?? false let bgImage = self.buildImage().clipImage(angle: self.angle, editRect: self.editRect, isCircle: isCircle)?.clipImage(angle: 0, editRect: r, isCircle: isCircle) let vc = ZLInputTextViewController(image: bgImage, text: text, textColor: textColor, bgColor: bgColor) vc.endInput = { (text, textColor, bgColor) in completion(text, textColor, bgColor) } vc.modalPresentationStyle = .fullScreen self.showDetailViewController(vc, sender: nil) } func getStickerOriginFrame(_ size: CGSize) -> CGRect { let scale = self.scrollView.zoomScale // Calculate the display rect of container view. let x = (self.scrollView.contentOffset.x - self.containerView.frame.minX) / scale let y = (self.scrollView.contentOffset.y - self.containerView.frame.minY) / scale let w = view.frame.width / scale let h = view.frame.height / scale // Convert to text stickers container view. let r = self.containerView.convert(CGRect(x: x, y: y, width: w, height: h), to: self.stickersContainer) let originFrame = CGRect(x: r.minX + (r.width - size.width) / 2, y: r.minY + (r.height - size.height) / 2, width: size.width, height: size.height) return originFrame } /// Add image sticker func addImageStickerView(_ image: UIImage) { let scale = self.scrollView.zoomScale let size = ZLImageStickerView.calculateSize(image: image, width: self.view.frame.width) let originFrame = self.getStickerOriginFrame(size) let imageSticker = ZLImageStickerView(image: image, originScale: 1 / scale, originAngle: -self.angle, originFrame: originFrame) self.stickersContainer.addSubview(imageSticker) imageSticker.frame = originFrame self.view.layoutIfNeeded() self.configImageSticker(imageSticker) } /// Add text sticker func addTextStickersView(_ text: String, textColor: UIColor, bgColor: UIColor) { guard !text.isEmpty else { return } let scale = self.scrollView.zoomScale let size = ZLTextStickerView.calculateSize(text: text, width: self.view.frame.width) let originFrame = self.getStickerOriginFrame(size) let textSticker = ZLTextStickerView(text: text, textColor: textColor, bgColor: bgColor, originScale: 1 / scale, originAngle: -self.angle, originFrame: originFrame) self.stickersContainer.addSubview(textSticker) textSticker.frame = originFrame self.configTextSticker(textSticker) } func configTextSticker(_ textSticker: ZLTextStickerView) { textSticker.delegate = self self.scrollView.pinchGestureRecognizer?.require(toFail: textSticker.pinchGes) self.scrollView.panGestureRecognizer.require(toFail: textSticker.panGes) self.panGes.require(toFail: textSticker.panGes) } func configImageSticker(_ imageSticker: ZLImageStickerView) { imageSticker.delegate = self self.scrollView.pinchGestureRecognizer?.require(toFail: imageSticker.pinchGes) self.scrollView.panGestureRecognizer.require(toFail: imageSticker.panGes) self.panGes.require(toFail: imageSticker.panGes) } func reCalculateStickersFrame(_ oldSize: CGSize, _ oldAngle: CGFloat, _ newAngle: CGFloat) { let currSize = self.stickersContainer.frame.size let scale: CGFloat if Int(newAngle - oldAngle) % 180 == 0 { scale = currSize.width / oldSize.width } else { scale = currSize.height / oldSize.width } self.stickersContainer.subviews.forEach { (view) in (view as? ZLStickerViewAdditional)?.addScale(scale) } } func drawLine() { let originalRatio = min(self.scrollView.frame.width / self.originalImage.size.width, self.scrollView.frame.height / self.originalImage.size.height) let ratio = min(self.scrollView.frame.width / self.editRect.width, self.scrollView.frame.height / self.editRect.height) let scale = ratio / originalRatio // 缩放到最初的size var size = self.drawingImageView.frame.size size.width /= scale size.height /= scale if self.angle == -90 || self.angle == -270 { swap(&size.width, &size.height) } var toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.width if self.editImage.size.width / self.editImage.size.height > 1 { toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.height } size.width *= toImageScale size.height *= toImageScale UIGraphicsBeginImageContextWithOptions(size, false, self.editImage.scale) let context = UIGraphicsGetCurrentContext() // 去掉锯齿 context?.setAllowsAntialiasing(true) context?.setShouldAntialias(true) for path in self.drawPaths { path.drawPath() } self.drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } func generateNewMosaicImage() { UIGraphicsBeginImageContextWithOptions(self.originalImage.size, false, self.originalImage.scale) if self.tools.contains(.filter), let image = self.filterImages[self.currentFilter.name] { image.draw(at: .zero) } else { self.originalImage.draw(at: .zero) } let context = UIGraphicsGetCurrentContext() self.mosaicPaths.forEach { (path) in context?.move(to: path.startPoint) path.linePoints.forEach { (point) in context?.addLine(to: point) } context?.setLineWidth(path.path.lineWidth / path.ratio) context?.setLineCap(.round) context?.setLineJoin(.round) context?.setBlendMode(.clear) context?.strokePath() } var midImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let midCgImage = midImage?.cgImage else { return } midImage = UIImage(cgImage: midCgImage, scale: self.editImage.scale, orientation: .up) UIGraphicsBeginImageContextWithOptions(self.originalImage.size, false, self.originalImage.scale) self.mosaicImage?.draw(at: .zero) midImage?.draw(at: .zero) let temp = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgi = temp?.cgImage else { return } let image = UIImage(cgImage: cgi, scale: self.editImage.scale, orientation: .up) self.editImage = image self.imageView.image = self.editImage self.mosaicImageLayerMaskLayer?.path = nil } func buildImage() -> UIImage { let imageSize = self.originalImage.size UIGraphicsBeginImageContextWithOptions(self.editImage.size, false, self.editImage.scale) self.editImage.draw(at: .zero) self.drawingImageView.image?.draw(in: CGRect(origin: .zero, size: imageSize)) if !self.stickersContainer.subviews.isEmpty, let context = UIGraphicsGetCurrentContext() { let scale = self.imageSize.width / self.stickersContainer.frame.width self.stickersContainer.subviews.forEach { (view) in (view as? ZLStickerViewAdditional)?.resetState() } context.concatenate(CGAffineTransform(scaleX: scale, y: scale)) self.stickersContainer.layer.render(in: context) context.concatenate(CGAffineTransform(scaleX: 1/scale, y: 1/scale)) } let temp = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgi = temp?.cgImage else { return self.editImage } return UIImage(cgImage: cgi, scale: self.editImage.scale, orientation: .up) } func finishClipDismissAnimate() { self.scrollView.alpha = 1 UIView.animate(withDuration: 0.1) { self.topShadowView.alpha = 1 self.bottomShadowView.alpha = 1 } } } extension ZLEditImageViewController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard self.imageStickerContainerIsHidden else { return false } if gestureRecognizer is UITapGestureRecognizer { if self.bottomShadowView.alpha == 1 { let p = gestureRecognizer.location(in: self.view) return !self.bottomShadowView.frame.contains(p) } else { return true } } else if gestureRecognizer is UIPanGestureRecognizer { guard let st = self.selectedTool else { return false } return (st == .draw || st == .mosaic) && !self.isScrolling } return true } } // MARK: scroll view delegate extension ZLEditImageViewController: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.containerView } public func scrollViewDidZoom(_ scrollView: UIScrollView) { let offsetX = (scrollView.frame.width > scrollView.contentSize.width) ? (scrollView.frame.width - scrollView.contentSize.width) * 0.5 : 0 let offsetY = (scrollView.frame.height > scrollView.contentSize.height) ? (scrollView.frame.height - scrollView.contentSize.height) * 0.5 : 0 self.containerView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self.isScrolling = false } public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard scrollView == self.scrollView else { return } self.isScrolling = true } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard scrollView == self.scrollView else { return } self.isScrolling = decelerate } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard scrollView == self.scrollView else { return } self.isScrolling = false } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { guard scrollView == self.scrollView else { return } self.isScrolling = false } } extension ZLEditImageViewController: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == self.editToolCollectionView { return self.tools.count } else if collectionView == self.drawColorCollectionView { return self.drawColors.count } else { return self.thumbnailFilterImages.count } } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.editToolCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLEditToolCell.zl_identifier(), for: indexPath) as! ZLEditToolCell let toolType = self.tools[indexPath.row] cell.icon.isHighlighted = false cell.toolType = toolType cell.icon.isHighlighted = toolType == self.selectedTool return cell } else if collectionView == self.drawColorCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLDrawColorCell.zl_identifier(), for: indexPath) as! ZLDrawColorCell let c = self.drawColors[indexPath.row] cell.color = c if c == self.currentDrawColor { cell.bgWhiteView.layer.transform = CATransform3DMakeScale(1.2, 1.2, 1) } else { cell.bgWhiteView.layer.transform = CATransform3DIdentity } return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLFilterImageCell.zl_identifier(), for: indexPath) as! ZLFilterImageCell let image = self.thumbnailFilterImages[indexPath.row] let filter = ZLPhotoConfiguration.default().filters[indexPath.row] cell.nameLabel.text = filter.name cell.imageView.image = image if self.currentFilter === filter { cell.nameLabel.textColor = .white } else { cell.nameLabel.textColor = zlRGB(160, 160, 160) } return cell } } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView == self.editToolCollectionView { let toolType = self.tools[indexPath.row] switch toolType { case .draw: self.drawBtnClick() case .clip: self.clipBtnClick() case .imageSticker: self.imageStickerBtnClick() case .textSticker: self.textStickerBtnClick() case .mosaic: self.mosaicBtnClick() case .filter: self.filterBtnClick() } } else if collectionView == self.drawColorCollectionView { self.currentDrawColor = self.drawColors[indexPath.row] } else { self.currentFilter = ZLPhotoConfiguration.default().filters[indexPath.row] if let image = self.filterImages[self.currentFilter.name] { self.editImage = image } else { let image = self.currentFilter.applier?(self.originalImage) ?? self.originalImage self.editImage = image self.filterImages[self.currentFilter.name] = image } if self.tools.contains(.mosaic) { self.mosaicImage = self.editImage.mosaicImage() self.mosaicImageLayer?.removeFromSuperlayer() self.mosaicImageLayer = CALayer() self.mosaicImageLayer?.frame = self.imageView.bounds self.mosaicImageLayer?.contents = self.mosaicImage?.cgImage self.imageView.layer.insertSublayer(self.mosaicImageLayer!, below: self.mosaicImageLayerMaskLayer) self.mosaicImageLayer?.mask = self.mosaicImageLayerMaskLayer if self.mosaicPaths.isEmpty { self.imageView.image = self.editImage } else { self.generateNewMosaicImage() } } else { self.imageView.image = self.editImage } } collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) collectionView.reloadData() } } extension ZLEditImageViewController: ZLTextStickerViewDelegate { func stickerBeginOperation(_ sticker: UIView) { self.setToolView(show: false) self.ashbinView.layer.removeAllAnimations() self.ashbinView.isHidden = false var frame = self.ashbinView.frame let diff = self.view.frame.height - frame.minY frame.origin.y += diff self.ashbinView.frame = frame frame.origin.y -= diff UIView.animate(withDuration: 0.25) { self.ashbinView.frame = frame } self.stickersContainer.subviews.forEach { (view) in if view !== sticker { (view as? ZLStickerViewAdditional)?.resetState() (view as? ZLStickerViewAdditional)?.gesIsEnabled = false } } } func stickerOnOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer) { let point = panGes.location(in: self.view) if self.ashbinView.frame.contains(point) { self.ashbinView.backgroundColor = zlRGB(241, 79, 79).withAlphaComponent(0.98) self.ashbinImgView.isHighlighted = true if sticker.alpha == 1 { sticker.layer.removeAllAnimations() UIView.animate(withDuration: 0.25) { sticker.alpha = 0.5 } } } else { self.ashbinView.backgroundColor = ZLEditImageViewController.ashbinNormalBgColor self.ashbinImgView.isHighlighted = false if sticker.alpha != 1 { sticker.layer.removeAllAnimations() UIView.animate(withDuration: 0.25) { sticker.alpha = 1 } } } } func stickerEndOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer) { self.setToolView(show: true) self.ashbinView.layer.removeAllAnimations() self.ashbinView.isHidden = true let point = panGes.location(in: self.view) if self.ashbinView.frame.contains(point) { (sticker as? ZLStickerViewAdditional)?.moveToAshbin() } self.stickersContainer.subviews.forEach { (view) in (view as? ZLStickerViewAdditional)?.gesIsEnabled = true } } func stickerDidTap(_ sticker: UIView) { self.stickersContainer.subviews.forEach { (view) in if view !== sticker { (view as? ZLStickerViewAdditional)?.resetState() } } } func sticker(_ textSticker: ZLTextStickerView, editText text: String) { self.showInputTextVC(text, textColor: textSticker.textColor, bgColor: textSticker.bgColor) { [weak self] (text, textColor, bgColor) in guard let `self` = self else { return } if text.isEmpty { textSticker.moveToAshbin() } else { textSticker.startTimer() guard textSticker.text != text || textSticker.textColor != textColor || textSticker.bgColor != bgColor else { return } textSticker.text = text textSticker.textColor = textColor textSticker.bgColor = bgColor let newSize = ZLTextStickerView.calculateSize(text: text, width: self.view.frame.width) textSticker.changeSize(to: newSize) } } } } extension ZLEditImageViewController { @objc public enum EditImageTool: Int { case draw case clip case imageSticker case textSticker case mosaic case filter } } // MARK: 裁剪比例 public class ZLImageClipRatio: NSObject { public var title: String public let whRatio: CGFloat let isCircle: Bool @objc public init(title: String, whRatio: CGFloat, isCircle: Bool = false) { self.title = title self.whRatio = isCircle ? 1 : whRatio self.isCircle = isCircle super.init() } } extension ZLImageClipRatio { static func ==(lhs: ZLImageClipRatio, rhs: ZLImageClipRatio) -> Bool { return lhs.whRatio == rhs.whRatio && lhs.title == rhs.title } } extension ZLImageClipRatio { @objc public static let custom = ZLImageClipRatio(title: "custom", whRatio: 0) @objc public static let circle = ZLImageClipRatio(title: "circle", whRatio: 1, isCircle: true) @objc public static let wh1x1 = ZLImageClipRatio(title: "1 : 1", whRatio: 1) @objc public static let wh3x4 = ZLImageClipRatio(title: "3 : 4", whRatio: 3.0/4.0) @objc public static let wh4x3 = ZLImageClipRatio(title: "4 : 3", whRatio: 4.0/3.0) @objc public static let wh2x3 = ZLImageClipRatio(title: "2 : 3", whRatio: 2.0/3.0) @objc public static let wh3x2 = ZLImageClipRatio(title: "3 : 2", whRatio: 3.0/2.0) @objc public static let wh9x16 = ZLImageClipRatio(title: "9 : 16", whRatio: 9.0/16.0) @objc public static let wh16x9 = ZLImageClipRatio(title: "16 : 9", whRatio: 16.0/9.0) } // MARK: Edit tool cell class ZLEditToolCell: UICollectionViewCell { var toolType: ZLEditImageViewController.EditImageTool? { didSet { switch toolType { case .draw?: self.icon.image = getImage("zl_drawLine") self.icon.highlightedImage = getImage("zl_drawLine_selected") case .clip?: self.icon.image = getImage("zl_clip") self.icon.highlightedImage = getImage("zl_clip") case .imageSticker?: self.icon.image = getImage("zl_imageSticker") self.icon.highlightedImage = getImage("zl_imageSticker") case .textSticker?: self.icon.image = getImage("zl_textSticker") self.icon.highlightedImage = getImage("zl_textSticker") case .mosaic?: self.icon.image = getImage("zl_mosaic") self.icon.highlightedImage = getImage("zl_mosaic_selected") case .filter?: self.icon.image = getImage("zl_filter") self.icon.highlightedImage = getImage("zl_filter_selected") default: break } } } var icon: UIImageView! override init(frame: CGRect) { super.init(frame: frame) self.icon = UIImageView(frame: self.contentView.bounds) self.contentView.addSubview(self.icon) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: draw color cell class ZLDrawColorCell: UICollectionViewCell { var bgWhiteView: UIView! var colorView: UIView! var color: UIColor! { didSet { self.colorView.backgroundColor = color } } override init(frame: CGRect) { super.init(frame: frame) self.bgWhiteView = UIView() self.bgWhiteView.backgroundColor = .white self.bgWhiteView.layer.cornerRadius = 10 self.bgWhiteView.layer.masksToBounds = true self.bgWhiteView.frame = CGRect(x: 0, y: 0, width: 20, height: 20) self.bgWhiteView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) self.contentView.addSubview(self.bgWhiteView) self.colorView = UIView() self.colorView.layer.cornerRadius = 8 self.colorView.layer.masksToBounds = true self.colorView.frame = CGRect(x: 0, y: 0, width: 16, height: 16) self.colorView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) self.contentView.addSubview(self.colorView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: filter cell class ZLFilterImageCell: UICollectionViewCell { var nameLabel: UILabel! var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) self.nameLabel = UILabel(frame: CGRect(x: 0, y: self.bounds.height-20, width: self.bounds.width, height: 20)) self.nameLabel.font = getFont(12) self.nameLabel.textColor = .white self.nameLabel.textAlignment = .center self.nameLabel.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor self.nameLabel.layer.shadowOffset = .zero self.nameLabel.layer.shadowOpacity = 1 self.nameLabel.adjustsFontSizeToFitWidth = true self.nameLabel.minimumScaleFactor = 0.5 self.contentView.addSubview(self.nameLabel) self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.width)) self.imageView.contentMode = .scaleAspectFill self.imageView.clipsToBounds = true self.contentView.addSubview(self.imageView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: 涂鸦path public class ZLDrawPath: NSObject { let pathColor: UIColor let path: UIBezierPath let ratio: CGFloat let shapeLayer: CAShapeLayer init(pathColor: UIColor, pathWidth: CGFloat, ratio: CGFloat, startPoint: CGPoint) { self.pathColor = pathColor self.path = UIBezierPath() self.path.lineWidth = pathWidth / ratio self.path.lineCapStyle = .round self.path.lineJoinStyle = .round self.path.move(to: CGPoint(x: startPoint.x / ratio, y: startPoint.y / ratio)) self.shapeLayer = CAShapeLayer() self.shapeLayer.lineCap = .round self.shapeLayer.lineJoin = .round self.shapeLayer.lineWidth = pathWidth / ratio self.shapeLayer.fillColor = UIColor.clear.cgColor self.shapeLayer.strokeColor = pathColor.cgColor self.shapeLayer.path = self.path.cgPath self.ratio = ratio super.init() } func addLine(to point: CGPoint) { self.path.addLine(to: CGPoint(x: point.x / self.ratio, y: point.y / self.ratio)) self.shapeLayer.path = self.path.cgPath } func drawPath() { self.pathColor.set() self.path.stroke() } } // MARK: 马赛克path public class ZLMosaicPath: NSObject { let path: UIBezierPath let ratio: CGFloat let startPoint: CGPoint var linePoints: [CGPoint] = [] init(pathWidth: CGFloat, ratio: CGFloat, startPoint: CGPoint) { self.path = UIBezierPath() self.path.lineWidth = pathWidth self.path.lineCapStyle = .round self.path.lineJoinStyle = .round self.path.move(to: startPoint) self.ratio = ratio self.startPoint = CGPoint(x: startPoint.x / ratio, y: startPoint.y / ratio) super.init() } func addLine(to point: CGPoint) { self.path.addLine(to: point) self.linePoints.append(CGPoint(x: point.x / self.ratio, y: point.y / self.ratio)) } }
39.782383
273
0.628517
4add0fa3625559ef859840660856b895a2f71ee1
236
extension CLProximity { var description: String { switch self { case .unknown: return "Unk" case .immediate: return "Imm" case .near: return "Near" case .far: return "Far" } } }
18.153846
37
0.533898
76b9131518412886a09155920ee3df08fbff852e
1,030
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Viper", platforms: [.iOS(.v13)], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Viper", targets: ["Viper"]), ], 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: "Viper", dependencies: []), .testTarget( name: "ViperTests", dependencies: ["Viper"]), ] )
34.333333
122
0.608738
761a18ce2b805211b4ccd85d1ba159e4d028be15
2,612
// // CustomInlineCamera.swift // DKImagePickerControllerDemo // // Created by ZhangAo on 03/01/2017. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit import MobileCoreServices import FTDKImagePickerController open class CustomInlineCameraExtension: DKImageBaseExtension, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var didCancel: (() -> Void)? var didFinishCapturingImage: ((_ image: UIImage, _ metadata: [AnyHashable : Any]?) -> Void)? var didFinishCapturingVideo: ((_ videoURL: URL) -> Void)? open override func perform(with extraInfo: [AnyHashable : Any]) { guard let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void) , let didFinishCapturingVideo = extraInfo["didFinishCapturingVideo"] as? ((URL) -> Void) , let didCancel = extraInfo["didCancel"] as? (() -> Void) else { return } self.didFinishCapturingImage = didFinishCapturingImage self.didFinishCapturingVideo = didFinishCapturingVideo self.didCancel = didCancel let camera = UIImagePickerController() camera.delegate = self camera.sourceType = .camera camera.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String] if (camera as UIViewController) is UINavigationController { self.context.imagePickerController.present(camera, animated: true) self.context.imagePickerController.setViewControllers([], animated: false) } else { self.context.imagePickerController.setViewControllers([camera], animated: false) } } open override func finish() { self.context.imagePickerController.dismiss(animated: true) } // MARK: - UIImagePickerControllerDelegate methods open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let mediaType = info[.mediaType] as! String if mediaType == kUTTypeImage as String { let metadata = info[.mediaMetadata] as! [AnyHashable : Any] let image = info[.originalImage] as! UIImage self.didFinishCapturingImage?(image, metadata) } else if mediaType == kUTTypeMovie as String { let videoURL = info[.mediaURL] as! URL self.didFinishCapturingVideo?(videoURL) } } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.didCancel?() } }
40.184615
149
0.676493
23769004a069d15ab3071d020ded8bd5cf65b78b
9,558
// // MainScene.swift // Shooter // // Created by Argentino Ducret on 6/7/17. // Copyright © 2017 ITBA. All rights reserved. // import SpriteKit import UIKit import GameplayKit import Foundation public class MainScene: SKScene, SKPhysicsContactDelegate { fileprivate var player: Player! fileprivate var lastInterval: TimeInterval? = .none fileprivate var enemies: [Enemy]! fileprivate let lifesLabel = SKLabelNode(fontNamed: "Apple Symbols") fileprivate let enemiesLabel = SKLabelNode(fontNamed: "Apple Symbols") public override func didMove(to view: SKView) { super.didMove(to: view) configureWorld() updateNodes() addCamera() enemies = children.filter { $0.name ?? "" == "Enemy"}.map { $0 as! Enemy } enemies.forEach { $0.player = player } addLabels() } public override func update(_ currentTime: TimeInterval) { super.update(currentTime) let win = enemies.reduce(true) { $0 && $1.parent == nil } if win { let transition = SKTransition.reveal(with: .up, duration: 1.0) let nextScene = MenuScene(fileNamed: "MenuScene") nextScene!.scaleMode = .aspectFill nextScene!.stateText = "You WIN!!!" view?.presentScene(nextScene!, transition: transition) return } if player.parent == nil { let transition = SKTransition.reveal(with: .up, duration: 1.0) let nextScene = MenuScene(fileNamed: "MenuScene") nextScene!.scaleMode = .aspectFill nextScene!.stateText = "Game Over" view?.presentScene(nextScene!, transition: transition) return } if lastInterval == .none { lastInterval = currentTime } let delta = currentTime - lastInterval! player.updateMovement(byTimeDelta: delta) enemies.forEach { $0.updateMovement(byTimeDelta: delta) } lastInterval = currentTime } public override func didFinishUpdate() { super.didFinishUpdate() updateCamera(on: player) lifesLabel.text = "Lifes: \(player.lifes)" let enemiesCount = enemies.reduce(0) { $0 + ($1.parent == nil ? 0 : 1) } enemiesLabel.text = "Enemies: \(enemiesCount)" } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first?.location(in: self) { for node in nodes(at: touch) { if node.name == "Wall" { break } if node.name == "Enemy" { player.pointTouched = touch break } if node.name == "Grass" { player.pointTouched = touch } } } } public func didBegin(_ contact: SKPhysicsContact) { var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if ((firstBody.categoryBitMask & PhysicsCategory.Enemy != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shot != 0)) { if let shot = secondBody.node { shot.isHidden = true } } if ((firstBody.categoryBitMask & PhysicsCategory.Player != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shot != 0)) { if let shot = secondBody.node { shot.isHidden = true } } if ((firstBody.categoryBitMask & PhysicsCategory.Wall != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shot != 0)) { if let shot = secondBody.node { shot.removeFromParent() } } if ((firstBody.categoryBitMask & PhysicsCategory.Player != 0) && (secondBody.categoryBitMask & PhysicsCategory.Life != 0)) { if let life = secondBody.node { life.removeFromParent() } player.lifes += 2 } } public func didEnd(_ contact: SKPhysicsContact) { var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if ((firstBody.categoryBitMask & PhysicsCategory.Enemy != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shot != 0)) { if let shot = secondBody.node { shot.removeFromParent() } if let enemy = firstBody.node as? Enemy { enemy.shooted() } } if ((firstBody.categoryBitMask & PhysicsCategory.Player != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shot != 0)) { if let shot = secondBody.node { shot.removeFromParent() } player.shooted() } } } // MARK: - Private Methods fileprivate extension MainScene { fileprivate func updateCamera(on node: SKSpriteNode) { let nodeFrame = node.calculateAccumulatedFrame() let cameraPositionX = nodeFrame.origin.x + nodeFrame.width / 2 let cameraPositiony = nodeFrame.origin.y + nodeFrame.height / 2 camera?.position = CGPoint(x: cameraPositionX, y: cameraPositiony) } fileprivate func addCamera() { let mainCamera = SKCameraNode() camera = mainCamera addChild(mainCamera) } fileprivate func updateNodes() { children .filter { $0.name == "Player" } .map { $0 as! SKSpriteNode } .forEach { $0.physicsBody = SKPhysicsBody(rectangleOf: $0.texture!.size()) $0.physicsBody?.categoryBitMask = PhysicsCategory.Player $0.physicsBody?.contactTestBitMask = PhysicsCategory.Shot $0.physicsBody?.collisionBitMask = PhysicsCategory.Enemy | PhysicsCategory.Wall $0.physicsBody?.mass = 5 $0.physicsBody?.affectedByGravity = false $0.physicsBody?.usesPreciseCollisionDetection = true self.player = $0 as! Player } children .filter { $0.name == "Grass" } .forEach { $0.physicsBody = SKPhysicsBody(rectangleOf: $0.frame.size) $0.physicsBody?.isDynamic = false $0.physicsBody?.categoryBitMask = PhysicsCategory.Grass $0.physicsBody?.contactTestBitMask = 0 $0.physicsBody?.collisionBitMask = 0 } children .filter { $0.name == "Wall" } .forEach { $0.physicsBody = SKPhysicsBody(rectangleOf: $0.frame.size) $0.physicsBody?.isDynamic = false $0.physicsBody?.categoryBitMask = PhysicsCategory.Wall $0.physicsBody?.contactTestBitMask = 0 $0.physicsBody?.collisionBitMask = 0 } children .filter { $0.name == "Enemy" } .map { $0 as! SKSpriteNode } .forEach { $0.physicsBody = SKPhysicsBody(rectangleOf: $0.texture!.size()) $0.physicsBody?.categoryBitMask = PhysicsCategory.Enemy $0.physicsBody?.contactTestBitMask = PhysicsCategory.Shot $0.physicsBody?.collisionBitMask = PhysicsCategory.Player | PhysicsCategory.Wall $0.physicsBody?.mass = 5 $0.physicsBody?.affectedByGravity = false $0.physicsBody?.usesPreciseCollisionDetection = true } children .filter { $0.name == "Life" } .map { $0 as! SKSpriteNode } .forEach { $0.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 40)) $0.physicsBody?.categoryBitMask = PhysicsCategory.Life $0.physicsBody?.contactTestBitMask = PhysicsCategory.Player $0.physicsBody?.collisionBitMask = 0 $0.physicsBody?.mass = 5 $0.physicsBody?.affectedByGravity = false $0.physicsBody?.usesPreciseCollisionDetection = true } } fileprivate func configureWorld() { physicsWorld.gravity = CGVector.zero physicsWorld.contactDelegate = self } fileprivate func addLabels() { lifesLabel.text = "Lifes: \(player.lifes)" lifesLabel.zPosition = 100 lifesLabel.position = CGPoint(x: 0, y: size.height / 2 - lifesLabel.frame.height) camera?.addChild(lifesLabel) enemiesLabel.text = String(format: "Enemies: \(enemies.count)") enemiesLabel.zPosition = 100 // enemiesLabel.fontSize = 17 enemiesLabel.position = CGPoint(x: size.width / 2 - enemiesLabel.frame.width + 20, y: size.height / 2 - enemiesLabel.frame.height) camera?.addChild(enemiesLabel) } }
35.932331
138
0.558694
181d20c6a5668458241bd2331d2a3c89a7f5c562
1,311
import Foundation // {{## BEGIN simple-operator ##}} func +(left: [Double], right: [Double]) -> [Double] { var sum = [Double](repeating: 0.0, count: left.count) for (i, _) in left.enumerated() { sum[i] = left[i] + right[i] } return sum } let result = [1, 2] + [3, 4] print(result) // {{## END simple-operator ##}} // {{## BEGIN mixed-operator ##}} func * (left: String, right: Int) -> String { if right <= 0 { return "" } var result = left for _ in 1..<right { result += left } return result } let scream = "a" * 6 print(scream) // {{## END mixed-operator ##}} // {{## BEGIN vector ##}} struct Vector: CustomStringConvertible { let x: Int let y: Int let z: Int var description: String { return "(\(x), \(y), \(z))" } init(_ x: Int, _ y: Int, _ z: Int) { self.x = x self.y = y self.z = z } // {{## END vector ##}} // {{## BEGIN vector-ops ##}} static func +(left: Vector, right: Vector) -> Vector { return Vector(left.x + right.x, left.y + right.y, left.z + right.z) } static prefix func -(vector: Vector) -> Vector { return Vector(-vector.x, -vector.y, -vector.z) } // {{## END vector-ops ##}} } let vectorA = Vector(1, 3, 2) let vectorB = Vector(-2, 5, 1) print(vectorA + vectorB)
21.85
57
0.540046
679dfda68c5a6de4fb0cea2cea830028c434836f
1,572
// // SpyConfigurationTests.swift // SpyTests // // Created by Tomasz Lewandowski on 23/01/2020. // Copyright © 2020 AppUnite Sp. z o.o. All rights reserved. // import XCTest import Spy public final class SpyConfigurationTests: XCTestCase { private var sut: SpyConfiguration<SpyLevel, SpyChannel>! public override func setUp() { sut = SpyConfiguration(spyOnLevels: [.info], spyOnChannels: [.foo]) } func testInit_WhenInitializedWithNoLevelsAndChannels_ShouldNotHaveLevelsAndChannelsSet() { sut = SpyConfiguration() XCTAssertEqual([], sut.spyOnLevels) XCTAssertEqual([], sut.spyOnChannels) } func testInit_WhenInitializedWithLevelsAndChannels_ShouldNotHaveTheseLevelsAndChannelsSet() { sut = SpyConfiguration(spyOnLevels: [.info, .warning], spyOnChannels: [.foo, .bar]) XCTAssertEqual([.info, .warning], sut.spyOnLevels) XCTAssertEqual([.foo, .bar], sut.spyOnChannels) } func testShouldLog_WhenOnlyChannelIsValid_ShouldReturnFalse() { XCTAssertFalse(sut.shouldLog(level: .warning, channel: .foo)) } func testShouldLog_WhenOnlyLevelIsValid_ShouldReturnFalse() { XCTAssertFalse(sut.shouldLog(level: .info, channel: .bar)) } func testShouldLog_WhenBothLevelChannelAreInvalid_ShouldReturnFalse() { XCTAssertFalse(sut.shouldLog(level: .warning, channel: .bar)) } func testShouldLog_WhenBothLevelChannelAreValid_ShouldReturnTrue() { XCTAssertTrue(sut.shouldLog(level: .info, channel: .foo)) } }
34.173913
97
0.708651
e0d8a86c49aec0eb5bfcecb3b068c142f2bee57e
2,601
// // MMDVACReader.swift // MMDSceneKit // // Created by magicien on 11/25/16. // Copyright © 2016 DarkHorse. All rights reserved. // import SceneKit class MMDVACReader: MMDReader { static func getNode(_ data: Data, directoryPath: String! = "") -> MMDNode? { let reader = MMDVACReader(data: data, directoryPath: directoryPath) let node = reader.loadVACFile() return node } // MARK: - Loading VMD File /** */ private func loadVACFile() -> MMDNode? { let data = String(data: self.binaryData, encoding: .shiftJIS) if let lines = data?.components(separatedBy: "\r\n") { if lines.count < 6 { return nil } let name = lines[0] let fileName = lines[1] let scaleStr = lines[2] let positions = lines[3].components(separatedBy: ",") let rotations = lines[4].components(separatedBy: ",") let boneName = lines[5] let xFilePath = (self.directoryPath as NSString).appendingPathComponent(fileName) var model: MMDNode? = nil if let scene = MMDSceneSource(path: xFilePath) { model = scene.getModel() } else { print("can't read file: \(xFilePath)") } if let mmdModel = model { mmdModel.name = name if let scale = Float(scaleStr) { let s = OSFloat(scale * 10.0) mmdModel.scale = SCNVector3Make(s, s, s) } else { mmdModel.scale = SCNVector3Make(10.0, 10.0, 10.0) } if positions.count >= 3 { let posX = Float(positions[0]) let posY = Float(positions[1]) let posZ = Float(positions[2]) if let x = posX, let y = posY, let z = posZ { mmdModel.position = SCNVector3Make(OSFloat(x), OSFloat(y), OSFloat(z)) } } if rotations.count >= 3 { let rotX = Float(rotations[0]) let rotY = Float(rotations[1]) let rotZ = Float(rotations[2]) if let x = rotX, let y = rotY, let z = rotZ { // TODO: implement } } return mmdModel } } return nil } }
32.5125
94
0.459054
8a0757ce6916cb3a5169f5d02531ed3133cf0a71
5,808
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: BuildSystem/Evaluation/configuration.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors import Foundation import SwiftProtobuf import llbuild2 // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// A ConfigurationKey represents the configuration to use while evaluating a project. It should contain the minimum set /// of data required in order to construct a full configuration fragment. Each configuration fragment key should be /// considered as a build key where the build value is the evaluated configuration for the key. The ConfigurationFunction /// requests the value for each of the fragment keys, and it will be up to the client implementation to provide functions /// that evaluate those keys into ConfigurationFragments. public struct LLBConfigurationKey { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var fragmentKeys: [llbuild2.LLBAnySerializable] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// A collection of configuration fragments as requested by a ConfigurationKey. The ConfigurationValue will be made /// available at rule evaluation time from the rule context. public struct LLBConfigurationValue { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var fragments: [llbuild2.LLBAnySerializable] = [] /// Contains a hash of the fragments that can be used as a root for derived artifacts. public var root: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. extension LLBConfigurationKey: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = "LLBConfigurationKey" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "fragmentKeys"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.fragmentKeys) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.fragmentKeys.isEmpty { try visitor.visitRepeatedMessageField(value: self.fragmentKeys, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: LLBConfigurationKey, rhs: LLBConfigurationKey) -> Bool { if lhs.fragmentKeys != rhs.fragmentKeys {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension LLBConfigurationValue: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = "LLBConfigurationValue" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "fragments"), 2: .same(proto: "root"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.fragments) }() case 2: try { try decoder.decodeSingularStringField(value: &self.root) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.fragments.isEmpty { try visitor.visitRepeatedMessageField(value: self.fragments, fieldNumber: 1) } if !self.root.isEmpty { try visitor.visitSingularStringField(value: self.root, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: LLBConfigurationValue, rhs: LLBConfigurationValue) -> Bool { if lhs.fragments != rhs.fragments {return false} if lhs.root != rhs.root {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
42.086957
133
0.749311
e5cd826257b1310eef73571eb553219d35ff5839
19,768
// // YGButton.swift // YGButton // // Created by yogalau on 2020/11/5. // Copyright (c) 2020 yogalau. All rights reserved. // import UIKit class YGButton: UIControl { //MARK: - Button Properties private var normalColor: UIColor? /// Button hightlightColor var hightlightColor: UIColor? /// Button cornerRadius, default is 0. It will default set the cornerCurve property is continuous when system version greater than iOS 13. var cornerRadius: CGFloat = 0 { didSet { if roundingCorners == .allCorners { layer.cornerRadius = cornerRadius if #available(iOS 13, *) { layer.cornerCurve = .continuous } } else { layer.cornerRadius = 0 } } } /// Button rounded corners, default is allCorners. You can custom the rounding corners by this property. if the button set this property it will Off-Screen Render. var roundingCorners: UIRectCorner = .allCorners { didSet { let current = cornerRadius cornerRadius = current } } //MARK: - Content View Properties private let contentView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.isUserInteractionEnabled = false stackView.spacing = 8 stackView.distribution = .equalCentering return stackView }() /// Button content spacing, default is 8 var contentSpacing: CGFloat = 8 { didSet { contentView.spacing = contentSpacing } } /// Button content inset, default is zero. var contentInset: UIEdgeInsets = .zero { didSet { contentTopInset.constant = contentInset.top contentBottomInset.constant = contentInset.bottom * -1 contentLeftInset.constant = contentInset.left contentRightInset.constant = contentInset.right * -1 } } private var contentCenterY: NSLayoutConstraint! private var contentCenterX: NSLayoutConstraint! private var contentTopInset: NSLayoutConstraint! private var contentBottomInset: NSLayoutConstraint! private var contentLeftInset: NSLayoutConstraint! private var contentRightInset: NSLayoutConstraint! /** Button content axis, default is horizontal. Button must with image content. E.g if you set the image for button so image and title contents align with horizontal. if the property set vertical, image and title contents align with vertical. */ var contentAxis = NSLayoutConstraint.Axis.horizontal { didSet { contentView.axis = contentAxis guard let imageView = imageView else { return } switch contentAxis { case .horizontal: let current = imageHorizontalPosition imageHorizontalPosition = current break case .vertical: let current = imageVerticalPosition imageVerticalPosition = current break @unknown default: break } if contentAxis == .horizontal { if let imageCenterX = imageCenterX, let imageTopInset = imageTopInset, let imageBottomInset = imageBottomInset { imageContentView.removeConstraints([ imageCenterX, imageTopInset, imageBottomInset ]) } imageCenterY = .init(item: imageContentView, attribute: .centerY, relatedBy: .equal, toItem: imageView, attribute: .centerY, multiplier: 1, constant: 0) imageContentView.addConstraint(imageCenterY) imageLeftInset = .init(item: imageContentView, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .left, multiplier: 1, constant: 0) imageContentView.addConstraint(imageLeftInset) imageRightInset = .init(item: imageContentView, attribute: .right, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 0) imageContentView.addConstraint(imageRightInset) } else { if let imageCenterY = imageCenterY, let imageLeftInset = imageLeftInset, let imageRightInset = imageRightInset { imageContentView.removeConstraints([ imageCenterY, imageLeftInset, imageRightInset ]) } imageCenterX = .init(item: imageContentView, attribute: .centerX, relatedBy: .equal, toItem: imageView, attribute: .centerX, multiplier: 1, constant: 0) imageContentView.addConstraint(imageCenterX) imageTopInset = .init(item: imageContentView, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .top, multiplier: 1, constant: 0) imageContentView.addConstraint(imageTopInset) imageBottomInset = .init(item: imageContentView, attribute: .bottom, relatedBy: .equal, toItem: imageView, attribute: .bottom, multiplier: 1, constant: 0) imageContentView.addConstraint(imageBottomInset) } } } //MARK: - Title Label Properties private var titleLabel: UILabel? /// Button's title label content. var title: String? { get { return titleLabel?.text } set { guard let newValue = newValue else { return } titleLabel = UILabel() titleLabel?.translatesAutoresizingMaskIntoConstraints = false titleLabel?.text = newValue contentView.addArrangedSubview(titleLabel!) } } /// Button's title label text color. default is BLACK. var titleColor: UIColor? { get { return titleLabel?.textColor } set { titleLabel?.textColor = newValue ?? .black } } /// Button's title label text font. default of size is 14. var titleFont: UIFont? { get { return titleLabel?.font } set { titleLabel?.font = newValue ?? .systemFont(ofSize: 14) } } //MARK: - Image Properties private let imageContentView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private var imageView: ImageView? { didSet { guard let imageView = imageView else { return } imageView.translatesAutoresizingMaskIntoConstraints = false imageContentView.addSubview(imageView) let current = contentAxis contentAxis = current } } private var imageCenterX: NSLayoutConstraint! private var imageCenterY: NSLayoutConstraint! private var imageTopInset: NSLayoutConstraint! private var imageBottomInset: NSLayoutConstraint! private var imageLeftInset: NSLayoutConstraint! private var imageRightInset: NSLayoutConstraint! private var imageWidth: NSLayoutConstraint! private var imageHeight: NSLayoutConstraint! /// Button's image content. var image: UIImage? { get { return imageView?.image } set { guard let newValue = newValue else { return } if let imageView = imageView { imageView.image = newValue } else { imageView = ImageView(image: newValue) } contentView.insertArrangedSubview(imageContentView, at: 0) // Default is the first subview } } /// Button's image content size. var imageSize: CGSize = .zero { didSet { guard let imageView = imageView else { return } imageView.contentSize = imageSize } } /** Button's image horizontal position. AtTitleRight: The image is to the right of the title. *** AtTitleLeft: The image is to the left of the title. */ enum ImageHorizontalPosition: Int { case AtTitleLeft = 0 case AtTitleRight = 1 } /** Button's image vertical position AtTitleTop: The image is to the top of the title. *** AtTitleBottom: The image is to bottom left of the title. */ enum ImageVerticalPosition: Int { case AtTitleTop = 0 case AtTitleBottom = 1 } /// Button's image horizontal position, default is AtTitleLeft. E.g The image is to the top of the title. var imageHorizontalPosition: ImageHorizontalPosition = .AtTitleLeft { didSet { guard let _ = titleLabel, contentAxis == .horizontal else { return } imageContentView.removeFromSuperview() switch imageHorizontalPosition { case .AtTitleLeft: contentView.insertArrangedSubview(imageContentView, at: ImageHorizontalPosition.AtTitleLeft.rawValue) break case .AtTitleRight: contentView.insertArrangedSubview(imageContentView, at: ImageHorizontalPosition.AtTitleRight.rawValue) break } } } /// Button's image vertical position, default is AtTitleTop. E.g The image is to the bottom of the title. var imageVerticalPosition: ImageVerticalPosition = .AtTitleTop { didSet { guard let _ = titleLabel, contentAxis == .vertical else { return } imageContentView.removeFromSuperview() switch imageVerticalPosition { case .AtTitleTop: contentView.insertArrangedSubview(imageContentView, at: ImageVerticalPosition.AtTitleTop.rawValue) break case .AtTitleBottom: contentView.insertArrangedSubview(imageContentView, at: ImageVerticalPosition.AtTitleBottom.rawValue) break } } } //MARK: Override Super Property override var frame: CGRect { didSet { translatesAutoresizingMaskIntoConstraints = true } } override var backgroundColor: UIColor? { get { return super.backgroundColor } set { guard let newValue = newValue else { return } super.backgroundColor = newValue if !newValue.isEqual(hightlightColor) { normalColor = newValue } } } override var isHighlighted: Bool { didSet { guard let hightlightColor = hightlightColor, let normalColor = normalColor else { return } UIView.transition(with: self, duration: 0.1, options: .curveLinear, animations: { [unowned self] in backgroundColor = isHighlighted ? hightlightColor : normalColor }, completion: nil) } } /// A color used to tint template images in the view hierarchy. override var tintColor: UIColor! { didSet { imageView?.tintColor = tintColor } } /// The horizontal alignment of content (text and images) within a control. override var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment { didSet { setNeedsLayout() } } /// Constants for specifying the vertical alignment of content (text and images) in a control. override var contentVerticalAlignment: UIControl.ContentVerticalAlignment { didSet { setNeedsLayout() } } //MARK: Override Super Function override init(frame: CGRect) { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) // Init content constraints variables contentCenterX = .init(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) contentCenterY = .init(item: contentView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) contentTopInset = .init(item: contentView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: contentInset.top) addConstraint(contentTopInset) contentBottomInset = .init(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: contentInset.bottom * -1) addConstraint(contentBottomInset) contentLeftInset = .init(item: contentView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: contentInset.left) addConstraint(contentLeftInset) contentRightInset = .init(item: contentView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: contentInset.right * -1) addConstraint(contentRightInset) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setNeedsDisplay() layoutIfNeeded() //MARK: - Corners if roundingCorners != .allCorners { drawRoundingCorners() } guard let titleLabel = titleLabel, let imageView = imageView, let image = imageView.image else { return } var contentWidth: CGFloat = 0 var contentHeight: CGFloat = 0 switch contentAxis { case .horizontal: contentWidth = image.size.width + contentSpacing + titleLabel.frame.width + contentInset.left + contentInset.right if image.size.height > titleLabel.frame.height { contentHeight = image.size.height } else { contentHeight = titleLabel.frame.height } break case .vertical: if image.size.width > titleLabel.frame.width { contentWidth = image.size.width } else { contentWidth = titleLabel.frame.width } contentHeight = image.size.height + contentSpacing + titleLabel.frame.height + contentInset.top + contentInset.bottom break @unknown default: break } // If the button actually width greater than content width then align the content view according to contentHorizontal. if frame.width > contentWidth { switch contentHorizontalAlignment { case .center: if !contentCenterX.isActive { addConstraint(contentCenterX) } removeConstraint(contentLeftInset) removeConstraint(contentRightInset) break case .left: removeConstraint(contentCenterX) if !contentLeftInset.isActive { addConstraint(contentLeftInset) } removeConstraint(contentRightInset) break case .right: removeConstraint(contentCenterX) removeConstraint(contentLeftInset) if !contentRightInset.isActive { addConstraint(contentRightInset) } break case .fill: removeConstraint(contentCenterX) if !contentLeftInset.isActive { addConstraint(contentLeftInset) } if !contentRightInset.isActive { addConstraint(contentRightInset) } default: if !contentCenterX.isActive { addConstraint(contentCenterX) } removeConstraint(contentLeftInset) removeConstraint(contentRightInset) break } } // If the button actually width greater than content width then align the content view according to contentHorizontal if frame.height > contentHeight { switch contentVerticalAlignment { case .center: if !contentCenterY.isActive { addConstraint(contentCenterY) } removeConstraint(contentTopInset) removeConstraint(contentBottomInset) break case .top: removeConstraint(contentCenterY) if !contentTopInset.isActive { addConstraint(contentTopInset) } removeConstraint(contentBottomInset) break case .bottom: removeConstraint(contentCenterY) removeConstraint(contentTopInset) if !contentBottomInset.isActive { addConstraint(contentBottomInset) } break case .fill: removeConstraint(contentCenterY) if !contentTopInset.isActive { addConstraint(contentTopInset) } if !contentBottomInset.isActive { addConstraint(contentBottomInset) } default: if !contentCenterY.isActive { addConstraint(contentCenterY) } removeConstraint(contentTopInset) removeConstraint(contentBottomInset) break } } // If height of image greater than button so make them equal if image.size.height > frame.height { imageTopInset = .init(item: imageContentView, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .top, multiplier: 1, constant: 0) imageContentView.addConstraint(imageTopInset) imageBottomInset = .init(item: imageContentView, attribute: .bottom, relatedBy: .equal, toItem: imageView, attribute: .bottom, multiplier: 1, constant: 0) imageContentView.addConstraint(imageBottomInset) } // If width of image greater than button so make them equal else if image.size.width > frame.width { imageLeftInset = .init(item: imageContentView, attribute: .left, relatedBy: .equal, toItem: imageView, attribute: .left, multiplier: 1, constant: 0) imageContentView.addConstraint(imageLeftInset) imageRightInset = .init(item: imageContentView, attribute: .right, relatedBy: .equal, toItem: imageView, attribute: .right, multiplier: 1, constant: 0) imageContentView.addConstraint(imageRightInset) } } private func drawRoundingCorners() { guard cornerRadius > 0 else { return } let rect = bounds let size = CGSize(width: cornerRadius, height: cornerRadius) let path = UIBezierPath(roundedRect: rect, byRoundingCorners: roundingCorners, cornerRadii: size) let maskLayer = CAShapeLayer() maskLayer.frame = rect maskLayer.path = path.cgPath layer.mask = maskLayer layer.shouldRasterize = true } } //MARK: - Override UIImageView's property of intrinsicContentSize, it make the image size can modify fileprivate class ImageView: UIImageView { /// Button image size var contentSize: CGSize? override var intrinsicContentSize: CGSize { return contentSize ?? super.intrinsicContentSize } }
38.913386
243
0.600769
e853a95e90b5b63903b5fe60b195297604b382b1
530
import UIKit public protocol Loadable { var loaderView: LoaderView { get set } func showLoaderView() func hideLoaderView() } extension Loadable where Self: UIView { public func showLoaderView() { guard !loaderView.isDescendant(of: self) else { return } add(loaderView, then: { $0.fillSuperview() }) } public func hideLoaderView() { guard loaderView.isDescendant(of: self) else { return } loaderView.removeFromSuperview() } }
22.083333
64
0.611321
46450d69c41fcf2acd0127888712838c8f2b7875
2,883
// // OSLogger.swift // GDPRConsentViewController // // Created by Andre Herculano on 06.10.19. // swiftlint:disable all import Foundation import os protocol SPLogger { func log(_ message: String) func debug(_ message: String) func error(_ message: String) } class OSLogger: SPLogger { static let TOO_MANY_ARGS_ERROR = StaticString("Cannot log messages with more than 5 argumetns") static let category = "GPDRConsent" let consentLog: OSLog? init(category: String) { if #available(iOS 10.0, *) { consentLog = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: category) } else { consentLog = nil } } convenience init() { self.init(category: OSLogger.category) } func log(_ message: String) { log("%s", [message]) } func debug(_ message: String) { log("%s", [message]) } func error(_ message: String) { log("%s", [message]) } func log(_ message: StaticString, _ args: [CVarArg]) { if #available(iOS 10.0, *) { switch args.count { case 0: log(message) case 1: log(message, args[0]) case 2: log(message, args[0], args[1]) case 3: log(message, args[0], args[1], args[2]) case 4: log(message, args[0], args[1], args[2], args[3]) case 5: log(message, args[0], args[1], args[2], args[3], args[4]) default: print(OSLogger.TOO_MANY_ARGS_ERROR) os_log(OSLogger.TOO_MANY_ARGS_ERROR) } } else { print(message) } } // It's not possible to forward variadic parameters in Swift so this is a gross workaround @available(iOS 10.0, *) private func log(_ message: StaticString) { os_log(message, log: consentLog!, type: .default) } @available(iOS 10.0, *) private func log(_ message: StaticString, _ a: CVarArg) { os_log(message, log: consentLog!, type: .default, a) } @available(iOS 10.0, *) private func log(_ message: StaticString, _ a: CVarArg, _ b: CVarArg) { os_log(message, log: consentLog!, type: .default, a, b) } @available(iOS 10.0, *) private func log(_ message: StaticString, _ a: CVarArg, _ b: CVarArg, _ c: CVarArg) { os_log(message, log: consentLog!, type: .default, a, b, c) } @available(iOS 10.0, *) private func log(_ message: StaticString, _ a: CVarArg, _ b: CVarArg, _ c: CVarArg, _ d: CVarArg) { os_log(message, log: consentLog!, type: .default, a, b, c, d) } @available(iOS 10.0, *) private func log(_ message: StaticString, _ a: CVarArg, _ b: CVarArg, _ c: CVarArg, _ d: CVarArg, _ e: CVarArg) { os_log(message, log: consentLog!, type: .default, a, b, c, d, e) } }
31.681319
117
0.578564
bbe9081015b5a48cca424d275835d166818a2701
5,166
// // xAPI+Download.swift // xAPI_New // // Created by Mac on 2021/8/27. // import Alamofire extension xAPI { // MARK: - 下载文件 /// 下载文件 /// - Parameters: /// - urlStr: 请求地址 /// - method: 请求方式 /// - headers: 头部 /// - parameters: 参数 /// - encoding: 参数编码类型,默认URL,或者可以切换为JSON /// - queue: 消息队列 /// - progress: 下载进度 /// - completed: 完成回调 /// - Returns: 下载对象 @discardableResult public static func download(urlStr : String, method : HTTPMethod, headers : [String : String]?, parameters : [String : Any]?, encoding: ParameterEncoding = URLEncoding.default, queue : DispatchQueue = .main, progress : @escaping xHandlerApiDownloadProgress, completed : @escaping xHandlerApiDownloadCompleted) -> DownloadRequest { // 格式化请求数据 var fm_url = self.formatterRequest(url: urlStr) var fm_parm = self.formatterRequest(parameters: parameters) let fm_head = self.formatterRequest(headers: headers) var ht_headers = HTTPHeaders() for key in fm_head.keys { guard let value = fm_head[key] else { continue } let header = HTTPHeader.init(name: key, value: value) ht_headers.add(header) } // GET请求拼接参数到URL中 if method == .get, fm_parm.count > 0 { let getStr = self.formatterGetString(of: fm_parm) fm_url = fm_url + "?" + getStr // URL编码(先解码再编码,防止2次编码) fm_url = fm_url.xToUrlDecodedString() ?? fm_url fm_url = fm_url.xToUrlEncodedString() ?? fm_url fm_parm.removeAll() // 重置参数对象 } // 创建请求体 let request = AF.download(fm_url, method: method, parameters: fm_parm, encoding: encoding, headers: ht_headers) { (req) in req.timeoutInterval = xAPI.getDownloadTimeoutDuration() // 配置超时时长 } // 开始下载 request.downloadProgress(queue: queue) { (pro) in let cur = pro.completedUnitCount let tot = pro.totalUnitCount let fra = pro.fractionCompleted progress(cur, tot, fra) }.responseData(queue: queue) { (rep) in switch rep.result { case let .success(obj): let result = self.serializerResponse(data: obj) completed(.init(state: .success, responseDataSerializerResult: result)) case let .failure(err): self.logRequestError(err) self.logRequestInfo(url: fm_url, method: method, header: fm_head, parameter: fm_parm) let result = self.serializerResponseError(code: err.responseCode, data: rep.resumeData) completed(.init(state: .failure, responseDataSerializerResult: result)) } } return request } // MARK: - 取消下载 /// 取消下载 /// - Parameter request: 下载对象 /// - Returns: 下载对象 @discardableResult public static func downloadCancel(request : DownloadRequest, completed : @escaping xHandlerApiDownloadCancel) -> DownloadRequest { request.cancel { (data) in completed(data) } return request } // MARK: - 继续下载 /// 继续下载 /// - Parameters: /// - request: 下载对象 /// - resumeData: 下载到一半的数据 /// - queue: 消息队列 /// - progress: 下载进度 /// - completed: 完成回调 /// - Returns: 下载对象 @discardableResult public static func downloadResuming(request : DownloadRequest, resumeData : Data?, queue : DispatchQueue = .main, progress : @escaping xHandlerApiDownloadProgress, completed : @escaping xHandlerApiDownloadCompleted) -> DownloadRequest { var req = request if let data = resumeData { // 继续下载 req = AF.download(resumingWith: data) } req.downloadProgress(queue: queue) { (pro) in let cur = pro.completedUnitCount let tot = pro.totalUnitCount let fra = pro.fractionCompleted progress(cur, tot, fra) }.responseData(queue: queue) { (rep) in switch rep.result { case let .success(obj): let result = self.serializerResponse(data: obj) completed(.init(state: .success, responseDataSerializerResult: result)) case let .failure(err): self.logRequestError(err) let result = self.serializerResponseError(code: err.responseCode, data: rep.resumeData) completed(.init(state: .failure, responseDataSerializerResult: result)) } } return req } }
35.875
121
0.525165
e0d509d3a9c788d224b7356cc5de635784a10fc5
7,397
// // SuggestedReplyView.swift // RichMessageKit // // Created by Shivam Pokhriyal on 18/01/19. // import UIKit /// It's a staggered grid view of buttons. /// /// Use `alignLeft` property to align the buttons to left or right side. /// Use `maxWidth` property if view has to be constrained with some maximum width. /// Pass custom `SuggestedReplyConfig` to modify font and color of view. /// - NOTE: It uses an array of dictionary where each dictionary should have `title` key which will be used as button text. public class SuggestedReplyView: UIView { // MARK: Public properties // MARK: Internal properties // This is used to align the view to left or right. Gets value from message.isMyMessage var alignLeft: Bool = true public weak var delegate: Tappable? var model: SuggestedReplyMessage? let mainStackView: UIStackView = { let stackView = UIStackView() stackView.spacing = 10 stackView.alignment = .fill stackView.axis = .vertical stackView.distribution = .fill return stackView }() // MARK: Initializers /// Initializer for `SuggestedReplyView` /// /// - Parameters: /// - maxWidth: Max Width to constrain view. /// Gives information about the title and index of quick reply selected. Indexing starts from 1. public init() { super.init(frame: .zero) setupConstraints() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Public methods /// Creates Suggested reply buttons using dictionary. /// /// - Parameter - model: Object that conforms to `SuggestedReplyMessage`. public func update(model: SuggestedReplyMessage, maxWidth: CGFloat) { self.model = model /// Set frame size. let width = maxWidth let height = SuggestedReplyView.rowHeight(model: model, maxWidth: width) let size = CGSize(width: width, height: height) frame.size = size alignLeft = !model.message.isMyMessage setupSuggestedReplyButtons(model, maxWidth: maxWidth) } /// It calculates height of `SuggestedReplyView` based on the dictionary passed. /// /// - NOTE: Padding is not used. /// - Parameters: /// - model: Object that conforms to `SuggestedReplyModel`. /// - maxWidth: MaxWidth to constrain view. pass same value used while initialization. /// - font: Font for suggested replies. Pass the custom SuggestedReplyConfig font used while initialization. /// - Returns: Returns height of view based on passed parameters. public static func rowHeight(model: SuggestedReplyMessage, maxWidth: CGFloat) -> CGFloat { return SuggestedReplyViewSizeCalculator().rowHeight(model: model, maxWidth: maxWidth) } // MARK: Private methods private func setupConstraints() { addViewsForAutolayout(views: [mainStackView]) NSLayoutConstraint.activate([ mainStackView.leadingAnchor.constraint(equalTo: leadingAnchor), mainStackView.trailingAnchor.constraint(equalTo: trailingAnchor), mainStackView.topAnchor.constraint(equalTo: topAnchor), mainStackView.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } private func setupSuggestedReplyButtons(_ suggestedMessage: SuggestedReplyMessage, maxWidth: CGFloat) { mainStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } var width: CGFloat = 0 var subviews = [UIView]() // A Boolean value to indicate whether the suggested replies span over more than 1 line. // Usage: We add hidden view to horizontal stackview due to the bug in stackview which causes subviews to // expand to cover total width.Change In case there is just 1 line, then it's probably // a better idea to just restrict the total width of stackview to the minimal required width rather than // bluntly adding hidden view all the time. var isMultiLine = false for index in 0 ..< suggestedMessage.suggestion.count { let title = suggestedMessage.suggestion[index].title let type = suggestedMessage.suggestion[index].type var button: CurvedImageButton! if type == .link { let image = UIImage(named: "link", in: Bundle.richMessageKit, compatibleWith: nil) button = curvedButton(title: title, image: image, index: index, maxWidth: maxWidth) } else { button = curvedButton(title: title, image: nil, index: index, maxWidth: maxWidth) } width += button.buttonWidth() + 10 // Button Padding if width >= maxWidth { isMultiLine = true guard !subviews.isEmpty else { let stackView = horizontalStackView(subviews: [button]) mainStackView.addArrangedSubview(stackView) width = 0 continue } let hiddenView = hiddenViewUsing(currWidth: width - button.buttonWidth(), maxWidth: maxWidth, subViews: subviews) alignLeft ? subviews.append(hiddenView) : subviews.insert(hiddenView, at: 0) width = button.buttonWidth() + 10 let stackView = horizontalStackView(subviews: subviews) mainStackView.addArrangedSubview(stackView) subviews.removeAll() subviews.append(button) } else { subviews.append(button) } } let hiddenView = hiddenViewUsing(currWidth: width, maxWidth: maxWidth, subViews: subviews) if isMultiLine { alignLeft ? subviews.append(hiddenView) : subviews.insert(hiddenView, at: 0) } let stackView = horizontalStackView(subviews: subviews) mainStackView.addArrangedSubview(stackView) } private func horizontalStackView(subviews: [UIView]) -> UIStackView { let stackView = UIStackView(arrangedSubviews: subviews) stackView.spacing = 10 stackView.alignment = .center stackView.axis = .horizontal stackView.distribution = .fill return stackView } private func hiddenViewUsing(currWidth: CGFloat, maxWidth: CGFloat, subViews _: [UIView]) -> UIView { let unusedWidth = maxWidth - currWidth - 20 let height = (subviews[0] as? CurvedImageButton)?.buttonHeight() ?? 0 let size = CGSize(width: unusedWidth, height: height) let view = UIView() view.backgroundColor = .clear view.frame.size = size return view } private func curvedButton(title: String, image: UIImage?, index: Int, maxWidth: CGFloat) -> CurvedImageButton { let button = CurvedImageButton(title: title, image: image, maxWidth: maxWidth) button.delegate = self button.index = index return button } } extension SuggestedReplyView: Tappable { public func didTap(index: Int?, title: String) { guard let index = index, let suggestion = model?.suggestion[index] else { return } let replyToBeSend = suggestion.reply ?? title delegate?.didTap(index: index, title: replyToBeSend) } }
39.983784
129
0.645126
0ebc13aab7f2b818b2d5a8e59ee37dd839deea07
1,505
import Foundation /** NOTE: This class should not be called directly in code. Use SCGameSettingsManager instead, which wraps around GameMode. Adding deprecated annotation to replaces all usages in code to use SCGameSettingsManager. **/ @available(*, deprecated) class GameMode: NSObject, NSCoding { static var instance = GameMode() fileprivate var mode: Mode? enum Mode: Int { case miniGame = 0 case regularGame = 1 } // MARK: Constructor/Destructor override init() { self.mode = .regularGame } // MARK: Coder func encode(with aCoder: NSCoder) { if let mode = self.mode?.rawValue { aCoder.encode( mode, forKey: SCConstants.coding.mode.rawValue ) } } required convenience init?(coder aDecoder: NSCoder) { self.init() if aDecoder.containsValue(forKey: SCConstants.coding.mode.rawValue) { let mode = aDecoder.decodeInteger( forKey: SCConstants.coding.mode.rawValue ) self.mode = Mode(rawValue: mode) SCGameSettingsManager.instance.enableGameSetting( .minigame, enabled: self.mode == .miniGame ) } } // MARK: Public func getMode() -> Mode? { return self.mode } func setMode(mode: Mode) { self.mode = mode } func reset() { self.mode = .regularGame } }
23.153846
90
0.575415
9196cf39eed1f18f49f81b279838daab7910e363
10,259
// // Analytics.swift // Pascal // // Created by Helena McGahagan on 11/30/18. // Copyright © 2018 Evidation Health, Inc. All rights reserved. // import AWSKinesis public protocol AnalyticsProtocol { func log(event: AnalyticsEvent) func log(event: AnalyticsEvent, completion: ((Error?) -> Void)?) } public class FirehoseAnalytics: AnalyticsProtocol { public static let MaxBatchCount = 500 enum AnalyticsError: Error { case partialFailed case uploadFailed(Error) } public typealias UserIDGetter = () -> String? public typealias SessionIDGetter = () -> String public typealias DeviceIDGetter = () -> String private static let dataStorageKey = "firehoseAnalyticsDataKey" private static let inProcessDataStorageKey = "firehoseAnalyticsInProcessDataKey" private let streamName: String private let userIDGetter: UserIDGetter private let sessionIDGetter: SessionIDGetter private let deviceIDGetter: DeviceIDGetter private let firehoseQueue = DispatchQueue(label: "com.evidation.EvidationCommon.analytics.firehose") @Storage(key: FirehoseAnalytics.dataStorageKey, defaultValue: nil) private var dataQueue: [Data]? /// Store any data in the process of being sent for each task /// If this is non-nil when the app starts up, add to the dataQueue in order to resend @Storage(key: FirehoseAnalytics.inProcessDataStorageKey, defaultValue: [:]) private var inProcessDataQueue: [Int64: [Data]] /// Incremented whenever a new data upload task is created; /// used as a key for the inProcessDataQueue private var currentTaskId: Int64 = 0 public init?(streamName: String, storage: StorageProtocol, userIDGetter: @escaping UserIDGetter, sessionIDGetter: @escaping SessionIDGetter, deviceIDGetter: @escaping DeviceIDGetter) { guard !streamName.isEmpty else { return nil } self.streamName = streamName self._dataQueue.storage = storage self._inProcessDataQueue.storage = storage self.userIDGetter = userIDGetter self.sessionIDGetter = sessionIDGetter self.deviceIDGetter = deviceIDGetter firehoseQueue.async { // Re-add any data that was in the process of sending to the data queue, to be retried later var dataQueue = self.dataQueue ?? [] let inProcessDataQueue = self.inProcessDataQueue.values.joined() dataQueue.append(contentsOf: inProcessDataQueue) self.dataQueue = dataQueue self.inProcessDataQueue = [:] } } public func log(event: AnalyticsEvent) { log(event: event, completion: nil) } public func log(event: AnalyticsEvent, completion: ((Error?) -> Void)?) { let json = generateEventJSON(from: event) firehoseQueue.async { self.putRecord(json: json, completion: completion) } } private func generateEventJSON(from event: AnalyticsEvent) -> JSONObject { var jsonDict = event.jsonDictionary // Log to the console in debug builds DebugLog.log("ANALYTICS log:") DebugLog.log("\t\(event.jsonDictionary.description)") if let userID = userIDGetter() { jsonDict["user_id"] = userID.json } jsonDict["session_id"] = sessionIDGetter().json jsonDict["device_id"] = deviceIDGetter().json return jsonDict } /// Upload the new json and any data that failed to upload previously to Firehose /// - Parameters: /// - json: new json to upload /// - completion: Block containing the work to perform after the upload finishes /// Note: this is called from the firehoseQueue only private func putRecord(json: JSONObject, completion: ((Error?) -> Void)?) { guard let data = try? json.json?.serialize() else { return } let dataToSend = generateDataArray(newData: data) guard let batchInput = generateBatchInput(data: dataToSend, streamName: streamName) else { return } let firehose = AWSFirehose.default() let task = firehose.putRecordBatch(batchInput) let taskId = self.addInProcessData(dataToSend) task.continueWith { (task) -> Any? in if let failedCount = task.result?.failedPutCount?.intValue, failedCount > 0 { self.handlePartialFailed(dataToSend: dataToSend, firehoseResponses: task.result?.requestResponses) completion?(AnalyticsError.partialFailed) } else if let error = task.error { self.handleUploadFailed(data: dataToSend) completion?(AnalyticsError.uploadFailed(error)) } else { completion?(nil) } self.removeInProcessData(for: taskId) return nil } } /// Generate data array with the new data and any data that failed to upload previously /// - Parameter newData: newData to send to firehose /// - Returns: data array private func generateDataArray(newData: Data) -> [Data] { let newData = newData + "\n" guard var queue = dataQueue else { return [newData] } if queue.count < Self.MaxBatchCount { let dataToSend = queue + [newData] // Clear the data queue dataQueue = nil return dataToSend } else { // Send only the first batch of records let dataToSend = Array<Data>(queue[0..<Self.MaxBatchCount]) // Remove the first batch of records from the data queue and append the new data queue.removeFirst(Self.MaxBatchCount) queue.append(newData) dataQueue = queue return dataToSend } } /// Create AWSFirehosePutRecordBatchInput with given data array and stream name /// - Parameters: /// - data: data to upload /// - streamName: firehose stream name /// - Returns: AWSFirehosePutRecordBatchInput private func generateBatchInput(data: [Data], streamName: String) -> AWSFirehosePutRecordBatchInput? { guard let input = AWSFirehosePutRecordBatchInput() else { return nil } let records: [AWSFirehoseRecord] = data.compactMap { (data) in guard let record = AWSFirehoseRecord() else { return nil } record.data = data return record } input.records = records input.deliveryStreamName = streamName return input } /// AWS Firehose partial failure handler. Save failed upload data to storage /// - Parameters: /// - dataToSend: Data array that is uploaded in a batch /// - firehoseResponses: Array of AWSFirehosePutRecordBatchResponseEntry from the upload result private func handlePartialFailed(dataToSend: [Data], firehoseResponses: [AWSFirehosePutRecordBatchResponseEntry]?) { guard let responses = firehoseResponses else { assert(false, "firehoseResponses shouldn't be nil according to the documentation") return } assert(dataToSend.count == responses.count, "Both arrays should be same size according to the documentation") var failedData = [Data]() var firstErrorCode: String? var firstErrorMessage: String? for index in 0..<responses.count { guard let response = responses[safe: index] else { continue } if response.errorCode != nil || response.errorMessage != nil { if firstErrorCode == nil { firstErrorCode = response.errorCode } if firstErrorMessage == nil { firstErrorMessage = response.errorMessage } failedData.append(dataToSend[index]) } } handleUploadFailed(data: failedData) } /// AWS Firehose upload failure handler. Save the failed input data to storage /// - Parameter data: data that failed to be uploaded /// Called when a task completes with a failure, or partial failure private func handleUploadFailed(data: [Data]) { firehoseQueue.async { // Store the failed input to data queue var dataQueue = self.dataQueue ?? [] dataQueue.append(contentsOf: data) self.dataQueue = dataQueue } } /// Returns the key for the stored in-process data /// Called from `putRecord` on the firehoseQueue private func addInProcessData(_ data: [Data]) -> Int64 { let taskId = currentTaskId currentTaskId += 1 inProcessDataQueue[taskId] = data return taskId } /// Called whenever a task completes, to clear the in process data private func removeInProcessData(for taskId: Int64) { firehoseQueue.async { self.inProcessDataQueue[taskId] = nil } } } public struct DebugLogAnalytics: AnalyticsProtocol { public init() {} public func log(event: AnalyticsEvent) { DebugLog.log("ANALYTICS: \(String(describing: event.jsonDictionary))") } public func log(event: AnalyticsEvent, completion: ((Error?) -> ())?) { log(event: event) completion?(nil) } public func log(eventName: String, message: String, metadata: [String: Any]?, isUnauthorized: Bool) { DebugLog.log("ANALYTICS log:") DebugLog.log("\teventName: \(eventName)") DebugLog.log("\tmessage: \(message)") if let metadata = metadata { DebugLog.log("\tmetadata: \(metadata)") } } public func log(eventName: String, message: String, metadata: [String: Any]?, isUnauthorized: Bool, completion: ((Error?) -> ())?) { log(eventName: eventName, message: message, metadata: metadata, isUnauthorized: isUnauthorized) completion?(nil) } }
35.996491
136
0.619749
d7b21c6cc2986122dbe559ac8b69f7fdcc4704ff
5,853
#if os(macOS) import XCTest import EasyImagy import CoreGraphics import AppKit class ImageAppKitTests: XCTestCase { func testInitWithNSImage() { do { let nsImage = NSImage(contentsOf: URL(fileURLWithPath: (#file as NSString).deletingLastPathComponent).appendingPathComponent("Test2x2.png"))! let image = Image<RGBA<UInt8>>(nsImage: nsImage) XCTAssertEqual(image.width, 2) XCTAssertEqual(image.height, 2) XCTAssertEqual(255, image[0, 0].red) XCTAssertEqual( 0, image[0, 0].green) XCTAssertEqual( 0, image[0, 0].blue) XCTAssertEqual( 64, image[0, 0].alpha) XCTAssertEqual( 0, image[1, 0].red) XCTAssertEqual(255, image[1, 0].green) XCTAssertEqual( 0, image[1, 0].blue) XCTAssertEqual(127, image[1, 0].alpha) XCTAssertEqual( 0, image[0, 1].red) XCTAssertEqual( 0, image[0, 1].green) XCTAssertEqual(255, image[0, 1].blue) XCTAssertEqual(191, image[0, 1].alpha) XCTAssertEqual(255, image[1, 1].red) XCTAssertEqual(255, image[1, 1].green) XCTAssertEqual( 0, image[1, 1].blue) XCTAssertEqual(255, image[1, 1].alpha) } do { // With `NSImage` whose `cgImage` is `nil` let nsImage = NSImage() let image = Image<RGBA<UInt8>>(nsImage: nsImage) XCTAssertEqual(image.width, 0) XCTAssertEqual(image.height, 0) } } func testNsImage() { do { let image = Image<RGBA<UInt8>>(width: 2, height: 2, pixels: [ RGBA<UInt8>(red: 0, green: 1, blue: 2, alpha: 255), RGBA<UInt8>(red: 253, green: 254, blue: 255, alpha: 255), RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 102), RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 51), ]) let nsImage = image.nsImage XCTAssertEqual(nsImage.size.width, CGFloat(image.width)) XCTAssertEqual(nsImage.size.height, CGFloat(image.height)) let restored = Image<RGBA<UInt8>>(nsImage: nsImage) XCTAssertEqual(restored.width, image.width) XCTAssertEqual(restored.height, image.height) XCTAssertEqual(restored[0, 0], image[0, 0]) XCTAssertEqual(restored[1, 0], image[1, 0]) XCTAssertEqual(restored[0, 1], image[0, 1]) XCTAssertEqual(restored[1, 1], image[1, 1]) } do { let image = Image<UInt8>(width: 2, height: 2, pixels: [0, 1, 127, 255]) let nsImage = image.nsImage XCTAssertEqual(nsImage.size.width, CGFloat(image.width)) XCTAssertEqual(nsImage.size.height, CGFloat(image.height)) let restored = Image<UInt8>(nsImage: nsImage) XCTAssertEqual(restored.width, image.width) XCTAssertEqual(restored.height, image.height) XCTAssertEqual(restored[0, 0], image[0, 0]) XCTAssertEqual(restored[1, 0], image[1, 0]) XCTAssertEqual(restored[0, 1], image[0, 1]) XCTAssertEqual(restored[1, 1], image[1, 1]) } } func testNsImageTiffRepresentation() { do { let image = Image<RGBA<UInt8>>(width: 2, height: 2, pixels: [ RGBA<UInt8>(red: 0, green: 1, blue: 2, alpha: 255), RGBA<UInt8>(red: 253, green: 254, blue: 255, alpha: 255), RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 102), RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 51), ]) let nsImage = image.nsImage let data = nsImage.tiffRepresentation! let nsRestored = NSImage(data: data)! XCTAssertEqual(nsRestored.size.width, CGFloat(image.width)) XCTAssertEqual(nsRestored.size.height, CGFloat(image.height)) let restored = Image<RGBA<UInt8>>(nsImage: nsRestored) XCTAssertEqual(restored.width, image.width) XCTAssertEqual(restored.height, image.height) XCTAssertEqual(restored[0, 0], image[0, 0]) XCTAssertEqual(restored[1, 0], image[1, 0]) XCTAssertEqual(restored[0, 1], image[0, 1]) XCTAssertEqual(restored[1, 1], image[1, 1]) } do { let image = Image<UInt8>(width: 2, height: 2, pixels: [0, 1, 127, 255]) let nsImage = image.nsImage let data = nsImage.tiffRepresentation! let nsRestored = NSImage(data: data)! XCTAssertEqual(nsRestored.size.width, CGFloat(image.width)) XCTAssertEqual(nsRestored.size.height, CGFloat(image.height)) let restored = Image<UInt8>(nsImage: nsRestored) XCTAssertEqual(restored.width, image.width) XCTAssertEqual(restored.height, image.height) XCTAssertEqual(restored[0, 0], image[0, 0]) XCTAssertEqual(restored[1, 0], image[1, 0]) XCTAssertEqual(restored[0, 1], image[0, 1]) XCTAssertEqual(restored[1, 1], image[1, 1]) } } } #endif
46.086614
157
0.506578
69c81c75303943cbc1aa8a1b8f55e18bb3bbfa09
2,054
// // AppDelegate.swift // Happiness // // Created by Richard E Millet on 2/16/15. // Copyright (c) 2015 remillet. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
43.702128
279
0.787731
22950ada8437b7416a64c9e18f83cbea31edd5ac
1,117
// // IconTVC.swift // otpio // // Created by Mason Phillips on 12/3/18. // Copyright © 2018 Matrix Studios. All rights reserved. // import UIKit import Eureka import libfa class IconDisplayTVC: UITableViewCell { var iconLabel: SystemLabel? var nameLabel: SystemLabel? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { iconLabel = SystemLabel(withFA: .brands, textPosition: .left, size: 20) nameLabel = SystemLabel(.right, size: 16) super.init(style: style, reuseIdentifier: reuseIdentifier) iconLabel?.textColor = .flatBlack nameLabel?.textColor = .flatBlack addSubview(iconLabel!) addSubview(nameLabel!) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() iconLabel?.anchorAndFillEdge(.left, xPad: 15, yPad: 5, otherSize: 30) nameLabel?.anchorAndFillEdge(.right, xPad: 15, yPad: 5, otherSize: nameLabel?.intrinsicContentSize.width ?? 150) } }
27.925
120
0.653536
d70fe540daf1ef732e602756fc9632bbe47edf95
756
// // GitHubRequest.swift // GitHubClientTestSample // // Created by 鈴木大貴 on 2018/09/06. // Copyright © 2018年 marty-suzuki. All rights reserved. // import Foundation protocol GitHubRequest { associatedtype Response: Decodable var baseURL: URL { get } var method: HttpMethod { get } var path: String { get } var headerFields: [String: String] { get } var queryParameters: [String: String]? { get } } extension GitHubRequest { var baseURL: URL { return URL(string: "https://api.github.com")! } var headerFields: [String: String] { return ["Accept": "application/json"] } var queryParameters: [String: String]? { return nil } } enum HttpMethod: String { case get = "GET" }
20.432432
56
0.634921
3985c47fe097e0b241395b480a4b32643d43f1f9
1,841
// // SearchEngineViewController.swift // UITabBrowser // // Created by ogaoga on 2021/02/15. // import Combine import UIKit class SearchEngineViewController: UITableViewController { // MARK: - Private properties private let viewModel = SettingsViewModel.shared private var cancellables: Set<AnyCancellable> = [] override func viewDidLoad() { super.viewDidLoad() viewModel.$searchEngine .receive(on: DispatchQueue.main) .sink { _ in self.tableView.reloadData() } .store(in: &cancellables) } deinit { cancellables.forEach { $0.cancel() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return SearchEngine.allCases.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SearchEngineCell", for: indexPath) let engine = SearchEngine.allCases[indexPath.row] cell.textLabel?.text = engine.title cell.detailTextLabel?.text = engine.urlPrefix cell.accessoryType = engine == viewModel.searchEngine ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { viewModel.setSearchEngine(SearchEngine.allCases[indexPath.row]) /* // If you want to go back to parent automatically DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.navigationController?.popViewController(animated: true) } */ } }
27.893939
100
0.652906
9c4ac3b5b1da40fbe72336cb2cf5887ecb0b3092
360
// // EndPointType.swift // MithranSwiftKit // // Created by MithranN on 29/03/20. // Copyright © 2020 MithranN. All rights reserved. // import Foundation public protocol EndPointType { var baseURL: URL { get } var path: String { get } var httpMethod: HTTPMethod { get } var task: HTTPTask { get } var headers: HTTPHeaders? { get } }
20
51
0.658333
6a2c753226f139170e9d11d002e1c0c609a3d2e4
7,518
import Foundation import XCTest import OHHTTPStubs import CoreLocation @testable import MapboxStatic #if os(OSX) typealias Color = NSColor #else typealias Color = UIColor #endif class ClassicOverlayTests: XCTestCase { override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } func testBuiltinMarker() { let markerOverlay = Marker( coordinate: CLLocationCoordinate2D(latitude: 45.52, longitude: -122.681944), size: .medium, iconName: "cafe") markerOverlay.color = .brown let options = ClassicSnapshotOptions( mapIdentifiers: ["mapbox.streets"], size: CGSize(width: 200, height: 200)) options.overlays = [markerOverlay] options.scale = 1 let hexColor: String #if os(macOS) hexColor = "865226" #else hexColor = "996633" #endif stub(condition: isHost("api.mapbox.com") && isPath("/v4/mapbox.streets/pin-m-cafe+\(hexColor)(-122.681944,45.52)/auto/200x200.png") && containsQueryParams(["access_token": BogusToken])) { request in let path = Bundle(for: type(of: self)).path(forResource: "marker", ofType: "png")! return fixture(filePath: path, headers: ["Content-Type": "image/png"]) } XCTAssertNotNil(Snapshot(options: options, accessToken: BogusToken).image) } func testCustomMarker() { let coordinate = CLLocationCoordinate2D(latitude: 45.522, longitude: -122.69) let markerURL = URL(string: "https://www.mapbox.com/help/img/screenshots/rocket.png")! let customMarker = CustomMarker(coordinate: coordinate, url: markerURL) let options = ClassicSnapshotOptions( mapIdentifiers: ["mapbox.streets"], size: CGSize(width: 200, height: 200)) options.overlays = [customMarker] options.scale = 1 stub(condition: isHost("api.mapbox.com") && isPath("/v4/mapbox.streets/url-\(markerURL)(-122.69,45.522)/auto/200x200.png") && containsQueryParams(["access_token": BogusToken])) { request in let path = Bundle(for: type(of: self)).path(forResource: "rocket", ofType: "png")! return fixture(filePath: path, headers: ["Content-Type": "image/png"]) } XCTAssertNotNil(Snapshot(options: options, accessToken: BogusToken).image) } func testGeoJSONString() { let geoJSONURL = Bundle(for: type(of: self)).url(forResource: "polyline", withExtension: "geojson")! let geoJSONString = try! String(contentsOf: geoJSONURL, encoding: .utf8) let geoJSONOverlay = GeoJSON(objectString: geoJSONString) let options = ClassicSnapshotOptions( mapIdentifiers: ["mapbox.streets"], size: CGSize(width: 200, height: 200)) options.overlays = [geoJSONOverlay] options.scale = 1 stub(condition: isHost("api.mapbox.com") && isPath("/v4/mapbox.streets/geojson(\(geoJSONString))/auto/200x200.png") && containsQueryParams(["access_token": BogusToken])) { request in let path = Bundle(for: type(of: self)).path(forResource: "geojson", ofType: "png")! return fixture(filePath: path, headers: ["Content-Type": "image/png"]) } XCTAssertNotNil(Snapshot(options: options, accessToken: BogusToken).image) } func testGeoJSONObject() { let geoJSONURL = Bundle(for: type(of: self)).url(forResource: "polyline", withExtension: "geojson")! let data = try! Data(contentsOf: geoJSONURL) let geoJSON = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let geoJSONOverlay = try! GeoJSON(object: geoJSON) let options = ClassicSnapshotOptions( mapIdentifiers: ["mapbox.streets"], size: CGSize(width: 200, height: 200)) options.overlays = [geoJSONOverlay] options.scale = 1 let geoJSONString = "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"properties\":{\"stroke-width\":3,\"stroke-opacity\":1,\"stroke\":\"#00f\"},\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[-122.69784450531006,45.518631758035312],[-122.69091367721559,45.521653692489771],[-122.68630027770996,45.518917420477024],[-122.68509864807127,45.51631633525551],[-122.68233060836793,45.519503775682161]]}}]}" stub(condition: isHost("api.mapbox.com") && isPath("/v4/mapbox.streets/geojson(\(geoJSONString.sortedJSON))/auto/200x200.png") && containsQueryParams(["access_token": BogusToken])) { request in let path = Bundle(for: type(of: self)).path(forResource: "geojson", ofType: "png")! return fixture(filePath: path, headers: ["Content-Type": "image/png"]) } XCTAssertNotNil(Snapshot(options: options, accessToken: BogusToken).image) } func testPath() { let path = Path( coordinates: [ CLLocationCoordinate2D( latitude: 45.52475063103141, longitude: -122.68209457397461 ), CLLocationCoordinate2D( latitude: 45.52451009822193, longitude: -122.67488479614258 ), CLLocationCoordinate2D( latitude: 45.51681250530043, longitude: -122.67608642578126 ), CLLocationCoordinate2D( latitude: 45.51693278828882, longitude: -122.68999099731445 ), CLLocationCoordinate2D( latitude: 45.520300607576864, longitude: -122.68964767456055 ), CLLocationCoordinate2D( latitude: 45.52475063103141, longitude: -122.68209457397461 ) ]) path.strokeWidth = 2 path.strokeColor = Color.black.withAlphaComponent(0.75) path.fillColor = Color.red.withAlphaComponent(0.25) let options = ClassicSnapshotOptions( mapIdentifiers: ["mapbox.streets"], size: CGSize(width: 200, height: 200)) options.overlays = [path] options.scale = 1 let hexColor: String #if os(macOS) hexColor = "fb0006" #else hexColor = "ff0000" #endif let encodedPolyline = "upztG`jxkVn@al@bo@pFWzuAaTcAyZgn@" stub(condition: isHost("api.mapbox.com") && isPath("/v4/mapbox.streets/path-2+000000-0.75+\(hexColor)-0.25(\(encodedPolyline))/auto/200x200.png") && containsQueryParams(["access_token": BogusToken])) { request in let path = Bundle(for: type(of: self)).path(forResource: "path", ofType: "png")! return fixture(filePath: path, headers: ["Content-Type": "image/png"]) } XCTAssertNotNil(Snapshot(options: options, accessToken: BogusToken).image) } } extension String { var sortedJSON: String { let json = try! JSONSerialization.jsonObject(with: self.data(using: .utf8)!, options: []) let data = try! JSONSerialization.data(withJSONObject: json, options: .sortedIfAvailable) return String(data: data, encoding: .utf8)! } }
42.715909
438
0.59577
1a5dbfffd0f1a54feb3fad56ff5d179f68909735
1,770
// // HPTabBarItemMoreContentView.swift // HPTabBarItemMoreContentView // // Created by PangJunJie on 2018/9/13. // import UIKit open class HPTabBarItemMoreContentView: HPTabBarItemContentView { public override init(frame: CGRect) { super.init(frame: frame) self.title = NSLocalizedString("More_TabBarItem", bundle: Bundle(for:HPTabBarController.self), comment: "") self.image = systemMore(highlighted: false) self.selectedImage = systemMore(highlighted: true) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func systemMore(highlighted isHighlighted: Bool) -> UIImage? { let image = UIImage.init() let circleDiameter = isHighlighted ? 5.0 : 4.0 let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 32, height: 32), false, scale) if let context = UIGraphicsGetCurrentContext() { context.setLineWidth(1.0) for index in 0...2 { let tmpRect = CGRect.init(x: 5.0 + 9.0 * Double(index), y: 14.0, width: circleDiameter, height: circleDiameter) context.addEllipse(in: tmpRect) image.draw(in: tmpRect) } if isHighlighted { context.setFillColor(UIColor.blue.cgColor) context.fillPath() } else { context.strokePath() } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } return nil } }
18.631579
127
0.584181
14d457eca3a0b1feebe6ab6acae6530cd9ad938c
166
import Foundation enum OriginTypeEnum: String, Codable { case account = "account" case none = "none" case reward = "reward" case typeSelf = "self" }
18.444444
38
0.656627
484ca7fa94db90610e6a609f978e22d939fb1b56
4,358
import UIKit import BackgroundTasks import Firebase import FirebaseMessaging import Swinject import Service @main class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: Container static var continer: Container { let continer = Container() continer.registerDependencies() return continer } // MARK: Application Lifecycle func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { FirebaseApp.configure() self.setFCM(application) self.registerBackgroundTasks() return true } func applicationWillTerminate(_ application: UIApplication) { pushTerminateNotification() } // MARK: UISceneSession Lifecycle func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions ) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application( _ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession> ) { } } // MARK: - Push Notification extension AppDelegate: UNUserNotificationCenterDelegate { private func setFCM(_ application: UIApplication) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) application.registerForRemoteNotifications() } func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { Messaging.messaging().apnsToken = deviceToken } func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { if #available(iOS 14.0, *) { completionHandler([.badge, .sound, .list, .banner]) } else { completionHandler([.alert, .badge, .sound]) } } func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { completionHandler() } private func pushTerminateNotification() { let push = UNMutableNotificationContent() push.title = "종료 알림" push.body = "백그라운드에서 앱을 종료하시면 기록이 랭킹에 반영되지 않습니다." let request = UNNotificationRequest(identifier: "TerminateNotification", content: push, trigger: nil) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } } // MARK: - Background Task extension AppDelegate { private func registerBackgroundTasks() { BGTaskScheduler.shared.register( forTaskWithIdentifier: "com.walkhub.Walkhub.synchronizeExerciseRecord", using: nil ) { self.synchronizeDailyExerciseRecord(task: ($0 as? BGProcessingTask)!) } } private func synchronizeDailyExerciseRecord(task: BGProcessingTask) { Self.scheduleSynchronizeDailyExerciseRecordIfNeeded() let synchronizeDailyExerciseRecordUseCase = Self.continer .resolve(SynchronizeDailyExerciseRecordUseCase.self)! let disposable = synchronizeDailyExerciseRecordUseCase.excute() .subscribe(onCompleted: { task.setTaskCompleted(success: true) }, onError: { _ in task.setTaskCompleted(success: false) }) task.expirationHandler = { disposable.dispose() } } static func scheduleSynchronizeDailyExerciseRecordIfNeeded() { let request = BGProcessingTaskRequest(identifier: "com.walkhub.Walkhub.synchronizeExerciseRecord") request.requiresNetworkConnectivity = true request.earliestBeginDate = Date(timeIntervalSinceNow: 3600) try? BGTaskScheduler.shared.submit(request) } }
30.475524
109
0.684029
e472feaed15b1e0e28a930f0ad826ed1d7bbe3d6
1,625
// // FirstViewController.swift // ZQFirstComponent // // Created by 周强 on 2018/7/4. // Copyright © 2018年 周强. All rights reserved. // import UIKit class FirstViewController: UIViewController { var titleString: String? override func viewDidLoad() { super.viewDidLoad() title = titleString view.backgroundColor = UIColor.gray let presentBtn = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 30)) presentBtn.setTitleColor(UIColor.white, for: .normal) presentBtn.setTitle("present vc", for: .normal) presentBtn.addTarget(self, action: #selector(presentBtnClick), for: .touchUpInside) view.addSubview(presentBtn) } @objc fileprivate func presentBtnClick() { guard let routeUrl = "ZQRouteOne://present/ZQSecondComponent.OrangeViewController".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} guard let url = URL(string: routeUrl) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.5
167
0.670769
9b2a170256c35f1d333ea0cc0ffa824efcfe2124
1,215
// // SwiftyLibTests.swift // SwiftyLibTests // // Created by Mac2 on 30/12/21. // import XCTest @testable import SwiftyLib class SwiftyLibTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
32.837838
130
0.683128
cca5c5b92c344619127d865c1d598211976c5b1a
775
import Foundation import XCTest @testable import TuistGraph @testable import TuistSupportTesting final class ProfileActionTests: TuistUnitTestCase { func test_codable() { // Given let subject = ProfileAction( configurationName: "name", executable: .init( projectPath: "/path/to/project", name: "name" ), arguments: .init( environment: [ "key": "value", ], launchArguments: [ .init( name: "name", isEnabled: false ), ] ) ) // Then XCTAssertCodable(subject) } }
23.484848
51
0.44
4a2bb9f62aecdf3f866a670d8f9d8fb4bab839f3
2,745
/* Copyright 2020 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /// NetworkRequest struct to be used by the NetworkService and the HttpConnectionPerformer when initiating network calls @objc(AEPNetworkRequest) public class NetworkRequest: NSObject { private static let REQUEST_HEADER_KEY_USER_AGENT = "User-Agent" private static let REQUEST_HEADER_KEY_LANGUAGE = "Accept-Language" public let url: URL public let httpMethod: HttpMethod public let connectPayload: String public let httpHeaders: [String: String] public let connectTimeout: TimeInterval public let readTimeout: TimeInterval /// Initialize the `NetworkRequest` /// - Parameters: /// - url: URL used to initiate the network connection, should use https scheme /// - httpMethod: `HttpMethod` to be used for this network request; the default value is GET /// - connectPayload: the body of the network request as a String; this parameter is ignored for GET requests /// - httpHeaders: optional HTTP headers for the request /// - connectTimeout: optional connect timeout value in seconds; default is 5 seconds /// - readTimeout: optional read timeout value in seconds, used to wait for a read to finish after a successful connect, default is 5 seconds /// - Returns: an initialized `NetworkRequest` object public init(url: URL, httpMethod: HttpMethod = HttpMethod.get, connectPayload: String = "", httpHeaders: [String: String] = [:], connectTimeout: TimeInterval = 5, readTimeout: TimeInterval = 5) { self.url = url self.httpMethod = httpMethod self.connectPayload = connectPayload let systemInfoService = ServiceProvider.shared.systemInfoService let defaultHeaders = [NetworkRequest.REQUEST_HEADER_KEY_USER_AGENT: systemInfoService.getDefaultUserAgent(), NetworkRequest.REQUEST_HEADER_KEY_LANGUAGE: systemInfoService.getActiveLocaleName()] self.httpHeaders = defaultHeaders.merging(httpHeaders) { _, new in new } // add in default headers and apply `httpHeaders` on top self.connectTimeout = connectTimeout self.readTimeout = readTimeout } }
54.9
199
0.740984
e88146ca624dba06a9aa5b4aa63a299acf1a8ac8
2,749
// // BaseTableViewController.swift // TongueTwister.Swift // // Created by Assassin on 25/5/20. // Copyright © 2020 Dan Gerchcovich. All rights reserved. // import Foundation import UIKit; import SVProgressHUD; internal class BaseTableViewController : UITableViewController { var _navigationBar : CustomNavigationBar?; public override func viewDidLoad() { super.viewDidLoad(); self.view.backgroundColor = UIColor.lightGray; self.isMotionEnabled = true; self.view.backgroundColor = UIColor.white; self.view.addGestureRecognizer(UISwipeGestureRecognizer.init(target: self, action: #selector(PopPage))); SetupUIComponents(); SetupNavigationBar(); } // func gotSilentStatus(isSilent: Bool) { // if(isSilent){ // ToasterHelper.OpenSimpleToastIndefinetly(self, "Your phone is on silent. Please turn off silent mode in order to hear the phrases"); // } // else { // ToasterHelper.HideAllToasts(self); // } // } fileprivate func SetupUIComponents(){ let masterRefreshMngr = UIRefreshControl.init(); masterRefreshMngr.addTarget(self, action: #selector(RefreshItems), for: UIControl.Event.valueChanged); self.tableView!.isMotionEnabled = true; self.tableView!.allowsSelectionDuringEditing = true; self.tableView!.rowHeight = 90; self.tableView!.refreshControl = masterRefreshMngr; } @objc fileprivate func PopPage(){ self.navigationController?.popViewController(animated: true); } public override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { PopPage(); } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if(self._navigationBar != nil){ self._navigationBar!.frame = CGRect.init(x: 0, y: 0, width: size.width, height: 70); } } //Configure the Base Components fileprivate func SetupNavigationBar(){ self.navigationController!.setNavigationBarHidden(true, animated: false); self._navigationBar = NavigationBarHelper.DrawNavigationBarWithBack(); self._navigationBar!.frame = CGRect(x: 0,y: 0, width: self.navigationController!.navigationBar.bounds.width, height: 70); self._navigationBar!.LeftBarButton.addTarget(self, action: #selector(PopPage), for: UIControl.Event.touchDown); self.view!.addSubview(self._navigationBar!); } @objc internal func RefreshItems() { LoaderHelper.ShowLoaderWithMessage("Synchronising"); } }
35.24359
150
0.659876
d61afeb525b61e439d81420e7be54fb3b59d0278
1,892
// // ViewController.swift // Example // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import FolioReaderKit class ViewController: UIViewController { @IBOutlet var bookOne: UIButton! @IBOutlet var bookTwo: UIButton! let epubSampleFiles = [ "The Silver Chair", // standard eBook "The Adventures Of Sherlock Holmes - Adventure I", // audio-eBook ] override func viewDidLoad() { super.viewDidLoad() setCover(bookOne, index: 0) setCover(bookTwo, index: 1) } @IBAction func didOpen(sender: AnyObject) { openEpub(sender.tag); } func openEpub(sampleNum:Int) { let config = FolioReaderConfig() config.shouldHideNavigationOnTap = sampleNum == 1 ? true : false // See more at FolioReaderConfig.swift // config.enableTTS = false // config.allowSharing = false // config.tintColor = UIColor.blueColor() // config.toolBarTintColor = UIColor.redColor() // config.toolBarBackgroundColor = UIColor.purpleColor() // config.menuTextColor = UIColor.brownColor() // config.menuBackgroundColor = UIColor.lightGrayColor() let epubName = epubSampleFiles[sampleNum-1]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") FolioReader.presentReader(parentViewController: self, withEpubPath: bookPath!, andConfig: config, shouldRemoveEpub: false) } func setCover(button: UIButton, index: Int) { let epubName = epubSampleFiles[index]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") if let image = FolioReader.getCoverImage(bookPath!) { button.setBackgroundImage(image, forState: .Normal) } } }
31.533333
130
0.64852
29519e73b87704d6745b41ae231499a7df8552fd
468
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck {protocol P{ typealias e protocol c{{}let t:e enum B:c{ typealias e:e
33.428571
79
0.75
507248706f67697adeec9e0f1b7b3aa196804937
977
// // UIBundle+Extension.swift // ZappCore // // Created by Anton Kononenko on 16/08/2021. // import UIKit extension Bundle { public static let externalURLSchemes: [String] = { guard let urlTypes = main.infoDictionary?["CFBundleURLTypes"] as? [[String: Any]] else { return [] } var result: [String] = [] for urlTypeDictionary in urlTypes { guard let urlSchemes = urlTypeDictionary["CFBundleURLSchemes"] as? [String] else { continue } guard let externalURLScheme = urlSchemes.first else { continue } result.append(externalURLScheme) } return result }() public static var stringifyExternalURLSchemes: String? { let urlSchemes = externalURLSchemes guard let data = try? JSONSerialization.data(withJSONObject: urlSchemes, options: []) else { return nil } return String(data: data, encoding: String.Encoding.utf8) } }
28.735294
105
0.629478
21b7041017d267c43461a8380319acbfae0fbc41
7,938
// // CheckoutPreference.swift // MercadoPagoSDK // // Created by Maria cristina rodriguez on 12/1/16. // Copyright © 2016 MercadoPago. All rights reserved. // import UIKit open class CheckoutPreference: NSObject { open var _id: String! open var items: [Item]! open var payer: Payer! open var paymentPreference: PaymentPreference! open var siteId: String = "MLA" open var expirationDateFrom: Date? open var expirationDateTo: Date? public init(_id: String) { self._id = _id } public init(items: [Item] = [], payer: Payer = Payer(), paymentMethods: PaymentPreference? = nil) { self.items = items self.payer = payer self.paymentPreference = paymentMethods ?? PaymentPreference() } public func addItem(item: Item) { items.append(item) } public func addItems(items: [Item]) { self.items.append(contentsOf: items) } public func addExcludedPaymentMethod(_ paymentMethodId: String) { if self.paymentPreference.excludedPaymentMethodIds != nil { self.paymentPreference.excludedPaymentMethodIds?.insert(paymentMethodId) } else { self.paymentPreference.excludedPaymentMethodIds = [paymentMethodId] } } public func setExcludedPaymentMethods(_ paymentMethodIds: Set<String>) { self.paymentPreference.excludedPaymentMethodIds = paymentMethodIds } public func addExcludedPaymentType(_ paymentTypeId: String) { if self.paymentPreference.excludedPaymentTypeIds != nil { self.paymentPreference.excludedPaymentTypeIds?.insert(paymentTypeId) } else { self.paymentPreference.excludedPaymentTypeIds = [paymentTypeId] } } public func setExcludedPaymentTypes(_ paymentTypeIds: Set<String>) { self.paymentPreference.excludedPaymentTypeIds = paymentTypeIds } public func setMaxInstallments(_ maxInstallments: Int) { self.paymentPreference.maxAcceptedInstallments = maxInstallments } public func setDefaultInstallments(_ defaultInstallments: Int) { self.paymentPreference.defaultInstallments = defaultInstallments } public func setDefaultPaymentMethodId(_ paymetMethodId: String) { self.paymentPreference.defaultPaymentMethodId = paymetMethodId } public func setPayerEmail(_ payerEmail: String) { self.payer.email = payerEmail } public func setSite(siteId: String) { self.siteId = siteId } public func setExpirationDate(_ expirationDate: Date) { self.expirationDateTo = expirationDate } public func setActiveFromDate(_ date: Date) { self.expirationDateFrom = date } public func setId(_ id: String) { self._id = id } public func getId() -> String { return self._id } public func getItems() -> [Item]? { return items } public func getPayer() -> Payer { return payer } public func getSiteId() -> String { return self.siteId } public func getExpirationDate() -> Date? { return expirationDateTo } public func getActiveFromDate() -> Date? { return expirationDateFrom } open func getExcludedPaymentTypesIds() -> Set<String>? { return paymentPreference.getExcludedPaymentTypesIds() } open func getDefaultInstallments() -> Int { return paymentPreference.getDefaultInstallments() } open func getMaxAcceptedInstallments() -> Int { return paymentPreference.getMaxAcceptedInstallments() } open func getExcludedPaymentMethodsIds() -> Set<String>? { return paymentPreference.getExcludedPaymentMethodsIds() } open func getDefaultPaymentMethodId() -> String? { return paymentPreference.getDefaultPaymentMethodId() } open func validate() -> String? { if let itemError = itemsValid() { return itemError } if self.payer == nil { return "No hay información de payer".localized } if self.payer.email == nil || self.payer.email?.characters.count == 0 { return "Se requiere email de comprador".localized } if !isActive() { return "La preferencia no esta activa.".localized } if isExpired() { return "La preferencia esta expirada".localized } if self.getAmount() < 0 { return "El monto de la compra no es válido".localized } return nil } open func itemsValid() -> String? { if Array.isNullOrEmpty(items) { return "No hay items".localized } let currencyIdAllItems = items[0].currencyId for (_, value) in items.enumerated() { if value.currencyId != currencyIdAllItems { return "Los items tienen diferente moneda".localized } if let error = value.validate() { return error } } return nil } open func isExpired() -> Bool { let date = Date() if let expirationDateTo = expirationDateTo { return expirationDateTo > date } return false } open func isActive() -> Bool { let date = Date() if let expirationDateFrom = expirationDateFrom { return expirationDateFrom < date } return true } open class func fromJSON(_ json: NSDictionary) -> CheckoutPreference { let preference: CheckoutPreference = CheckoutPreference() if let _id = JSONHandler.attemptParseToString(json["id"]) { preference._id = _id } if let siteId = JSONHandler.attemptParseToString(json["site_id"]) { preference.siteId = siteId } if let payerDic = json["payer"] as? NSDictionary { preference.payer = Payer.fromJSON(payerDic) } var items = [Item]() if let itemsArray = json["items"] as? NSArray { for i in 0..<itemsArray.count { if let itemDic = itemsArray[i] as? NSDictionary { items.append(Item.fromJSON(itemDic)) } } preference.items = items } if let paymentPreference = json["payment_methods"] as? NSDictionary { preference.paymentPreference = PaymentPreference.fromJSON(paymentPreference) } return preference } open func toJSONString() -> String { let _id : Any = self._id == nil ? JSONHandler.null : (self._id)! let player : Any = self.payer == nil ? JSONHandler.null : self.payer.toJSONString() var obj: [String:Any] = [ "id": _id, "payer": player ] var itemsJson = "" for item in items { itemsJson = itemsJson + item.toJSONString() } obj["items"] = itemsJson return JSONHandler.jsonCoding(obj) } open func getAmount() -> Double { var amount = 0.0 for item in self.items { amount = amount + (Double(item.quantity) * item.unitPrice) } return amount } /*open func getTitle() -> String { if self.items.count > 1 { var title = self.items.reduce("", { (result, element) -> String in return element.title + ", " + result }) let index = title.index(title.endIndex, offsetBy: -2) title.remove(at: index) return title } return self.items[0].title }*/ } public func ==(obj1: CheckoutPreference, obj2: CheckoutPreference) -> Bool { let areEqual = obj1._id == obj2._id && obj1.items == obj2.items && obj1.payer == obj2.payer && obj1.paymentPreference == obj2.paymentPreference return areEqual }
28.148936
103
0.604812
2388bf688a8d04cc011a236db0f7a7f2bb005a94
2,089
// // KeyValueObserver.swift // Player // // Created by Fredrik Sjöberg on 2017-04-07. // Copyright © 2017 emp. All rights reserved. // import Foundation /// `KVO` wrapper for convenience access to *key value observation. /// /// For more information regarding *Key Value Observation*, please see Apple's documentation internal protocol KeyValueObserver { /// Observed object type. associatedtype Object: NSObject /// Storage for the *observables* used to track registered `KVO`. var observers: [Observer<Object>] { get set } } extension KeyValueObserver where Object: KeyValueObservable, Object.ObservableKeys: RawRepresentable, Object.ObservableKeys.RawValue == String { /// Registers an *observer* that receives `KVO` notifications for the *key path* relative to `object`. /// /// - parameter path: KeyPath to observe /// - parameter object: Object to observe `path` for /// - parameter options: `NSKeyValueObservingOptions` specifying which value changes to include /// - parameter callback: Executes when the `KVO` change fires. internal mutating func observe(path: Object.ObservableKeys, on object: Object, with options: NSKeyValueObservingOptions = [.new, .old, .initial, .prior], callback: @escaping (Object, KVOChange) -> Void) { let kvo = Observer<Object>(of: object, at: path.rawValue, with: options, callback: callback) observers.append(kvo) } /// Stops `KVO` observation of `path` on `object`. internal func stopObserving(path: Object.ObservableKeys, on object: Object) { observers .filter{ $0.object == object && $0.path == path.rawValue } .forEach{ $0.cancel() } } /// Removes all `KVO` observations, no matter the *path* or *target*. internal mutating func stopObservingAll() { observers.forEach{ $0.cancel() } observers = [] } }
37.981818
144
0.619914
bbdc27d60543b064e0e0cf786911bd66c122f77b
7,749
// // MineViewController.swift // SportBureeau // // Created by sophiemarceau_qu on 2019/4/25. // Copyright © 2019 sophiemarceau_qu. All rights reserved. // import UIKit class MineViewController: UIViewController { fileprivate lazy var sumVM : SumVM = SumVM() private var listView:UITableView! override func viewDidLoad() { super.viewDidLoad() listView = UITableView() listView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - tabBarHeight) listView.backgroundColor = UIColor.white listView.delegate = self listView.dataSource = self view.addSubview(listView) let headImage = UIImage(named: "国家体育局我的页面") let headHeight = CGFloat(SCREEN_WIDTH / ((headImage?.size.width)! / (headImage?.size.height)!)) let headImageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: headHeight)) headImageView.contentMode = .scaleAspectFill headImageView.image = headImage headImageView.isUserInteractionEnabled = true listView.tableHeaderView = headImageView // listView.contentInsetAdjustmentBehavior = .never if #available(iOS 11.0, *) { listView.contentInsetAdjustmentBehavior = .never } else { automaticallyAdjustsScrollViewInsets = false; listView.contentInset = UIEdgeInsets.init(top: -20, left: 0, bottom: 0, right: 0) }; listView.showsVerticalScrollIndicator = false listView.separatorStyle = .none listView.bounces = false let btn = UIButton.init(frame: CGRect.init(x: (SCREEN_WIDTH - SCREEN_WIDTH * 1 / 3), y: 270*SCALEX, width: SCREEN_WIDTH / 3, height: 75*SCALEX )) btn.addTarget(self, action: #selector(self.gotoBusRecordList), for: .touchUpInside) headImageView.addSubview(btn) let qrbtn = UIButton.init(frame: CGRect.init(x: (0), y: 270*SCALEX, width: SCREEN_WIDTH / 3, height: 80*SCALEX )) qrbtn.addTarget(self, action: #selector(self.gotoRecordList), for: .touchUpInside) headImageView.addSubview(qrbtn) let loftBtn = UIButton.init(frame: CGRect.init(x: (SCREEN_WIDTH / 3), y: 270*SCALEX, width: SCREEN_WIDTH / 3, height: 80*SCALEX )) loftBtn.addTarget(self, action: #selector(self.gotoLoftList), for: .touchUpInside) headImageView.addSubview(loftBtn) let cardMangertn = UIButton.init(frame: CGRect.init(x: (0), y: (1132/2)*SCALEX, width: SCREEN_WIDTH, height: 50*SCALEX )) cardMangertn.addTarget(self, action: #selector(self.gotoCardManager), for: .touchUpInside) headImageView.addSubview(cardMangertn) let fixBtn = UIButton.init(frame: CGRect.init(x: (0), y: (1132/2+50)*SCALEX, width: SCREEN_WIDTH, height: 45*SCALEX )) fixBtn.addTarget(self, action: #selector(self.gotoFix), for: .touchUpInside) headImageView.addSubview(fixBtn) let consumerRecordBtn = UIButton.init(frame: CGRect.init(x: (0), y: (1132/2+50+45)*SCALEX, width: SCREEN_WIDTH, height: 45*SCALEX )) consumerRecordBtn.addTarget(self, action: #selector(self.consumerRecordList), for: .touchUpInside) headImageView.addSubview(consumerRecordBtn) var yValue = (1132/2+140) * SCALEX let gooutRecordBtn = UIButton.init(frame: CGRect.init(x: (0), y: yValue, width: SCREEN_WIDTH, height: 45*SCALEX )) gooutRecordBtn.addTarget(self, action: #selector(self.gooutRecordList), for: .touchUpInside) headImageView.addSubview(gooutRecordBtn) headImageView.addSubview(self.nickLbel) headImageView.addSubview(self.balanceLbel) headImageView.addSubview(self.bindBtn) requestData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) requestData() } private lazy var nickLbel:UILabel = { let nickLbel = UILabel.init() nickLbel.textColor = UIColor.white nickLbel.frame = CGRect(x: (188)/2*SCALEX, y: 190/2*SCALEX, width: SCREEN_WIDTH/2, height: 33/2) nickLbel.font = UIFont.systemFont(ofSize: 16*SCALEX) return nickLbel }() private lazy var balanceLbel:UILabel = { let balanceLbel = UILabel.init() balanceLbel.textColor = UIColor(hexString: "#444444")! balanceLbel.frame = CGRect(x: 55*SCALEX, y: 357/2*SCALEX, width: SCREEN_WIDTH/3, height: 30/2) balanceLbel.font = UIFont.systemFont(ofSize: 16*SCALEX) return balanceLbel }() private lazy var bindBtn:UIButton = { let bindBtn = UIButton.init() bindBtn.addTarget(self, action: #selector(self.gotoRecordList), for: .touchUpInside) bindBtn.frame = CGRect(x: SCREEN_WIDTH - 100, y: 196/2*SCALEX, width: 100, height: 44) bindBtn.backgroundColor = UIColor.clear return bindBtn }() @objc func gotoRecordList(){ let openDoorVC = ResturantViewController() // ConsumerListViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func gotoBusRecordList(){ let openDoorVC = ServiceViewController() // BusListViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func gotoLoftList(){ let openDoorVC = LoftServiceViewController() // ConsumerListViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func gotoFix(){ let openDoorVC = QuickFixViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func gotoCardManager(){ let openDoorVC = CardManagerViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func consumerRecordList(){ let openDoorVC = ConsumerListViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } @objc func gooutRecordList(){ let openDoorVC = BusListViewController() self.navigationController?.pushViewController(openDoorVC, animated: true) } func requestData(){ let parameters = ["cardId": User.cardId] sumVM.requestData(parameters: parameters as [String : Any]) { if self.sumVM.codeStr == "200" { print("requestData") self.nickLbel.text = self.sumVM.nickName self.balanceLbel.text = "¥\(self.sumVM.totalBalance!)" let cardId = User.cardId if(cardId == "-1"){ self.bindBtn.backgroundColor = UIColor.clear self.bindBtn.isEnabled = false }else{ self.bindBtn.backgroundColor = UIColor(hexString: "#0092D3")! self.bindBtn.isEnabled = true } } } } } extension MineViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func numberOfSections(in tableView: UITableView) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellid = "testCellID" var cell = tableView.dequeueReusableCell(withIdentifier: cellid) if cell==nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid) } return cell! } }
41.66129
153
0.646277
468926b41f6ad8706ec2e7c7365077736329170d
1,623
// // AppDelegate.swift // TipCalculator // // Created by Ben Scheirman on 6/14/19. // Copyright © 2019 Fickle Bits. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // 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. } }
38.642857
179
0.748614
ffd90e86de1fcebf98172cc93f2c8910610d7612
2,001
// // ShowTypeChooseVCTableViewController.swift // PhotoBrowser // // Created by 冯成林 on 15/8/14. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class ShowTypeChooseTVC: UITableViewController { var langType: LangType! var photoType: PhotoType! let rid = "ShowTypeChooseTVCCell" lazy var dataList: [String] = {["Push","Modal","CancelBtnClickDissmiss","SingleTapDismiss"]}() } extension ShowTypeChooseTVC{ override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: rid) ?? UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: rid) cell.textLabel?.text = dataList[indexPath.row] cell.textLabel?.font = UIFont.systemFont(ofSize: 24) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let displayVC = DisplayVC() displayVC.langType = langType displayVC.photoType = photoType switch indexPath.row { case 0:displayVC.showType = PhotoBrowser.ShowType.push case 1:displayVC.showType = PhotoBrowser.ShowType.modal case 2:displayVC.showType = PhotoBrowser.ShowType.zoomAndDismissWithCancelBtnClick case 3:displayVC.showType = PhotoBrowser.ShowType.zoomAndDismissWithSingleTap default: break } self.navigationController?.pushViewController(displayVC, animated: true) } }
30.318182
147
0.670665
71c405fb09f40a3b14cc1dd012ebbc5f7da00376
2,743
// // MIT License // // Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import SwiftUI import Combine import RadixSDK public final class AppState: ObservableObject { @Published public private(set) var rootContent: RootContent = .welcome private let preferences: Preferences private let securePersistence: SecurePersistence private let _update: Update private var cancellable: Cancellable? init( preferences: Preferences, securePersistence: SecurePersistence ) { self.preferences = preferences self.securePersistence = securePersistence let triggerNavigationSubject = CurrentValueSubject<Void, Never>(()) self._update = Update( preferences: preferences, securePersistence: securePersistence, triggerNavigation: { triggerNavigationSubject.send() } ) cancellable = triggerNavigationSubject.sink { [unowned self] _ in self.goToNextScreen() } } } // MARK: - PRIVATE private extension AppState { func goToNextScreen() { rootContent = nextContent objectWillChange.send() } var nextContent: RootContent { guard preferences.hasAgreedToTermsOfUse else { return .welcome } guard securePersistence.isWalletSetup else { return .getStarted } return .main } } // MARK: - PUBLIC // MARK: Update State public extension AppState { // Syntax sugar enforcing function calling notation `.update()` rather than `.update` to highlight mutating func update() -> Update { _update } }
30.142857
111
0.701422
9b7abd3fe280136e785aceeb1ac01292193cf5aa
1,295
// // SettingsUnitsInteractor.swift // xDrip // // Created by Artem Kalmykov on 09.04.2020. // Copyright (c) 2020 Faifly. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol SettingsUnitsBusinessLogic { func doLoad(request: SettingsUnits.Load.Request) } protocol SettingsUnitsDataStore: AnyObject { } final class SettingsUnitsInteractor: SettingsUnitsBusinessLogic, SettingsUnitsDataStore { var presenter: SettingsUnitsPresentationLogic? var router: SettingsUnitsRoutingLogic? // MARK: Do something func doLoad(request: SettingsUnits.Load.Request) { let user = User.current let response = SettingsUnits.Load.Response(currentSelectedUnit: user.settings.unit) { [weak self] index in self?.handleUnitSelection(index) } presenter?.presentLoad(response: response) } private func handleUnitSelection(_ index: Int) { guard let unit = GlucoseUnit(rawValue: index) else { return } User.current.settings.updateUnit(unit) NotificationCenter.default.postSettingsChangeNotification(setting: .unit) } }
29.431818
114
0.705792
4883024db6898d1b5244a14b82a5b89414ddbcfd
1,332
// // NetworkService.swift // MVP+API // // Created by Ted on 2021/08/10. // import Foundation enum ServiceError: Error { case urlTransformFailed case requestFailed(response: URLResponse, data: Data?) case decodeFailed } class NetworkService { func fetchArticles(completion: @escaping (Result<[ArticleContent], Error>) -> Void) { let baseUrl = "https://newsapi.org/v2/top-headlines?country=us&sortBy=%20popularity&apiKey=33e4f0e56b324ab7a51f2d8e9fef4204" guard let url = URL(string: baseUrl) else { return } let dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let response = response as? HTTPURLResponse, let data = data else { completion(.failure(ServiceError.urlTransformFailed)) return } guard 200..<400 ~= response.statusCode else { completion(.failure(ServiceError.requestFailed(response: response, data: data))) return } do { let articles = try JSONDecoder().decode(Article.self, from: data) completion(.success(articles.articles)) } catch let error { completion(.failure(error)) } } dataTask.resume() } }
30.976744
139
0.59985
229ab391edcfd1c435422ceb05e2126b181b9b08
7,126
@testable import SwiftVer import XCTest class GlobalVersionTests: 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 testGoodBundleVersion() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let bundle = MockBundle(version: "1.2.3", build: 4) let version = Version( bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo ) XCTAssertEqual(version?.semver.major, 1) XCTAssertEqual(version?.semver.minor, 2) XCTAssertEqual(version?.semver.patch, 3) XCTAssertEqual(version?.build, 4) XCTAssertEqual(version?.versionControl?.type, versionControlInfo.type) XCTAssertEqual(version?.versionControl?.baseName, versionControlInfo.baseName) XCTAssertEqual(version?.versionControl?.uuid, versionControlInfo.uuid) XCTAssertEqual(version?.versionControl?.number, versionControlInfo.number) XCTAssertEqual(version?.versionControl?.date, versionControlInfo.date) XCTAssertEqual(version?.versionControl?.branch, versionControlInfo.branch) XCTAssertEqual(version?.versionControl?.tag, versionControlInfo.tag) XCTAssertEqual(version?.versionControl?.tick, versionControlInfo.tick) XCTAssertEqual(version?.versionControl?.extra, versionControlInfo.extra) XCTAssertEqual(version?.versionControl?.hash, versionControlInfo.hash) XCTAssertEqual(version?.versionControl?.isWorkingCopyModified, versionControlInfo.isWorkingCopyModified) } func testMissingBundleVersion() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let bundle = MockBundle(version: nil, build: 4) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertNil(version) } func testMissingInvalidVersion() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let bundle = MockBundle(version: "dfasdfs", build: 4) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertNil(version) } func testMissingBundleBuild() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let bundle = MockBundle(version: "1.2.3", build: nil) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertNil(version) } func testInvalidBundleBuild() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let bundle = MockBundle(version: "1.2.3", build: "asdfdsaf") let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertNil(version) } public func testdescription() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.description, version?.shortDescription) } public func testStageBuildNumber() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.stageBuildNumber, 4) } public func testSemverBuildNumber() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.semverBuildNumber, 9) } public func testStage() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.stage, .beta) } public func testFullDescription() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual((try? version?.fullDescription(withLocale: Locale(identifier: "en_US")))!, "1.1.0.0900250000") XCTAssertEqual((try? version?.fullDescription(withLocale: Locale(identifier: "nl_NL")))!, "1.1.0.0900250000") } public func testSubSemVerValue() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.subSemVerValue, 0.0900250000) } public func testShortDescription() { let bundle = MockBundle(version: "1.1.0", build: 26) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.shortDescription, "1.1.0-beta4") } public func testShortDescriptionProduction() { let bundle = MockBundle(version: "1.1.0", build: 32) let version = Version(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, versionControl: versionControlInfo) XCTAssertEqual(version?.shortDescription, "1.1.0 (0020)") } public func testInitBuildNumber() { let version = Version(cumulativeBuildNumber: 26, dictionary: MockBundle.globalBuildNumberDictionary) XCTAssertEqual(version.shortDescription, "1.1.0-beta4") } public func testFromBundle() { let bundle = MockBundle(version: "1.1.0", build: 32) let version = Version.from(bundle: bundle, dictionary: MockBundle.globalBuildNumberDictionary, withVersionControlInfoWithJsonResource: "versions-global") XCTAssertEqual(version?.shortDescription, "1.1.0 (0020)") } }
40.72
113
0.681448
fb1a2a302690e5b77bccab175b5ceba8686b4e1f
16,023
// // OTPView.swift // ATP // // Created by Binal Shah on 06/09/19. // Copyright © 2019 Hidden Brains. All rights reserved. // import UIKit enum style { case box case line } /// This view is basically made for implementing One Time Password text. class OTPView: UIView { //MARK: - IBOutlets @IBOutlet var contentView: UIView! @IBOutlet weak var collectionVw: UICollectionView! var OTPStyle: style = .box private var isEmpty : Bool = true var pinLength: Int = 4 // Don't change its default value. It must be 4. { didSet{ self.pinLength = min(max(pinLength, 4), 10) self.setPinLength(length: min(pinLength, 10)) } } var textFont: UIFont = UIFont.systemFont(ofSize: 14.0) var textColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) var bgColorActiveText: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var bgColorEmptyText: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) var bgColorFilledText: UIColor = #colorLiteral(red: 0.9606800675, green: 0.9608443379, blue: 0.9606696963, alpha: 1) var bgColorTextField: UIColor = #colorLiteral(red: 0.8078431373, green: 0.8196078431, blue: 0.8352941176, alpha: 1) var textDidChange:(()->())? var OTPIsEntered:(()->())? /// Init with frame override init(frame: CGRect) { super.init(frame: frame) commonInit() } /// Init with coder required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /// Set Pin Lenght between 4 to 10 func setPinLength(length: Int) { self.collectionVw.reloadData() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) { self.setupUI() } } /// Initialize common controls private func commonInit() { Bundle.main.loadNibNamed("OTPView", owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionVw.delegate = self collectionVw.dataSource = self collectionVw.register(UINib(nibName: "OTPCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "OTPCollectionViewCell") } /// AwakeFromNib override func awakeFromNib() { super.awakeFromNib() } /// Setup UI func setupUI() { for i in (0..<pinLength) { if let txtFd = self.viewWithTag(1000+i) as? OTPTextField { self.setupTextField(textField: txtFd) } } self.updateTextFields() if let txtFd = self.viewWithTag(1000) as? OTPTextField { DispatchQueue.main.async { txtFd.becomeFirstResponder() } } } /// textfield setup /// /// - Parameter textField: textfield func setupTextField(textField: OTPTextField) { if self.OTPStyle == .box { textField.layer.cornerRadius = 3.0 textField.layer.masksToBounds = true textField.layer.borderColor = #colorLiteral(red: 0.9293106794, green: 0.929469943, blue: 0.9293007255, alpha: 1) textField.layer.borderWidth = 1 } textField.addTarget(self, action: #selector(textDidChange(textField:)), for: .editingChanged) textField.font = self.textFont textField.textColor = self.textColor textField.backPressed = { DispatchQueue.main.async(execute: { if (textField.text?.isEmpty)!// && !self.isEmpty { self.manageTextFieldResponderOnBackPress(textField: textField) } self.isEmpty = false }) } } /// manage textfield responder /// /// - Parameter textField: textfield func updateTextFields() { for i in (0..<pinLength) { if let txtFd = self.viewWithTag(1000+i) as? OTPTextField { self.checkTextField(txtField: txtFd) } } } /// update textfield colors based on its state /// /// - Parameter textField: textfield func checkTextField(txtField: OTPTextField) { let vwBottomLineTag = 2000+(txtField.tag-1000) if txtField.isFirstResponder { if OTPStyle == .box { txtField.backgroundColor = bgColorActiveText } else { if let vwBottomLine = txtField.superview?.viewWithTag(vwBottomLineTag) { vwBottomLine.backgroundColor = bgColorActiveText txtField.backgroundColor = .clear } } } else { if (txtField.text?.isEmpty)! == true { if OTPStyle == .box { txtField.backgroundColor = bgColorEmptyText } else { if let vwBottomLine = txtField.superview?.viewWithTag(vwBottomLineTag) { vwBottomLine.backgroundColor = bgColorEmptyText txtField.backgroundColor = .clear } } } else { if OTPStyle == .box { txtField.backgroundColor = bgColorFilledText } else { if let vwBottomLine = txtField.superview?.viewWithTag(vwBottomLineTag) { vwBottomLine.backgroundColor = bgColorFilledText txtField.backgroundColor = .clear } } } } } /// Clear Textfieds func clearEnteredOTP() { for i in (0..<pinLength) { if let txtFd = self.viewWithTag(1000+i) as? OTPTextField { txtFd.text = "" } } } /// Get entered OTP func getOTP() -> String { var sOTPCode = "" for i in (0..<pinLength) { if let txtFd = self.viewWithTag(1000+i) as? OTPTextField, txtFd.text?.isValidText() == true { sOTPCode = sOTPCode + txtFd.text! } } return sOTPCode } /// manage textfield change responder /// /// - Parameter textField: textfield @objc func textDidChange(textField: UITextField) { var sOTPCode = "" for i in (0..<pinLength) { if let txtFd = self.viewWithTag(1000+i) as? OTPTextField, txtFd.text?.isValidText() == true { sOTPCode = sOTPCode + txtFd.text! } } self.manageTextFieldResponder(textField: textField) self.textDidChange?() } /// manage textfield responder for handling logic for OTP /// /// - Parameter textField: textfield func manageTextFieldResponder(textField: UITextField) { isEmpty = true if textField.text?.count == 1 { let currentTextIndex = textField.tag-1000 if currentTextIndex == pinLength-1 { isEmpty = false textField.resignFirstResponder() if self.getOTP().count == pinLength { self.OTPIsEntered?() } } else { if let txtFd_next = self.viewWithTag(1000+currentTextIndex+1) as? OTPTextField { if let cell = collectionVw.viewWithTag(5000+currentTextIndex+1) as? OTPCollectionViewCell { cell.setBeginTxt(viewTopCont: cell.con_top_vwBg, lineHeightCont: cell.con_height_vwBottomLine, view: cell.vwBottomLine) } txtFd_next.becomeFirstResponder() } } } else if textField.text?.count == 0 { let currentTextIndex = textField.tag-1000 if currentTextIndex == 0 || currentTextIndex == 1 { if let txtFd_first = self.viewWithTag(1000) as? OTPTextField { txtFd_first.becomeFirstResponder() } } else { if let txtFd_prev = self.viewWithTag(1000+currentTextIndex-1) as? OTPTextField { txtFd_prev.becomeFirstResponder() } } } else if (textField.text?.count)! > 1 { let lastChar = String(describing: (textField.text?.last)!) textField.text = lastChar let currentTextIndex = textField.tag-1000 if currentTextIndex == pinLength-1 { isEmpty = false textField.resignFirstResponder() } else { if let txtFd_next = self.viewWithTag(1000+currentTextIndex+1) as? OTPTextField { txtFd_next.becomeFirstResponder() } } } } /// manage textfield responder on back press /// /// - Parameter textField: textfield func manageTextFieldResponderOnBackPress(textField: UITextField) { if textField.text?.count == 1 { let currentTextIndex = textField.tag-1000 if currentTextIndex == pinLength-1 { isEmpty = false textField.resignFirstResponder() } else { if let txtFd_next = self.viewWithTag(1000+currentTextIndex+1) as? OTPTextField { txtFd_next.becomeFirstResponder() } } } else if textField.text?.count == 0 { let currentTextIndex = textField.tag-1000 if currentTextIndex == 0 { if let txtFd_first = self.viewWithTag(1000) as? OTPTextField { txtFd_first.becomeFirstResponder() } } else if currentTextIndex == 1 { if let txtFd_first = self.viewWithTag(1000) as? OTPTextField { txtFd_first.text = "" txtFd_first.becomeFirstResponder() } } else { if let txtFd_prev = self.viewWithTag(1000+currentTextIndex-1) as? OTPTextField { txtFd_prev.becomeFirstResponder() } } } else if (textField.text?.count)! > 1 { let lastChar = String(describing: (textField.text?.last)!) textField.text = lastChar } } } // MARK: - UITextFieldDelegate extension OTPView: UITextFieldDelegate { /// textFieldDidBeginEditing : Handles textfield when editing begins /// /// - Parameter textField: textfield func textFieldDidBeginEditing(_ textField: UITextField) { self.updateTextFields() } /// textFieldDidEndEditing: Handles textfield when editing ends. /// /// - Parameter textField: textfield func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { let currentIndex = textField.tag-1000 if let cell = collectionVw.viewWithTag(5000+currentIndex) as? OTPCollectionViewCell { cell.setBeginTxt(viewTopCont: cell.con_top_vwBg, lineHeightCont: cell.con_height_vwBottomLine, view: cell.vwBottomLine, textField: cell.txtField) } UIView.animate(withDuration: 0.3) { self.layoutIfNeeded() } self.updateTextFields() } /// textFieldDidEndEditing: Handles textfield when editing begins. /// /// - Parameter textField: textfield func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { let currentIndex = textField.tag-1000 if let cell = collectionVw.viewWithTag(5000+currentIndex) as? OTPCollectionViewCell { for cell in collectionVw.visibleCells { if let aCell = cell as? OTPCollectionViewCell { if aCell.txtField.isFirstResponder { aCell.setBeginTxt(viewTopCont: aCell.con_top_vwBg, lineHeightCont: aCell.con_height_vwBottomLine, view: aCell.vwBottomLine) } } } cell.setBeginTxt(viewTopCont: cell.con_top_vwBg, lineHeightCont: cell.con_height_vwBottomLine, view: cell.vwBottomLine, forBegin: true) UIView.animate(withDuration: 0.3) { cell.layoutIfNeeded() } } return true } } /// custom class for textfield for handling back call. class OTPTextField: UITextField { var backPressed : (() -> ())? override func deleteBackward() { super.deleteBackward() self.backPressed?() } } /// String extension for validating text. extension String { /// It will validate the given text /// - Returns: true or false func isValidText() -> Bool { let str:String = self.replacingOccurrences(of: " ", with: "") return str.count>0 ? true:false } } extension OTPView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pinLength } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { print(self.frame) print(pinLength) let rWidth = self.frame.size.width let totalBoxWidth: CGFloat = CGFloat((pinLength*50)+((pinLength-1)*10)) let finalWidth: CGFloat = rWidth-totalBoxWidth if finalWidth>0 { return CGSize(width: 50.0, height: 50.0) } else { let expectedWidth: CGFloat = CGFloat((rWidth - CGFloat((pinLength-1)*10))/CGFloat(pinLength)) print(expectedWidth) return CGSize(width: expectedWidth, height: 50.0) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let rWidth = self.frame.size.width let totalBoxWidth: CGFloat = CGFloat((pinLength*50)+((pinLength-1)*10)) let finalWidth: CGFloat = rWidth-totalBoxWidth if finalWidth>0 { let totalCellWidth = 50 * collectionView.numberOfItems(inSection: 0) let totalSpacingWidth = 10 * (collectionView.numberOfItems(inSection: 0) - 1) let leftInset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2 let rightInset = leftInset return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset) } else { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "OTPCollectionViewCell", for: indexPath) as! OTPCollectionViewCell cell.tag = 5000+indexPath.row cell.txtField.tag = 1000+indexPath.row cell.vwBottomLine.tag = 2000+indexPath.row cell.vwBg.backgroundColor = bgColorTextField cell.txtField.delegate = self cell.vwBottomLine.isHidden = (OTPStyle == .line ? false : true) cell.vwBg.isHidden = (OTPStyle == .line ? false : true) return cell } }
33.520921
162
0.5655
036e6f4fe429da373d220e9dc132bc5c65345257
3,538
import Foundation public final class Promise<T> { private var value: T? private var lock = pthread_mutex_t() private let disposable = MetaDisposable() private let subscribers = Bag<(T) -> Void>() public init(_ value: T) { self.value = value pthread_mutex_init(&self.lock, nil) } public init() { pthread_mutex_init(&self.lock, nil) } deinit { pthread_mutex_destroy(&self.lock) self.disposable.dispose() } public func set(_ signal: Signal<T, NoError>) { pthread_mutex_lock(&self.lock) self.value = nil pthread_mutex_unlock(&self.lock) self.disposable.set(signal.start(next: { [weak self] next in if let strongSelf = self { pthread_mutex_lock(&strongSelf.lock) strongSelf.value = next let subscribers = strongSelf.subscribers.copyItems() pthread_mutex_unlock(&strongSelf.lock) for subscriber in subscribers { subscriber(next) } } })) } public func get() -> Signal<T, NoError> { return Signal { subscriber in pthread_mutex_lock(&self.lock) let currentValue = self.value let index = self.subscribers.add({ next in subscriber.putNext(next) }) pthread_mutex_unlock(&self.lock) if let currentValue = currentValue { subscriber.putNext(currentValue) } return ActionDisposable { pthread_mutex_lock(&self.lock) self.subscribers.remove(index) pthread_mutex_unlock(&self.lock) } } } } public final class ValuePromise<T: Equatable> { private var value: T? private var lock = pthread_mutex_t() private let subscribers = Bag<(T) -> Void>() public let ignoreRepeated: Bool public init(_ value: T, ignoreRepeated: Bool = false) { self.value = value self.ignoreRepeated = ignoreRepeated pthread_mutex_init(&self.lock, nil) } public init(ignoreRepeated: Bool = false) { self.ignoreRepeated = ignoreRepeated pthread_mutex_init(&self.lock, nil) } deinit { pthread_mutex_destroy(&self.lock) } public func set(_ value: T) { pthread_mutex_lock(&self.lock) let subscribers: [(T) -> Void] if !self.ignoreRepeated || self.value != value { self.value = value subscribers = self.subscribers.copyItems() } else { subscribers = [] } pthread_mutex_unlock(&self.lock); for subscriber in subscribers { subscriber(value) } } public func get() -> Signal<T, NoError> { return Signal { subscriber in pthread_mutex_lock(&self.lock) let currentValue = self.value let index = self.subscribers.add({ next in subscriber.putNext(next) }) pthread_mutex_unlock(&self.lock) if let currentValue = currentValue { subscriber.putNext(currentValue) } return ActionDisposable { pthread_mutex_lock(&self.lock) self.subscribers.remove(index) pthread_mutex_unlock(&self.lock) } } } }
28.764228
68
0.547202
14e8601cf1d331250aaa34a789eba9ff360c4c8c
63
open class ContractMethodDecoration: TransactionDecoration { }
21
60
0.857143
fc04d7473a1344c7d63f7e38d801f021ddc44a5b
10,961
// File created from ScreenTemplate // $ createScreen.sh Spaces/SpaceRoomList/ExploreRoom ShowSpaceExploreRoom /* Copyright 2021 New Vector Ltd 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 final class SpaceExploreRoomViewController: UIViewController { // MARK: - Constants private enum Constants { static let estimatedRowHeight: CGFloat = 64 } // MARK: Outlets @IBOutlet private var tableSearchBar: UISearchBar! @IBOutlet private var tableView: UITableView! // MARK: Private private var viewModel: SpaceExploreRoomViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var titleView: MainTitleView! private var emptyView: RootTabEmptyView! private var plusButtonImageView: UIImageView! private var hasMore: Bool = false private var itemDataList: [SpaceExploreRoomListItemViewData] = [] { didSet { self.tableView.reloadData() } } private var emptyViewArtwork: UIImage { return ThemeService.shared().isCurrentThemeDark() ? Asset.Images.roomsEmptyScreenArtworkDark.image : Asset.Images.roomsEmptyScreenArtwork.image } private var scrollViewHidden = true { didSet { UIView.animate(withDuration: 0.2) { self.tableView.alpha = self.scrollViewHidden ? 0 : 1 self.emptyView.alpha = self.scrollViewHidden ? 1 : 0 } } } // MARK: - Setup class func instantiate(with viewModel: SpaceExploreRoomViewModelType) -> SpaceExploreRoomViewController { let viewController = StoryboardScene.SpaceExploreRoomViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme viewController.emptyView = RootTabEmptyView.instantiate() return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.tableView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleView.update(theme: theme) self.tableView.backgroundColor = theme.colors.background self.tableView.reloadData() self.emptyView.update(theme: theme) theme.applyStyle(onSearchBar: self.tableSearchBar) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.vc_removeBackTitle() self.titleView = MainTitleView() self.titleView.titleLabel.text = VectorL10n.titleRooms self.navigationItem.titleView = self.titleView self.tableSearchBar.placeholder = VectorL10n.searchDefaultPlaceholder self.tableView.keyboardDismissMode = .interactive self.setupTableView() self.emptyView.fill(with: self.emptyViewArtwork, title: VectorL10n.roomsEmptyViewTitle, informationText: VectorL10n.roomsEmptyViewInformation) self.plusButtonImageView = self.vc_addFAB(withImage: Asset.Images.roomsFloatingAction.image, target: self, action: #selector(addRoomAction(semder:))) self.emptyView.frame = CGRect(x: 0, y: self.tableSearchBar.frame.maxY, width: self.view.bounds.width, height: self.view.bounds.height - self.tableSearchBar.frame.maxY) self.emptyView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.emptyView.alpha = 0 self.view.insertSubview(self.emptyView, at: 0) } private func setupTableView() { self.tableView.separatorStyle = .none self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = Constants.estimatedRowHeight self.tableView.allowsSelection = true self.tableView.register(cellType: SpaceChildViewCell.self) self.tableView.register(cellType: SpaceChildSpaceViewCell.self) self.tableView.register(cellType: PaginationLoadingViewCell.self) self.tableView.tableFooterView = UIView() } private func render(viewState: SpaceExploreRoomViewState) { switch viewState { case .loading: self.renderLoading() case .spaceNameFound(let spaceName): self.titleView.subtitleLabel.text = spaceName case .loaded(let children, let hasMore): self.hasMore = hasMore self.renderLoaded(children: children) case .emptySpace: self.renderEmptySpace() case .emptyFilterResult: self.renderEmptyFilterResult() case .error(let error): self.render(error: error) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(children: [SpaceExploreRoomListItemViewData]) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.itemDataList = children self.scrollViewHidden = false } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func renderEmptySpace() { self.emptyView.fill(with: self.emptyViewArtwork, title: VectorL10n.spacesEmptySpaceTitle, informationText: VectorL10n.spacesEmptySpaceDetail) self.scrollViewHidden = true self.activityPresenter.removeCurrentActivityIndicator(animated: true) } private func renderEmptyFilterResult() { self.emptyView.fill(with: self.emptyViewArtwork, title: VectorL10n.spacesNoResultFoundTitle, informationText: VectorL10n.spacesNoRoomFoundDetail) self.scrollViewHidden = true self.activityPresenter.removeCurrentActivityIndicator(animated: true) } // MARK: - Actions private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } @objc private func addRoomAction(semder: UIView) { self.errorPresenter.presentError(from: self, title: VectorL10n.spacesAddRoomsComingSoonTitle, message: VectorL10n.spacesComingSoonDetail, animated: true, handler: nil) } // MARK: - UISearchBarDelegate override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.viewModel.process(viewAction: .searchChanged(searchText)) } } // MARK: - UITableViewDataSource extension SpaceExploreRoomViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.itemDataList.count + (self.hasMore ? 1 : 0) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard indexPath.row < self.itemDataList.count else { let cell = tableView.dequeueReusableCell(for: indexPath, cellType: PaginationLoadingViewCell.self) cell.update(theme: self.theme) return cell } let viewData = self.itemDataList[indexPath.row] let cell = viewData.childInfo.roomType == .space ? tableView.dequeueReusableCell(for: indexPath, cellType: SpaceChildSpaceViewCell.self) : tableView.dequeueReusableCell(for: indexPath, cellType: SpaceChildViewCell.self) cell.update(theme: self.theme) cell.fill(with: viewData) cell.selectionStyle = .none return cell } } // MARK: - UITableViewDelegate extension SpaceExploreRoomViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.viewModel.process(viewAction: .complete(self.itemDataList[indexPath.row], tableView.cellForRow(at: indexPath))) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if self.hasMore && indexPath.row >= self.itemDataList.count { self.viewModel.process(viewAction: .loadData) } } } // MARK: - SpaceExploreRoomViewModelViewDelegate extension SpaceExploreRoomViewController: SpaceExploreRoomViewModelViewDelegate { func spaceExploreRoomViewModel(_ viewModel: SpaceExploreRoomViewModelType, didUpdateViewState viewSate: SpaceExploreRoomViewState) { self.render(viewState: viewSate) } }
37.927336
227
0.697382
d5863f2a5d35a3d4637cb4795d5d19559737492c
547
// // FavStockCell.swift // Ribbit // // Created by Rao Mudassar on 29/07/2021. // import UIKit class FavStockCell: UITableViewCell { @IBOutlet var collectionView: UICollectionView! @IBOutlet var btnViewAll: UIButton! var actionBlock: (() -> Void)? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func buttonAllViewTap(sender: AnyObject) { actionBlock?() } }
24.863636
65
0.670932
0816fa1c1ed1f5f03ea5f5df3a9bb97b20ee6a91
6,918
// // ScheduledAssessment.swift // BridgeApp (iOS) // // Copyright © 2020 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import BridgeSDK import Research public protocol AssessmentSchedule { /// A localized string with the label for the timing for when the assessment is available. var availabilityLabel: String? { get } /// The task info associated with this schedule. var taskInfo: RSDTaskInfo { get } /// Is this a schedule that is available all day for one day only? var isAllDay: Bool { get } } public protocol AssessmentScheduleManager : RSDTaskControllerDelegate { func reloadData() func numberOfSections() -> Int func numberOfAssessmentSchedules(in section: Int) -> Int func assessmentSchedule(at indexPath: IndexPath) -> AssessmentSchedule func instantiateTaskViewModel(at indexPath: IndexPath) -> RSDTaskViewModel func isCompleted(at indexPath: IndexPath, on date: Date) -> Bool func isExpired(at indexPath: IndexPath, on date: Date) -> Bool func isAvailableNow(at indexPath: IndexPath, on date: Date) -> Bool } extension SBAScheduleManager : AssessmentScheduleManager { public func numberOfSections() -> Int { return 1 } public func numberOfAssessmentSchedules(in section: Int) -> Int { return self.scheduledActivities.count } public func assessmentSchedule(at indexPath: IndexPath) -> AssessmentSchedule { return self.scheduledActivities[indexPath.row] } public func instantiateTaskViewModel(at indexPath: IndexPath) -> RSDTaskViewModel { let schedule = self.scheduledActivities[indexPath.row] return self.instantiateTaskViewModel(for: schedule) } public func isCompleted(at indexPath: IndexPath, on date: Date) -> Bool { let schedule = self.scheduledActivities[indexPath.row] return schedule.isCompleted } public func isExpired(at indexPath: IndexPath, on date: Date) -> Bool { let schedule = self.scheduledActivities[indexPath.row] return schedule.isExpired } public func isAvailableNow(at indexPath: IndexPath, on date: Date) -> Bool { let schedule = self.scheduledActivities[indexPath.row] return !schedule.isCompleted && schedule.isAvailableNow } } extension SBBScheduledActivity : AssessmentSchedule { public var taskInfo: RSDTaskInfo { return self.activity } /// Is this a schedule that is available all day for one day only? public var isAllDay: Bool { guard let expireDate = self.expiresOn else { return false } let startOfDay = scheduledOn.startOfDay() return startOfDay == scheduledOn && startOfDay.addingNumberOfDays(1) == expireDate } private var now: Date { return Date() } public var availabilityLabel: String? { if let finished = finishedOn { let timeStr = finished.localizedAvailabilityString() let formatStr = Localization.localizedString("Completed: %@") return String.localizedStringWithFormat(formatStr, timeStr) } else if isAvailableNow { if let expireTime = self.expiresOn, !isAllDay { let timeStr = expireTime.localizedAvailabilityString() let formatStr = Localization.localizedString("Available until %@") return String.localizedStringWithFormat(formatStr, timeStr) } else { // Do not show anything for the availability string if available now // and will not expire or if it is a daily schedule. return nil } } else if let expireTime = self.expiresOn, !isAllDay { if expireTime < now, !isCompleted { let timeStr = expireTime.localizedAvailabilityString() let formatStr = Localization.localizedString("Expired: %@") return String.localizedStringWithFormat(formatStr, timeStr) } else { let formatter = DateIntervalFormatter() formatter.dateStyle = scheduledOn.isToday ? .none : .short formatter.timeStyle = scheduledOn.isToday ? .short : .none let timeStr = formatter.string(from: scheduledOn, to: expireTime) let formatStr = Localization.localizedString("Available: %@") return String.localizedStringWithFormat(formatStr, timeStr) } } else { let timeStr = scheduledOn.localizedAvailabilityString() let formatStr = Localization.localizedString("Available: %@") return String.localizedStringWithFormat(formatStr, timeStr) } } } extension Date { fileprivate func localizedAvailabilityString() -> String { if isToday { return DateFormatter.localizedString(from: self, dateStyle: .none, timeStyle: .short) } else if self.startOfDay() == self { return DateFormatter.localizedString(from: self, dateStyle: .short, timeStyle: .none) } else { return DateFormatter.localizedString(from: self, dateStyle: .short, timeStyle: .short) } } }
41.42515
98
0.681411
e998c2b03618f5d6147203cb9e04916f5b45a2de
2,560
// // UIButton+Typesetting.swift // JuYou // // Created by caobo56 on 16/5/18. // Copyright © 2016年 caobo56. All rights reserved. // import UIKit extension UIButton{ func setHomeImage(image:UIImage,title:String,stateType:UIControlState){ let titleSize:CGSize = title.sizeWithAttributes([NSFontAttributeName : UIFont.systemFontOfSize(14.0)]) self.imageView?.contentMode = UIViewContentMode.Center self.imageEdgeInsets = UIEdgeInsetsMake(-20, 0.0, 0.0, -titleSize.width) self.setImage(image, forState: stateType) self.titleLabel?.contentMode = UIViewContentMode.Center self.titleLabel?.backgroundColor = UIColor.clearColor() self.titleLabel?.font = UIFont.systemFontOfSize(14.0) self.setTitleColor(UIColorWithHex(0x26323B, alpha:1.0), forState: stateType) self.titleEdgeInsets = UIEdgeInsetsMake(52.0, -image.width, 0.0, 0.0) self.setTitle(title, forState:stateType) } func setHorizontalLeftImage(image: UIImage, withTitle title: String, forState stateType: UIControlState, andWithFont fontSize: CGFloat) { self.imageView?.contentMode = UIViewContentMode.Center self.imageEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) self.setImage(image, forState: stateType) self.titleLabel!.contentMode = UIViewContentMode.Center self.titleLabel!.backgroundColor = UIColor.clearColor() self.titleLabel!.font = UIFont.systemFontOfSize(fontSize) self.setTitleColor(UIColorWithHex(0x26323B, alpha:1.0), forState: stateType) self.titleEdgeInsets = UIEdgeInsetsMake(0.0, 3.0, 0.0, 0.0) self.setTitle(title, forState: stateType) } func setHorizontalRightImage(image: UIImage, title: String,stateType: UIControlState,fontSize: CGFloat) { let titleSize: CGSize = title.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(12.0)]) self.imageView?.contentMode = UIViewContentMode.Center self.imageEdgeInsets = UIEdgeInsetsMake(0.0,titleSize.width+25, 0.0, -titleSize.width) self.setImage(image, forState: stateType) self.titleLabel!.contentMode = UIViewContentMode.Center self.titleLabel!.backgroundColor = UIColor.clearColor() self.titleLabel!.font = UIFont.systemFontOfSize(fontSize) self.setTitleColor(UIColorWithHex(0x26323B, alpha:1.0), forState: stateType) self.titleEdgeInsets = UIEdgeInsetsMake(0, -image.size.width, 0, image.size.width) self.setTitle(title, forState: stateType) } }
49.230769
141
0.716797
644f8b199729d0bc6af156a3b64dad801fb95642
2,099
// // SevenSegmentLetters.swift // SwiftyTM1637 // // Created by Helge Hess on 10.06.18. // import Foundation public extension SevenSegment { static let dash : SevenSegment = [ .middleDash ] // - static let letters : [ Character : SevenSegment ] = [ "A": SevenSegment(hexDigit: 0xA), "B": SevenSegment(hexDigit: 0xB), "C": SevenSegment(hexDigit: 0xC), "D": SevenSegment(hexDigit: 0xD), "E": SevenSegment(hexDigit: 0xE), "F": SevenSegment(hexDigit: 0xF), "G": SevenSegment(digit: 6), "H": [ .upperLeft, .upperRight, .middleDash, .lowerLeft, .lowerRight ], "I": [ .upperRight, .lowerRight ], "J": [ .upperRight, .lowerRight, .lowerDash ], "K": [ .upperRight, .middleDash, .upperLeft, .lowerLeft, .lowerRight ], "L": [ .upperLeft, .lowerLeft, .lowerDash ], "O": SevenSegment(digit: 0), "P": [ .upperLeft, .upperDash, .upperRight, .middleDash, .lowerLeft ], "Q": SevenSegment(digit: 0, dot: true), "R": SevenSegment(hexDigit: 0xA), "S": [ .upperLeft, .middleDash, .upperDash, .lowerRight, .lowerDash ], "T": [ .upperDash, .upperRight, .lowerRight ], "U": [ .upperLeft, .upperRight, .lowerLeft, .lowerRight, .lowerDash ], "V": [ .upperLeft, .upperRight, .lowerLeft, .lowerRight, .lowerDash ], // W? "X": [ .upperRight, .middleDash, .upperLeft, .lowerLeft, .lowerRight ], "Y": [ .upperRight, .middleDash, .upperLeft, .lowerRight ], "Z": [ .upperDash, .upperRight, .middleDash, .lowerLeft, .lowerDash ], "a": SevenSegment(hexDigit: 0xA), "b": [ .upperLeft, .middleDash, .lowerLeft, .lowerRight, .lowerDash ], "c": [ .middleDash, .lowerLeft, .lowerDash ], "d": [ .middleDash, .upperRight, .lowerLeft, .lowerRight, .lowerDash ], "h": [ .upperRight, .middleDash, .lowerLeft, .lowerRight ], "i": [ .lowerRight ], "n": [ .lowerLeft, .middleDash, .lowerRight ], "o": [ .middleDash, .lowerLeft, .lowerRight, .lowerDash ], "u": [ .lowerLeft, .lowerDash, .lowerRight ], "v": [ .lowerLeft, .lowerDash, .lowerRight ], ] }
40.365385
77
0.606956
dd9e735f3216a587b47d8f9b9a56a37321e6d55e
1,255
// // SavannaKit+Swift.swift // SourceEditor // // Created by Louis D'hauwe on 24/07/2018. // Copyright © 2018 Silver Fox. All rights reserved. // import Foundation import SavannaKit public protocol SourceCodeRegexLexer: RegexLexer { } extension RegexLexer { public func regexGenerator(_ pattern: String, options: NSRegularExpression.Options = [], transformer: @escaping TokenTransformer) -> TokenGenerator? { guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return nil } return .regex(RegexTokenGenerator(regularExpression: regex, tokenTransformer: transformer)) } } extension SourceCodeRegexLexer { public func regexGenerator(_ pattern: String, options: NSRegularExpression.Options = [], tokenType: SourceCodeTokenType) -> TokenGenerator? { return regexGenerator(pattern, options: options, transformer: { (range) -> Token in return SimpleSourceCodeToken(type: tokenType, range: range) }) } public func keywordGenerator(_ words: [String], tokenType: SourceCodeTokenType) -> TokenGenerator { return .keywords(KeywordTokenGenerator(keywords: words, tokenTransformer: { (range) -> Token in return SimpleSourceCodeToken(type: tokenType, range: range) })) } }
26.702128
151
0.743426
0e27ba944df773a209453711f4ceb0401cd0c957
2,031
// // Copyright 2020 Swiftkube 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. // /// /// Generated by Swiftkube:ModelGen /// Kubernetes v1.20.9 /// flowcontrol.v1beta1.ServiceAccountSubject /// import Foundation public extension flowcontrol.v1beta1 { /// /// ServiceAccountSubject holds detailed information for service-account-kind subject. /// struct ServiceAccountSubject: KubernetesResource { /// /// `name` is the name of matching ServiceAccount objects, or "*" to match regardless of name. Required. /// public var name: String /// /// `namespace` is the namespace of matching ServiceAccount objects. Required. /// public var namespace: String /// /// Default memberwise initializer /// public init( name: String, namespace: String ) { self.name = name self.namespace = namespace } } } /// /// Codable conformance /// public extension flowcontrol.v1beta1.ServiceAccountSubject { private enum CodingKeys: String, CodingKey { case name = "name" case namespace = "namespace" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name) self.namespace = try container.decode(String.self, forKey: .namespace) } func encode(to encoder: Encoder) throws { var encodingContainer = encoder.container(keyedBy: CodingKeys.self) try encodingContainer.encode(name, forKey: .name) try encodingContainer.encode(namespace, forKey: .namespace) } }
26.723684
106
0.726736
142ede8e32d495783948cf43016bf73c49a6c6f1
2,018
// // RealmCompanyWireframe.swift // SyncKitRealmSwiftExample // // Created by Manuel Entrena on 26/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import Foundation import RealmSwift import SyncKit class RealmCompanyWireframe: CompanyWireframe { let navigationController: UINavigationController let realm: Realm let employeeWireframe: EmployeeWireframe let synchronizer: CloudKitSynchronizer? let settingsManager: SettingsManager init(navigationController: UINavigationController, realm: Realm, employeeWireframe: EmployeeWireframe, synchronizer: CloudKitSynchronizer?, settingsManager: SettingsManager) { self.navigationController = navigationController self.realm = realm self.employeeWireframe = employeeWireframe self.synchronizer = synchronizer self.settingsManager = settingsManager } func show() { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Company") as! CompanyViewController #if USE_INT_KEY let interactor = RealmCompanyInteractor_Int(realm: realm, shareController: synchronizer) #else let interactor = RealmCompanyInteractor(realm: realm, shareController: synchronizer) #endif let presenter = DefaultCompanyPresenter(view: viewController, interactor: interactor, wireframe: self, synchronizer: synchronizer, canEdit: true, settingsManager: settingsManager) viewController.presenter = presenter interactor.delegate = presenter navigationController.viewControllers = [viewController] } func show(company: Company, canEdit: Bool) { employeeWireframe.show(company: company, canEdit: canEdit) } }
40.36
179
0.653617
f4320b0dfd1f423ba515b372f486d1347863fb7f
363
// // Model.swift // PushoverSender // // Created by m3g0byt3 on 03/09/2018. // Copyright © 2018 m3g0byt3. All rights reserved. // import Foundation /// Adopted by immutable struct. protocol Model { associatedtype ModelObject /// Persistence representation (e.g CoreData NSManagedObject / Realm Object). var modelObject: ModelObject { get } }
19.105263
81
0.705234
4b6792616d507808dd3a39f5a3a108f1440041fc
626
// // TKUIRoutingResultsViewModel+RealTime.swift // TripKitUI-iOS // // Created by Adrian Schönig on 01.04.19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import Foundation import RxSwift import TripKit // MARK: - Real-time updates extension TKUIRoutingResultsViewModel { static func fetchRealTimeUpdates(for tripGroups: Observable<[TripGroup]>) -> Observable<TKRealTimeUpdateProgress<Void>> { return Observable<Int>.interval(.seconds(30), scheduler: MainScheduler.instance) .withLatestFrom(tripGroups) .flatMapLatest(TKRealTimeFetcher.rx.update) .startWith(.idle) } }
23.185185
123
0.738019
8fd654b8323f15dc713742835929b9c3ebeb2697
10,305
import Foundation import RealmSwift final class GPSSecureStorage: SafePathsSecureStorage { @objc static let shared = GPSSecureStorage() static let DAYS_TO_KEEP: TimeInterval = 14 static let LOCATION_INTERVAL: TimeInterval = 60 * 5 /// Hashing is very computationally expensive, so limit the number of hashes computed during a single backfill. static let MAX_BACKFILL_HASHES = 60 private let queue = DispatchQueue(label: "GPSSecureStorage") /// Creates stationary locations at `previousLocation` ever `LOCATION_INTERVAL` until `newLocation`. /// Returns locations in descending chronological order. static func createAssumedLocations(previousLocation: Location, newLocation: MAURLocation) -> [Location] { var assumedLocations = [Location]() assumedLocations.append(contentsOf: stride( from: previousLocation.time + LOCATION_INTERVAL, to: newLocation.time.timeIntervalSince1970, by: LOCATION_INTERVAL ).enumerated().map { idx, time in return Location.fromAssumed( time: time, latitude: previousLocation.latitude, longitude: previousLocation.longitude, hash: idx < MAX_BACKFILL_HASHES ) }.reversed()) return assumedLocations } @objc func saveDeviceLocation(_ backgroundLocation: MAURLocation, backfill: Bool = true, completion: (() -> Void)? = nil) { queue.async { autoreleasepool { [weak self] in self?.saveDeviceLocationImmediately(backgroundLocation, backfill: backfill) completion?() } } } @objc func importLocations(locations: NSArray, source: Location.Source, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { queue.async { autoreleasepool { [weak self] in self?.importLocationsImmediately(locations, source: source, resolve: resolve, reject: reject) } } } @objc func getLocations(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { queue.async { autoreleasepool { [weak self] in self?.getLocationsImmediately(resolve: resolve, reject: reject) } } } @objc func trimLocations(backfill: Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { queue.async { autoreleasepool { [weak self] in self?.trimLocationsImmediately(backfill: backfill, resolve: resolve, reject: reject) } } } override func getRealmConfig() -> Realm.Configuration? { // TODO: Create appropriate migration blocks as needed if let key = getEncryptionKey() { if inMemory { return Realm.Configuration( inMemoryIdentifier: identifier, encryptionKey: key as Data, schemaVersion: 1, deleteRealmIfMigrationNeeded: true, objectTypes: [Location.self] ) } else { return Realm.Configuration( encryptionKey: key as Data, schemaVersion: 1, deleteRealmIfMigrationNeeded: true, objectTypes: [Location.self] ) } } else { return nil } } override func getRealmInstance() -> Realm? { guard let realm = super.getRealmInstance() else { return nil } // The OS default file protection level encrypts Realm files when device is locked. // We enable Realm's encryption (see getEncryptionKey) instead, so can remove the OS file protection. // This allows us to write/read from Realm while the app is backgrounded and the device is locked. if let dir = realm.configuration.fileURL?.deletingLastPathComponent().path { do { try FileManager.default.setAttributes([ .protectionKey: FileProtectionType.none ], ofItemAtPath: dir) } catch (let error) { Log.storage.error("Failed to set Realm file protection level: \(error)") } } return realm } } // MARK: - Private private extension GPSSecureStorage { var cutoffTime: TimeInterval { return (Date().timeIntervalSince1970 - (GPSSecureStorage.DAYS_TO_KEEP * 86400)) } /// This function should be called only on self.queue func saveDeviceLocationImmediately(_ backgroundLocation: MAURLocation, backfill: Bool) { Log.storage.debug("Processing \(backgroundLocation)") // The geolocation library sometimes returns nil times. // Almost immediately after these locations, we receive an identical location containing a time. guard backgroundLocation.hasTime() else { return } guard let realm = getRealmInstance() else { return } let currentLocation = Location.fromBackgroundLocation(backgroundLocation: backgroundLocation, source: .device) var previousLocations = Array(realm.previousLocations.prefix(2)) var newLocations = [Location]() // Backfill locations if outside the desired interval if backfill, let previousLocation = previousLocations.first { let assumedLocations = GPSSecureStorage.createAssumedLocations( previousLocation: previousLocation, newLocation: backgroundLocation ) if assumedLocations.count > 0 { Log.storage.debug("Backfilling \(assumedLocations.count) locations") newLocations.append(contentsOf: assumedLocations) } previousLocations = assumedLocations + previousLocations } // If within the minimum time interval, update the existing location if previousLocations.count >= 2 && previousLocations[0].time - previousLocations[1].time < GPSSecureStorage.LOCATION_INTERVAL { Log.storage.debug("Within minimum interval, updating previous location") currentLocation.id = previousLocations[0].id } newLocations.insert(currentLocation, at: 0) realm.write(locations: newLocations) } /// This function should be called only on self.queue func importLocationsImmediately(_ locations: NSArray, source: Location.Source, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { guard let realm = getRealmInstance() else { resolve(false) return } let locationsToInsert = locations.compactMap { Location.fromImportLocation(dictionary: $0 as? NSDictionary, source: source) }.filter { $0.time >= cutoffTime } realm.write(locations: locationsToInsert, resolve: resolve, reject: reject) } /// This function should be called only on self.queue func getLocationsImmediately(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { guard let realm = getRealmInstance() else { resolve(NSArray()) return } let results = realm.objects(Location.self) .filter("\(Location.Key.time.rawValue)>=\(cutoffTime)") .sorted(byKeyPath: Location.Key.time.rawValue, ascending: true) resolve(Array(results.map { $0.toSharableDictionary() })) } /// This function should be called only on self.queue func trimLocationsImmediately(backfill: Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { guard let realm = getRealmInstance() else { resolve(false) return } Log.storage.debug("Trimming locations") realm.delete( locations: realm.objects(Location.self).filter("\(Location.Key.time.rawValue)<\(cutoffTime)"), resolve: { _ in if backfill { realm.backfillLocations(resolve: resolve, reject: reject) } else { resolve(true) } }, reject: reject ) } } private extension Realm { var previousLocations: Results<Location> { return objects(Location.self).sorted(byKeyPath: Location.Key.time.rawValue, ascending: false) } /// Backfills locations if necessary. `resolve` and `reject` will be invoked on the same thread before returning. func backfillLocations(resolve: RCTPromiseResolveBlock? = nil, reject: RCTPromiseRejectBlock? = nil) { guard let previousLocation = previousLocations.first else { resolve?(true) return } let now = Date() guard now.timeIntervalSince(previousLocation.date) > GPSSecureStorage.LOCATION_INTERVAL else { resolve?(true) return } let currentLocation = MAURLocation(location: previousLocation) currentLocation.time = now let assumedLocations = GPSSecureStorage.createAssumedLocations( previousLocation: previousLocation, newLocation: currentLocation ) if assumedLocations.count > 0 { Log.storage.debug("Backfilling \(assumedLocations.count) locations") } write(locations: assumedLocations, resolve: resolve, reject: reject) } /// Inserts the given locations. `resolve` and `reject` will be invoked on the same thread before returning. func write<T: Collection>(locations: T, resolve: RCTPromiseResolveBlock? = nil, reject: RCTPromiseRejectBlock? = nil) where T.Element == Location { guard !locations.isEmpty else { resolve?(true) return } do { try write { add(locations, update: .modified) Log.storage.debug("Wrote \(locations.count) locations to Realm") Log.storage.debug("There are now \(previousLocations.count) locations in Realm") resolve?(true) } } catch (let error as NSError) { Log.storage.error("Failed to write \(locations.count) locations: \(error)") reject?(String(error.code), error.localizedFailureReason ?? error.localizedDescription, error) } } /// Deletes the given locations. `resolve` and `reject` will be invoked on the same thread before returning. func delete<T: Collection>(locations: T, resolve: RCTPromiseResolveBlock? = nil, reject: RCTPromiseRejectBlock? = nil) where T.Element == Location { guard !locations.isEmpty else { resolve?(true) return } do { try write { delete(locations) Log.storage.debug("Deleted \(locations.count) locations from Realm") Log.storage.debug("There are now \(previousLocations.count) locations in Realm") resolve?(true) } } catch (let error as NSError) { Log.storage.error("Failed to delete \(locations.count) locations: \(error)") reject?(String(error.code), error.localizedFailureReason ?? error.localizedDescription, error) } } }
33.898026
166
0.693547
675aacf5881ede4a65fb2a3e5d5f02ee61039b98
1,558
/** * Copyright IBM Corporation 2017 * * 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 /** UpdateSynonym. */ public struct UpdateSynonym { /// The text of the synonym. public var synonym: String? /** Initialize a `UpdateSynonym` with member variables. - parameter synonym: The text of the synonym. - returns: An initialized `UpdateSynonym`. */ public init(synonym: String? = nil) { self.synonym = synonym } } extension UpdateSynonym: Codable { private enum CodingKeys: String, CodingKey { case synonym = "synonym" static let allValues = [synonym] } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) synonym = try container.decodeIfPresent(String.self, forKey: .synonym) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(synonym, forKey: .synonym) } }
28.327273
78
0.691913
bba6c857ae5deae81d94d0083c51ac726517a5bd
12,036
import UIKit internal enum NIDSessionEventName: String { case createSession = "CREATE_SESSION" case stateChange = "STATE_CHANGE" case setUserId = "SET_USER_ID" case setVariable = "SET_VARIABLE" case tag = "TAG" case setCheckPoint = "SET_CHECKPOINT" case setCustomEvent = "SET_CUSTOM_EVENT" case heartBeat = "HEARTBEAT" func log() { let event = NIDEvent(session: self, tg: nil, x: nil, y: nil) NeuroID.captureEvent(event) } } public enum NIDEventName: String { case heartbeat = "HEARTBEAT" case error = "ERROR" case log = "LOG" case userInactive = "USER_INACTIVE" case registerComponent = "REGISTER_COMPONENT" case registerTarget = "REGISTER_TARGET" case registerStylesheet = "REGISTER_STYLESHEET" case mutationInsert = "MUTATION_INSERT" case mutationRemove = "MUTATION_REMOVE" case mutationAttr = "MUTATION_ATTR" case formSubmit = "FORM_SUBMIT" case formReset = "FORM_RESET" case formSubmitSuccess = "FORM_SUBMIT_SUCCESS" case formSubmitFailure = "FORM_SUBMIT_FAILURE" case applicationSubmit = "APPLICATION_SUBMIT" case applicationSubmitSuccess = "APPLICATION_SUBMIT_SUCCESS" case applicationSubmitFailure = "APPLICATION_SUBMIT_FAILURE" case pageSubmit = "PAGE_SUBMIT" case focus = "FOCUS" case blur = "BLUR" case copy = "COPY" case cut = "CUT" case paste = "PASTE" case input = "INPUT" case invalid = "INVALID" case keyDown = "KEY_DOWN" case keyUp = "KEY_UP" case change = "CHANGE" case selectChange = "SELECT_CHANGE" case textChange = "TEXT_CHANGE" case radioChange = "RADIO_CHANGE" case checkboxChange = "CHECKBOX_CHANGE" case inputChange = "INPUT_CHANGE" case sliderChange = "SLIDER_CHANGE" case sliderSetMin = "SLIDER_SET_MIN" case sliderSetMax = "SLIDER_SET_MAX" case touchStart = "TOUCH_START" case touchMove = "TOUCH_MOVE" case touchEnd = "TOUCH_END" case touchCancel = "TOUCH_CANCEL" case windowLoad = "WINDOW_LOAD" case windowUnload = "WINDOW_UNLOAD" case windowFocus = "WINDOW_FOCUS" case windowBlur = "WINDOW_BLUR" case windowOrientationChange = "WINDOW_ORIENTATION_CHANGE" case windowResize = "WINDOW_RESIZE" case deviceMotion = "DEVICE_MOTION" case deviceOrientation = "DEVICE_ORIENTATION" var etn: String? { switch self { case .change, .textChange, .radioChange, .inputChange, .paste, .keyDown, .keyUp, .selectChange, .sliderChange: return rawValue default: return nil } } } public enum TargetValue: Codable,Equatable { case int(Int), string(String), bool(Bool), double(Double) public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .int(let value): try container.encode(value) case .string(let value): try container.encode(value) case .bool(let value): try container.encode(value) case .double(let value): try container.encode(value) } } public init(from decoder: Decoder) throws { if let int = try? decoder.singleValueContainer().decode(Int.self) { self = .int(int) return } if let double = try? decoder.singleValueContainer().decode(Double.self) { self = .double(double) return } if let string = try? decoder.singleValueContainer().decode(String.self) { self = .string(string) return } if let bool = try? decoder.singleValueContainer().decode(Bool.self) { self = .bool(bool) return } throw TG.missingValue } enum TG:Error { case missingValue } } public struct EventCache: Codable { var nidEvents: [NIDEvent] } public struct NIDEvent: Codable { public let type: String var tg: [String: TargetValue]? = nil var tgs: String? var en: String? var etn: String? // Tag name (input) var et: String? // Element Type (text) var eid: String? var v: String? // Value var ts:Int64 = ParamsCreator.getTimeStamp() var x: CGFloat? var y: CGFloat? var f: String? var lsid: String? var sid: String? // Done var siteId: String? // Unused var cid: String? // Done var did: String? // Done var iid: String? // Done var loc: String? // Done var ua: String? // Done var tzo: Int? // Done var lng: String? // Done var p: String? // Done var dnt: Bool? // Done var tch: Bool? // Done var url: String? var ns: String? // Done var jsl: Array<String> = ["iOS"]; var jsv: String? // Done var uid: String? /** Use to initiate a new session Element mapping: type: CREATE_SESSION, f: key, siteId: siteId, sid: sessionId, lsid: lastSessionId, cid: clientId, did: deviceId, iid: intermediateId, loc: locale, ua: userAgent, tzo: timezoneOffset, lng: language, ce: cookieEnabled, je: javaEnabled, ol: onLine, p: platform, sh: screenHeight, sw: screenWidth, ah: availHeight, aw: availWidth, cd: colorDepth, pd: pixelDepth, jsl: jsLibraries, dnt: doNotTrack, tch: touch, url: url, ns: commandQueueNamespace, jsv: jsVersion, is: idleSince, ts: Date.now(), Event Change type: CHANGE, tg: { tgs: target, et: eventMetadata.elementType, etn: eventMetadata.elementTagName }, v: eventMetadata.value, sm: eventMetadata.similarity, pd: eventMetadata.percentDiff, pl: eventMetadata.previousLength, cl: eventMetadata.currentLength, ld: eventMetadata.levenshtein, ts: Date.now(), */ // public init(from decoder: Decoder) throws { // // // } init(session: NIDSessionEventName, f: String? = nil, siteId: String? = nil, sid: String? = nil, lsid: String? = nil, cid: String? = nil, did: String? = nil, iid: String? = nil, loc: String? = nil, ua: String? = nil, tzo: Int? = nil, lng: String? = nil, p: String? = nil, dnt: Bool? = nil, tch: Bool? = nil, url: String? = nil, ns: String? = nil, jsv: String? = nil) { self.type = session.rawValue self.f = f self.siteId = siteId self.sid = sid self.lsid = lsid self.cid = cid self.did = did self.iid = iid self.loc = loc self.ua = ua self.tzo = tzo self.lng = lng self.p = p self.dnt = dnt self.tch = tch self.url = url self.ns = ns self.jsv = jsv } /** Register Target {"type":"REGISTER_TARGET","tgs":"#happyforms_message_nonce","en":"happyforms_message_nonce","eid":"happyforms_message_nonce","ec":"","etn":"INPUT","et":"hidden","ef":null,"v":"S~C~~10","ts":1633972363470} ET - Submit, Blank, Hidden */ init(eventName: NIDEventName, tgs: String, en: String, etn: String, et: String, v: String) { self.type = eventName.rawValue self.tgs = tgs; self.en = en; self.eid = tgs; var ec = ""; self.etn = etn; self.et = et; var ef:Any = Optional<String>.none; self.v = v; } /** Primary View Controller will be the URL that we are tracking. */ public init(type: NIDEventName, tg: [String: TargetValue]?, primaryViewController: UIViewController?, view: UIView?) { self.type = type.rawValue var newTg = tg ?? [String: TargetValue]() newTg["tgs"] = TargetValue.string(view != nil ? view!.id : "") self.tg = newTg self.url = primaryViewController?.className self.x = view?.frame.origin.x self.y = view?.frame.origin.y } init(session: NIDSessionEventName, tg: [String: TargetValue]?, x: CGFloat?, y: CGFloat?) { type = session.rawValue self.tg = tg self.x = x self.y = y } /** Set UserID Event */ init(session: NIDSessionEventName, uid: String){ self.uid = uid self.type = session.rawValue } init(type: NIDEventName, tg: [String: TargetValue]?, x: CGFloat?, y: CGFloat?) { self.type = type.rawValue self.tg = tg self.x = x self.y = y } init(customEvent: String, tg: [String: TargetValue]?, x: CGFloat?, y: CGFloat?) { self.type = customEvent self.tg = tg self.x = x self.y = y } /** FOCUS BLUR */ public init(type: NIDEventName, tg: [String: TargetValue]?) { self.type = type.rawValue self.tg = tg } public init(type: NIDEventName, tg: [String: TargetValue]?, view: UIView?) { self.type = type.rawValue var newTg = tg ?? [String: TargetValue]() newTg["tgs"] = TargetValue.string(view != nil ? view!.id : "") self.tg = newTg self.url = view?.className self.x = view?.frame.origin.x self.y = view?.frame.origin.y } // public init(customEvent: String, tg: [String: TargetValue]?, view: UIView?) { // type = customEvent // var newTg = tg ?? [String: TargetValue]() // newTg["tgs"] = TargetValue.string(view != nil ? view!.id : "") // self.tg = newTg // self.x = view?.frame.origin.x // self.y = view?.frame.origin.y // } var asDictionary : [String:Any] { let mirror = Mirror(reflecting: self) let dict = Dictionary(uniqueKeysWithValues: mirror.children.lazy.map({ (label:String?, value:Any) -> (String, Any)? in guard let label = label else { return nil } return (label, value) }).compactMap { $0 }) return dict } func toDict() -> [String: Any?] { let valuesAsDict = self.asDictionary; return valuesAsDict } func toBase64() -> String? { // Filter and remove any nil optionals let dict = toDict().filter({ $0.value != nil }).mapValues({ $0! }) do { let data = try JSONSerialization.data(withJSONObject: dict, options: .fragmentsAllowed) let base64 = data.base64EncodedString() return base64 } catch let error { NIDPrintLog("Encode event", dict, "to base64 failed with error", error) return nil } } } extension Array { func toBase64() -> String? { do { let data = try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed) let base64 = data.base64EncodedString() return base64 } catch let error { NIDPrintLog("Encode event", self, "to base64 failed with error", error) return nil } } } extension Collection where Iterator.Element == [String: Any?] { func toJSONString() -> String { if let arr = self as? [[String: Any?]], let dat = try? JSONSerialization.data(withJSONObject: arr), let str = String(data: dat, encoding: String.Encoding.utf8) { return str } return "[]" } } extension Collection where Iterator.Element == NIDEvent { func toArrayOfDicts() -> [[String: Any?]] { let dat = self.map({ $0.asDictionary.mapValues { value in return value } }) return dat } }
30.014963
207
0.565969
e992a9289ac2594b6fd3512c0e64f9626ced8215
9,869
//===--- main.swift -------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // This is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySetElement import ArraySubscript import BinaryFloatingPointConversionFromBinaryInteger import BinaryFloatingPointProperties import BitCount import Breadcrumbs import ByteSwap import COWTree import COWArrayGuaranteedParameterOverhead import CString import CSVParsing import Calculator import CaptureProp import ChainedFilterMap import CharacterLiteralsLarge import CharacterLiteralsSmall import CharacterProperties import Chars import ClassArrayGetter import Codable import Combos import DataBenchmarks import DeadArray import DictOfArraysToArrayOfDicts import DictTest import DictTest2 import DictTest3 import DictTest4 import DictTest4Legacy import DictionaryBridge import DictionaryBridgeToObjC import DictionaryCompactMapValues import DictionaryCopy import DictionaryGroup import DictionaryKeysContains import DictionaryLiteral import DictionaryOfAnyHashableStrings import DictionaryRemove import DictionarySubscriptDefault import DictionarySwap import Diffing import DropFirst import DropLast import DropWhile import ErrorHandling import Exclusivity import ExistentialPerformance import Fibonacci import FlattenList import FloatingPointPrinting import Hanoi import Hash import Histogram import InsertCharacter import Integrate import IterateData import Join import LazyFilter import LinkedList import LuhnAlgoEager import LuhnAlgoLazy import MapReduce import Memset import MonteCarloE import MonteCarloPi import Myers import NibbleSort import NSDictionaryCastToSwift import NSError import NSStringConversion import NopDeinit import ObjectAllocation #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import ObjectiveCBridging import ObjectiveCBridgingStubs #if !(SWIFT_PACKAGE || Xcode) import ObjectiveCNoBridgingStubs #endif #endif import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpaqueConsumingUsers import OpenClose import Phonebook import PointerArithmetics import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import PrimsSplit import ProtocolDispatch import ProtocolDispatch2 import Queue import RC4 import RGBHistogram import Radix2CooleyTukey import RandomShuffle import RandomValues import RangeAssignment import RangeIteration import RangeOverlaps import RangeReplaceableCollectionPlusDefault import RecursiveOwnedParameter import ReduceInto import RemoveWhere import ReversedCollections import RomanNumbers import SequenceAlgos import SetTests import SevenBoom import Sim2DArray import SortIntPyramids import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringComparison import StringEdits import StringEnum import StringInterpolation import StringMatch import StringRemoveDupes import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import WordCount import XorLoop @inline(__always) private func registerBenchmark(_ bench: BenchmarkInfo) { registeredBenchmarks.append(bench) } @inline(__always) private func registerBenchmark< S : Sequence >(_ infos: S) where S.Element == BenchmarkInfo { registeredBenchmarks.append(contentsOf: infos) } registerBenchmark(Ackermann) registerBenchmark(AngryPhonebook) registerBenchmark(AnyHashableWithAClass) registerBenchmark(Array2D) registerBenchmark(ArrayAppend) registerBenchmark(ArrayInClass) registerBenchmark(ArrayLiteral) registerBenchmark(ArrayOfGenericPOD) registerBenchmark(ArrayOfGenericRef) registerBenchmark(ArrayOfPOD) registerBenchmark(ArrayOfRef) registerBenchmark(ArraySetElement) registerBenchmark(ArraySubscript) registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger) registerBenchmark(BinaryFloatingPointPropertiesBinade) registerBenchmark(BinaryFloatingPointPropertiesNextUp) registerBenchmark(BinaryFloatingPointPropertiesUlp) registerBenchmark(BitCount) registerBenchmark(Breadcrumbs) registerBenchmark(ByteSwap) registerBenchmark(COWTree) registerBenchmark(COWArrayGuaranteedParameterOverhead) registerBenchmark(CString) registerBenchmark(CSVParsing) registerBenchmark(CSVParsingAlt) registerBenchmark(CSVParsingAltIndices) registerBenchmark(Calculator) registerBenchmark(CaptureProp) registerBenchmark(ChainedFilterMap) registerBenchmark(CharacterLiteralsLarge) registerBenchmark(CharacterLiteralsSmall) registerBenchmark(CharacterPropertiesFetch) registerBenchmark(CharacterPropertiesStashed) registerBenchmark(CharacterPropertiesStashedMemo) registerBenchmark(CharacterPropertiesPrecomputed) registerBenchmark(Chars) registerBenchmark(Codable) registerBenchmark(Combos) registerBenchmark(ClassArrayGetter) registerBenchmark(DataBenchmarks) registerBenchmark(DeadArray) registerBenchmark(DictOfArraysToArrayOfDicts) registerBenchmark(Dictionary) registerBenchmark(Dictionary2) registerBenchmark(Dictionary3) registerBenchmark(Dictionary4) registerBenchmark(Dictionary4Legacy) registerBenchmark(DictionaryBridge) registerBenchmark(DictionaryBridgeToObjC) registerBenchmark(DictionaryCompactMapValues) registerBenchmark(DictionaryCopy) registerBenchmark(DictionaryGroup) registerBenchmark(DictionaryKeysContains) registerBenchmark(DictionaryLiteral) registerBenchmark(DictionaryOfAnyHashableStrings) registerBenchmark(DictionaryRemove) registerBenchmark(DictionarySubscriptDefault) registerBenchmark(DictionarySwap) registerBenchmark(Diffing) registerBenchmark(DropFirst) registerBenchmark(DropLast) registerBenchmark(DropWhile) registerBenchmark(ErrorHandling) registerBenchmark(Exclusivity) registerBenchmark(ExistentialPerformance) registerBenchmark(Fibonacci) registerBenchmark(FlattenListLoop) registerBenchmark(FlattenListFlatMap) registerBenchmark(FloatingPointPrinting) registerBenchmark(Hanoi) registerBenchmark(HashTest) registerBenchmark(Histogram) registerBenchmark(InsertCharacter) registerBenchmark(IntegrateTest) registerBenchmark(IterateData) registerBenchmark(Join) registerBenchmark(LazyFilter) registerBenchmark(LinkedList) registerBenchmark(LuhnAlgoEager) registerBenchmark(LuhnAlgoLazy) registerBenchmark(MapReduce) registerBenchmark(Memset) registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(Myers) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) registerBenchmark(NSStringConversion) registerBenchmark(NibbleSort) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) #if !(SWIFT_PACKAGE || Xcode) registerBenchmark(ObjectiveCNoBridgingStubs) #endif #endif registerBenchmark(ObserverClosure) registerBenchmark(ObserverForwarderStruct) registerBenchmark(ObserverPartiallyAppliedMethod) registerBenchmark(ObserverUnappliedMethod) registerBenchmark(OpaqueConsumingUsers) registerBenchmark(OpenClose) registerBenchmark(Phonebook) registerBenchmark(PointerArithmetics) registerBenchmark(PolymorphicCalls) registerBenchmark(PopFront) registerBenchmark(PopFrontArrayGeneric) registerBenchmark(Prefix) registerBenchmark(PrefixWhile) registerBenchmark(Prims) registerBenchmark(PrimsSplit) registerBenchmark(ProtocolDispatch) registerBenchmark(ProtocolDispatch2) registerBenchmark(QueueGeneric) registerBenchmark(QueueConcrete) registerBenchmark(RC4Test) registerBenchmark(RGBHistogram) registerBenchmark(Radix2CooleyTukey) registerBenchmark(RandomShuffle) registerBenchmark(RandomValues) registerBenchmark(RangeAssignment) registerBenchmark(RangeIteration) registerBenchmark(RangeOverlaps) registerBenchmark(RangeReplaceableCollectionPlusDefault) registerBenchmark(RecursiveOwnedParameter) registerBenchmark(ReduceInto) registerBenchmark(RemoveWhere) registerBenchmark(ReversedCollections) registerBenchmark(RomanNumbers) registerBenchmark(SequenceAlgos) registerBenchmark(SetTests) registerBenchmark(SevenBoom) registerBenchmark(Sim2DArray) registerBenchmark(SortIntPyramids) registerBenchmark(SortLargeExistentials) registerBenchmark(SortLettersInPlace) registerBenchmark(SortStrings) registerBenchmark(StackPromo) registerBenchmark(StaticArrayTest) registerBenchmark(StrComplexWalk) registerBenchmark(StrToInt) registerBenchmark(StringBuilder) registerBenchmark(StringComparison) registerBenchmark(StringEdits) registerBenchmark(StringEnum) registerBenchmark(StringHashing) registerBenchmark(StringInterpolation) registerBenchmark(StringInterpolationSmall) registerBenchmark(StringInterpolationManySmallSegments) registerBenchmark(StringMatch) registerBenchmark(StringNormalization) registerBenchmark(StringRemoveDupes) registerBenchmark(StringTests) registerBenchmark(StringWalk) registerBenchmark(SubstringTest) registerBenchmark(Suffix) registerBenchmark(SuperChars) registerBenchmark(TwoSum) registerBenchmark(TypeFlood) registerBenchmark(UTF8Decode) registerBenchmark(Walsh) registerBenchmark(WordCount) registerBenchmark(XorLoop) main()
28.277937
80
0.880434
fe7c0baec09d02fe6f76c23d28d2dbf3c0ed39c1
102
for loop in 1 ... 5 { moveForward() turnLeft() moveForward() moveForward() collectGem() turnRight() }
11.333333
21
0.696078
1cbd763d6e46c9a7f3918863e50cc34ae4d00633
16,034
// // MGNetworkUtils.swift // MGUtilsSwift // // Created by Magical Water on 2018/9/29. // Copyright © 2018年 Magical Water. All rights reserved. // import Foundation import UIKit import CoreServices public class MGNetworkUtils: NSObject { public override init() { super.init() } public static var share: MGNetworkUtils { return MGNetworkUtils() } private var downloadSessionConfig: URLSessionConfiguration = { let configiguration = URLSessionConfiguration.default configiguration.timeoutIntervalForRequest = .infinity return configiguration }() private lazy var downloadSession: URLSession = { //當 delegateQueue 沒有設置時,session会创建一个串行隊列,並且在該隊列中執行操作 return URLSession(configuration: downloadSessionConfig, delegate: self, delegateQueue: nil) }() //儲存正在下載的task request, 對應要下載到的目錄位置 private var donwloadingTask: [URLRequest : (URL, URLSessionDownloadTask)] = [:] public enum Method: String { case get = "GET" case post = "POST" } /* GET 異步獲取 */ public func get(url: URL, params: [String : Any]?, paramEncoding: MGParamEncoding, headers: [String : String]?, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { do { let request = try generateRequest(url: url, params: params, paramEncoding: paramEncoding, headers: headers, method: .get) executeRequest(request: request, completeHandler: completeHandler) } catch { let response = MGNetworkResponse.init(data: nil, statusCode: nil, responseHeaders: nil, error: error) completeHandler?(response) } } /* POST 異步獲取 */ public func post(url: URL, params: [String : Any]?, paramEncoding: MGParamEncoding, headers: [String : String]?, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { do { let request = try generateRequest(url: url, params: params, paramEncoding: paramEncoding, headers: headers, method: .post) executeRequest(request: request, completeHandler: completeHandler) } catch { let response = MGNetworkResponse.init(data: nil, statusCode: nil, responseHeaders: nil, error: error) completeHandler?(response) } } /* 上傳 使用 POST */ public func upload(url: URL, datas: [MGNetworkUploadData], params: [String : Any]?, paramEncoding: MGParamEncoding, headers: [String : String]?, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { let requestPair = generateUploadRequest(url: url, datas: datas, params: params, headers: headers) executeUploadRequest(request: requestPair.0, data: requestPair.1) } /* 下載 使用 GET */ public func download(url: URL, destination: URL, params: [String : Any]?, headers: [String : String]?, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { let request = generateDownloadRequest(url: url, params: params, headers: headers) executeDownloadRequest(request: request, destination: destination, completeHandler: completeHandler) } private func handleResponse(data: Data?, response: URLResponse?, error: Error?) -> MGNetworkResponse { if let httpResponse = response as? HTTPURLResponse { let statusCode: Int? = httpResponse.statusCode let headers = httpResponse.allHeaderFields return MGNetworkResponse.init(data: data, statusCode: statusCode, responseHeaders: headers, error: error) } else { return MGNetworkResponse.init(data: data, statusCode: nil, responseHeaders: nil, error: error) } } } //生成 URLRequest 實例 extension MGNetworkUtils { //取得一般資料的 URLRequest 實例 private func generateRequest(url: URL, params: [String : Any]?, paramEncoding: MGParamEncoding, headers: [String : String]?, method: Method) throws -> URLRequest { var request = URLRequest.init(url: url) request.httpMethod = method.rawValue setHeader(request: &request, headers: headers) guard let params = params else { return request } try paramEncoding.encode(request: &request, params: params, method: method) return request } //取得上傳檔案的 URLRequest 實例 private func generateUploadRequest(url: URL, datas: [MGNetworkUploadData], params: [String : Any]?, headers: [String : String]?) -> (URLRequest, Data) { var request = URLRequest.init(url: url) request.httpMethod = Method.post.rawValue setHeader(request: &request, headers: headers) //有看到另外一個人寫法是這樣, 但不清楚是否都可以, 因此保留 // let boundary = "Boundary+\(arc4random())\(arc4random())" let boundary = String(format: "boundary.%08x%08x", arc4random(), arc4random()) let contentType = "multipart/form-data; boundary=\(boundary)" request.setValue(contentType, forHTTPHeaderField: "Content-Type") //將上傳的 檔案 與 參數 包裝成 Data let data = combinationData(boundary: boundary, datas: datas, params: params) return (request, data) } //取得下載檔案的 URLRequest 實例 private func generateDownloadRequest(url: URL, params: [String : Any]?, headers: [String : String]?) -> URLRequest { var request = URLRequest.init(url: url) request.httpMethod = Method.get.rawValue setHeader(request: &request, headers: headers) guard let params = params else { return request } try! MGURLEncoding.default.encode(request: &request, params: params, method: .get) return request } } //處理參數 extension MGNetworkUtils { //設置要求頭 func setHeader(request: inout URLRequest, headers: [String : String]?) { if let headers = headers { for (headerField, headerValue) in headers { request.setValue(headerValue, forHTTPHeaderField: headerField) } } } //傳入參數, 轉為參數字串 static func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } //傳入參數, 平鋪所有key以及對應的參數 static func queryDictionary(_ parameters: [String: Any]) -> [String : String] { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } var maps: [String:String] = [:] components.forEach { maps[$0.0] = $0.1 } return maps } /* 傳入某個key與對應的value, 平鋪此key下的所有的參數 */ private static func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { //value是個字典, 需要再繼續往下循環調用此方法取出平鋪的參數 for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { //value是個陣列, 依照陣列的顯示方式, 將key後面加上順序Index - [0] [1]..., 之後往下循環調用取出平鋪的參數 for i in 0..<array.count { components += queryComponents(fromKey: "\(key)[\(i)]", value: array[i]) } } else if let value = value as? NSNumber { //value是數字相關的值 components.append((escape(key), escape("\(value)"))) } else if let bool = value as? Bool { //value是布爾相關的值 components.append((escape(key), escape("\(bool)"))) } else { //value不再上列(直接轉成字串) components.append((escape(key), escape("\(value)"))) } return components } /* 這邊參考 alamofire 加入參數時對字串的處理, 具體如何還不清楚, 因此此段說明暫先保留 */ /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. private static func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") let escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string return escaped } } //處理上傳檔案的資料 extension MGNetworkUtils { //換行符號, 上傳檔案的參數與檔案需要按照一定格式 private var crlf: String { return "\r\n" } enum UploadError: Error { case noSupportUrl //暫時不支援url上傳 case noMatchType //沒有找到可以處理的類型 var localizedDescription: String { switch self { case .noMatchType: return "上傳檔案出錯 - 沒有找到對應的類型" case .noSupportUrl: return "上傳檔案出錯 - 暫時不支援 url" } } } //將上傳檔案需要帶入的參數與檔案包裝成Data private func combinationData(boundary: String, datas: [MGNetworkUploadData], params: [String : Any]?) -> Data { //使用 Data 裝載參數以及檔案 var body = Data() //處理參數加入 if let params = params { for (paramKey, paramValue) in params { body.append(string: "--\(boundary)\(crlf)") body.append(string: "Content-Disposition: form-data; name=\"\(paramKey)\"\(crlf)\(crlf)") body.append(string: "\(paramValue)\(crlf)") } } //處理上傳的文件 for uploadData in datas { body.append(string: "--\(boundary)\(crlf)") body.append(string: "Content-Disposition: form-data; name=\"\(uploadData.name)\"; filename=\"\(uploadData.fileName)\"\(crlf)") do { let dataPart = try convertData(data: uploadData.data) if let mimeType = dataPart.1 { body.append(string: "Content-Type: \(mimeType)\(crlf)\(crlf)") } body.append(dataPart.0) } catch { print("\(error.localizedDescription)") } body.append(string: "\(crlf)") } body.append(string: "--\(boundary)--\r\n") return body } //傳入一個資料, 自動將其轉換成可上傳的類型以及mimetype private func convertData(data: Any) throws -> (Data,String?) { if let data = data as? Data { return (data, nil) } else if let img = data as? UIImage { //這邊自動將圖片壓縮為jpg let jpegData = img.jpegData(compressionQuality: 1.0)! return (jpegData, "image/jpg") } else if let string = data as? String { //若是一個字串, 則應該轉為 data let stringData = string.data(using: .utf8)! return (stringData, nil) } else if let _ = data as? URL { //上傳的 url 必須是一個 fileURL, 後續步驟過於複雜, 這邊暫時不加入 throw UploadError.noSupportUrl } //沒找到對應的類型 throw UploadError.noMatchType } //根據 url 的尾端 extesion 判斷 mineType private func mimeType(forPathExtension pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } } //處理下載相關回調 extension MGNetworkUtils: URLSessionDownloadDelegate { //下載完成回傳通知 public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let requst = downloadTask.currentRequest, let downloadPair = donwloadingTask[requst] { //系統默認下載位置 // print("系統默認下載位置: \(location)") //移動到目地位置 let fileMaanager = FileManager.default do { try fileMaanager.moveItem(at: location, to: downloadPair.0) } catch { print("下載檔案後, 移動過程出現錯誤: \(error.localizedDescription)") } // print("移動完畢: \(downloadPair.0)") } } //在此監控進度 public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite) print(progress) } } //執行任務 extension MGNetworkUtils { //執行一般 request, 使用獲取資料的 URLSession private func executeRequest(request: URLRequest, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { let getTask = URLSession.shared.dataTask(with: request) { data, response, error in let connectResponse = self.handleResponse(data: data, response: response, error: error) completeHandler?(connectResponse) // if let connectResponse = self.handleResponse(data: data, response: response, error: error) { // completeHandler?(connectResponse) // } } getTask.resume() } //執行下載任務 private func executeDownloadRequest(request: URLRequest, destination: URL, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { let downloadTask = downloadSession.downloadTask(with: request) { fileURL, response, error in self.donwloadingTask.removeValue(forKey: request) let connectResponse = self.handleResponse(data: nil, response: response, error: error) completeHandler?(connectResponse) // if let connectResponse = self.handleResponse(data: nil, response: response, error: error) { // completeHandler?(connectResponse) // } } donwloadingTask[request] = (destination, downloadTask) downloadTask.resume() } //執行上傳任務 private func executeUploadRequest(request: URLRequest, data: Data, completeHandler: ((MGNetworkResponse) -> Void)? = nil) { let uploadTask = URLSession.shared.uploadTask(with: request, from: data) { data, response, error in let connectResponse = self.handleResponse(data: data, response: response, error: error) completeHandler?(connectResponse) // if let connectResponse = self.handleResponse(data: data, response: response, error: error) { // completeHandler?(connectResponse) // } } uploadTask.resume() } } //上傳檔案時, 讓 Data 可以直接傳入字串 public extension Data{ mutating func append(string: String) { let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) append(data!) } }
37.462617
173
0.596981
f567d92c6e1d0c21bf8776010c9c24640a8142a6
2,285
import CLibMongoC /// Internal intermediate result of a ListIndexes command. internal enum ListIndexesResults { /// Includes the name, keys, and creation options of each index. case models(MongoCursor<IndexModel>) /// Only includes the names. case names([String]) } /// An operation corresponding to a "listIndexes" command on a collection. internal struct ListIndexesOperation<T: Codable>: Operation { private let collection: MongoCollection<T> private let nameOnly: Bool internal init(collection: MongoCollection<T>, nameOnly: Bool) { self.collection = collection self.nameOnly = nameOnly } internal func execute( using connection: Connection, session: ClientSession? ) throws -> ListIndexesResults { let opts = try encodeOptions(options: nil as BSONDocument?, session: session) let indexes: OpaquePointer = self.collection.withMongocCollection(from: connection) { collPtr in withOptionalBSONPointer(to: opts) { optsPtr in guard let indexes = mongoc_collection_find_indexes_with_opts(collPtr, optsPtr) else { fatalError(failedToRetrieveCursorMessage) } return indexes } } if self.nameOnly { let cursor = try Cursor( mongocCursor: MongocCursor(referencing: indexes), connection: connection, session: session, type: .nonTailable ) defer { cursor.kill() } var names: [String] = [] while let nextDoc = try cursor.tryNext() { guard let name = nextDoc["name"]?.stringValue else { throw MongoError.InternalError(message: "Invalid server response: index has no name") } names.append(name) } return .names(names) } let cursor: MongoCursor<IndexModel> = try MongoCursor( stealing: indexes, connection: connection, client: self.collection._client, decoder: self.collection.decoder, eventLoop: self.collection.eventLoop, session: session ) return .models(cursor) } }
34.621212
105
0.603939
09f11e311ea25bd24af47c60dd68656fa6fd71c5
2,105
// // ExternalViewModel.swift // PrimerSDK // // Created by Carl Eriksson on 16/01/2021. // #if canImport(UIKit) import Foundation internal protocol ExternalViewModelProtocol { func fetchVaultedPaymentMethods(_ completion: @escaping (Result<[PaymentMethodToken], Error>) -> Void) } internal class ExternalViewModel: ExternalViewModelProtocol { deinit { log(logLevel: .debug, message: "🧨 deinit: \(self) \(Unmanaged.passUnretained(self).toOpaque())") } func fetchVaultedPaymentMethods(_ completion: @escaping (Result<[PaymentMethodToken], Error>) -> Void) { let state: AppStateProtocol = DependencyContainer.resolve() if state.decodedClientToken.exists { let vaultService: VaultServiceProtocol = DependencyContainer.resolve() vaultService.loadVaultedPaymentMethods({ err in if let err = err { completion(.failure(err)) } else { let paymentMethods = state.paymentMethods completion(.success(paymentMethods)) } }) } else { let clientTokenService: ClientTokenServiceProtocol = DependencyContainer.resolve() clientTokenService.fetchClientToken({ err in if let err = err { completion(.failure(err)) } else { let vaultService: VaultServiceProtocol = DependencyContainer.resolve() vaultService.loadVaultedPaymentMethods({ err in if let err = err { completion(.failure(err)) } else { let paymentMethods = state.paymentMethods completion(.success(paymentMethods)) } }) } }) } } } internal class MockExternalViewModel: ExternalViewModelProtocol { func fetchVaultedPaymentMethods(_ completion: @escaping (Result<[PaymentMethodToken], Error>) -> Void) { } } #endif
33.412698
108
0.577672
46386c37286b21e121bb22f56a5e65666d801f08
21,446
// // Requests.swift // DisruptiveAPI // // Created by Vegard Solheim Theriault on 23/05/2020. // Copyright © 2020 Disruptive Technologies Research AS. All rights reserved. // import Foundation internal struct Request { let method: HTTPMethod let baseURL: String let endpoint: String private(set) var headers: [HTTPHeader] var params: [String: [String]] let body: Data? init( method: HTTPMethod, baseURL: String, endpoint: String, headers: [HTTPHeader] = [], params: [String: [String]] = [:]) { self.method = method self.baseURL = baseURL self.endpoint = endpoint self.headers = headers self.params = params self.body = nil } init<Body: Encodable>( method: HTTPMethod, baseURL: String, endpoint: String, headers: [HTTPHeader] = [], params: [String: [String]] = [:], body: Body) throws { self.headers = headers // If the body is already of type `Data`, just set it directly. // Otherwise, JSON encode it. if let body = body as? Data { self.body = body } else { self.body = try JSONEncoder().encode(body) self.headers.append(HTTPHeader(field: "Content-Type", value: "application/json")) } self.baseURL = baseURL self.method = method self.endpoint = endpoint self.params = params } /// Overrides an existing header if it already exists, otherwise creates a new header. mutating func setHeader(field: String, value: String) { let newHeader = HTTPHeader(field: field, value: value) // Update the existing header if it already exists for (index, header) in headers.enumerated() { if header.field == field { headers[index] = newHeader return } } // Create a new header headers.append(newHeader) } /** Creates a `URLRequest` object from the `Request` properties. Sets the HTTP method, query parameters, headers, and body of the `URLRequest`. */ func urlRequest() -> URLRequest? { // Construct the URL guard var urlComponents = URLComponents(string: baseURL + endpoint) else { return nil } if params.count > 0 { urlComponents.queryItems = params.flatMap { paramName, paramValues in return paramValues.map { URLQueryItem(name: paramName, value: $0) } } } guard let url = urlComponents.url(relativeTo: nil) else { return nil } // Create the request var req = URLRequest(url: url) req.httpMethod = method.rawValue req.httpBody = body // Add the headers headers.forEach { req.addValue($0.value, forHTTPHeaderField: $0.field) } return req } } extension Request { /// Creates a URL session with a 20 second timeout. static var defaultSession: URLSession = { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 20 config.timeoutIntervalForResource = 20 return URLSession(configuration: config) }() // ------------------------------- // MARK: Sending Requests // ------------------------------- /// Use this instead of `Void` as a generic parameter (the `T`) for the `send` function since `Void` cannot be `Decodable`. internal struct EmptyResponse: Decodable {} /** Sends the request to the Disruptive backend. This function does not handle authentications, so it's expected that the `Authorization` header is already populated (if necessary). If a "429 Too Many Requests" error is received, the request will be re-sent after waiting the appropriate amount of time. If an empty response is expected (eg. `Void`), use the `EmptyResponse` type as the generic success type, and just replace it with `Void` if the request was successful. - Parameter decoder: If some custom decoding is required (eg. pagination), this default decoder can be replaced with a custom one. */ internal func send<T: Decodable>(decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, DisruptiveError>) -> ()) { guard let urlReq = urlRequest() else { Disruptive.log("Failed to create URLRequest from request: \(self)", level: .error) DispatchQueue.main.async { completion(.failure(.unknownError)) } return } var diagnostics = RequestDiagnostics(request: self) diagnostics.setNetworkStart() let task = Request.defaultSession.dataTask(with: urlReq) { data, response, error in diagnostics.setNetworkEnd() let urlString = urlReq.url!.absoluteString // Check the response for any errors if let internalError = Request.checkResponseForErrors( forRequestURL: urlString, response: response, data: data, error: error) { // If this error can be converted to a disruptive error if let dtErr = internalError.disruptiveError() { Disruptive.log("Request to \(urlString) resulted in error: \(dtErr)", level: .error) DispatchQueue.main.async { completion(.failure(dtErr)) } return } // Check if we've been rate limited if case .tooManyRequests(let retryAfter) = internalError { Disruptive.log("Request got rate limited, waiting \(retryAfter) seconds before retrying", level: .warning) // Dispatch the same request again after waiting DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(retryAfter)) { self.send(decoder: decoder, completion: completion) } return } // Unhandled error // All types of errors should have been handled above, so this // should never happen. This is here as a fallback in case new // types of errors are added in the future. Disruptive.log("The internal error \(internalError) was not handled for \(urlString)", level: .error) DispatchQueue.main.async { completion(.failure(.unknownError)) } return } // If the caller has requested a success type of `EmptyResponse`, just response // with an `EmptyResponse` value without doing any parsing of the received payload. // This is done instead of responding with `Void` because `Void` does not conform // to the `Decodable` protocol if T.self == EmptyResponse.self { diagnostics.logDiagnostics(responseData: nil) DispatchQueue.main.async { completion(.success(EmptyResponse() as! T)) } return } diagnostics.setParseStart() // Parse the returned data guard let result: T = Request.parsePayload(data, decoder: decoder) else { DispatchQueue.main.async { Disruptive.log("Failed to parse the response JSON from \(urlString)", level: .error) completion(.failure(.unknownError)) } return } diagnostics.setParseEnd() diagnostics.logDiagnostics(responseData: data) DispatchQueue.main.async { completion(.success(result)) } } task.resume() } // ------------------------------- // MARK: Error Checking // ------------------------------- /// A standardized error body from the Disruptive backend private struct ErrorMessage: Decodable { let error: String let code: Int let help: String } internal static func checkResponseForErrors( forRequestURL url: String, response: URLResponse?, data: Data?, error: Error?) -> InternalError? { // Check if there is an error (server probably not accessible) if let error = error { Disruptive.log("Request: \(url) resulted in error: \(error) (code: \(String(describing: (error as? URLError)?.code))), response: \(String(describing: response))", level: .error) return .serverUnavailable } // Cast response to HTTPURLResponse guard let httpResponse = response as? HTTPURLResponse else { Disruptive.log("Request: \(url) resulted in HTTP Error: \(String(describing: error)). Response: \(String(describing: response))", level: .error) return .unknownError } // Check if the status code is outside the 2XX range guard httpResponse.statusCode >= 200 && httpResponse.statusCode < 300 else { // Decode the ErrorMessage body (if it's there) var message: ErrorMessage? if let data = data { message = try? JSONDecoder().decode(ErrorMessage.self, from: data) } // Log the error if let msg = message { Disruptive.log("Received status code \(httpResponse.statusCode) from the backend with message: \(msg)", level: .error) } else { Disruptive.log("Received status code \(httpResponse.statusCode) from the backend", level: .error) } switch httpResponse.statusCode { case 400: return .badRequest case 401: return .unauthorized case 403: return .forbidden case 404: return .notFound case 409: return .conflict case 500: return .internalServerError case 501: return .serviceUnavailable case 503: return .gatewayTimeout case 429: // Read "Retry-After" header for how long we need to wait // Default to 5 seconds if not present let retryAfterStr = httpResponse.value(forHTTPHeaderField: "Retry-After") ?? "5" let retryAfter = Int(retryAfterStr) ?? 5 return .tooManyRequests(retryAfter: retryAfter) default: Disruptive.log("Unexpected status code: \(httpResponse.statusCode)", level: .error) return .unknownError } } return nil } // ------------------------------- // MARK: Parsing Payload // ------------------------------- internal static func parsePayload<T: Decodable>(_ payload: Data?, decoder: JSONDecoder) -> T? { // Unwrap payload guard let payload = payload else { Disruptive.log("Didn't get a body in the response as expected", level: .error) return nil } // Decode the payload do { return try decoder.decode(T.self, from: payload) } catch { // Failed to decode payload if let str = String(data: payload, encoding: .utf8) { Disruptive.log("Failed to parse JSON: \(str)", level: .error) Disruptive.log("Error: \(error)", level: .error) } else { Disruptive.log("Failed to parse payload data: \(payload)", level: .error) } return nil } } } // ------------------------------- // MARK: Disruptive Extension (Send Requests) // // Adds three convenience functions to `Disruptive` to both ensure that // the request gets authenticated before being sent, as well as properly // handling the three types of requests: no response payload, single response // payload, and paginated response payload. // ------------------------------- extension Disruptive { /// If the auth provider is already authenticated, and the expiration date is far enough /// away, this will succeed with the `Authorization` header set to the auth token. /// If the auth provider is not authenticated, private func authenticateRequest( _ request: Request, completion: @escaping (Result<Request, DisruptiveError>) -> ()) { authenticator.getActiveAccessToken { result in switch result { case .success(let token): var req = request req.setHeader(field: "Authorization", value: token) completion(.success(req)) case .failure(let e): completion(.failure(e)) } } } /// Makes sure the `authenticator` is authenticated, and adds the `Authorization` header to /// the request before sending it. This will not return anything if successful, but it will return a /// `DisruptiveError` on failure. internal func sendRequest( _ request: Request, completion: @escaping (Result<Void, DisruptiveError>) -> ()) { // Create a new request with a non-expired access token // in the `Authorization` header. authenticateRequest(request) { authResult in switch authResult { case .success(let req): // Send the request to the Disruptive endpoint // Switch out the `EmptyResponse` payload with `Void` (aka "()") req.send { (response: Result<Request.EmptyResponse, DisruptiveError>) in switch response { case .success: completion(.success(())) case .failure(let err): completion(.failure(err)) } } case .failure(let err): completion(.failure(err)) } } } /// Makes sure the `authenticator` is authenticated, and adds the `Authorization` header to /// the request before sending it. This will return a single value if successful, and a /// `DisruptiveError` on failure. internal func sendRequest<T: Decodable>( _ request: Request, completion: @escaping (Result<T, DisruptiveError>) -> ()) { // Create a new request with a non-expired access token // in the `Authorization` header. authenticateRequest(request) { authResult in switch authResult { case .success(let req): // Send the request to the Disruptive endpoint req.send { completion($0) } case .failure(let err): completion(.failure(err)) } } } /// Makes sure the `authenticator` is authenticated, and adds the `Authorization` header to /// the request before sending it. This will return a one page of results if successful, and a /// `DisruptiveError` on failure. internal func sendRequest<T: Decodable>( _ request : Request, pageSize : Int, pageToken : String?, pagingKey : String, completion : @escaping (Result<PagedResult<T>, DisruptiveError>) -> ()) { // Set the pagination query parameters var req = request req.params["page_size"] = [String(pageSize)] if let pageToken = pageToken { req.params["page_token"] = [String(pageToken)] } // Prepare a JSON decoder for decoding paged results let decoder = pagingJSONDecoder(pagingKey: pagingKey) // Create a new request with a non-expired access token // in the `Authorization` header. authenticateRequest(req) { authResult in switch authResult { case .success(let req): req.send(decoder: decoder) { completion($0) } case .failure(let err): completion(.failure(err)) } } } /// Makes sure the `authenticator` is authenticated, and adds the `Authorization` header to /// the request before sending it. This expects a list of paginated items to be returned, and fetches /// all the available pages before returning. internal func sendRequest<T: Decodable>( _ request: Request, pagingKey: String, completion: @escaping (Result<[T], DisruptiveError>) -> ()) { // Prepare a decoder for decoding paginated results let decoder = pagingJSONDecoder(pagingKey: pagingKey) // Recursive function to fetch all the pages as long as `nextPageToken` is set. // The structure of this is a bit unfortunate due to having multiple nested // function calls that takes a completion closure. This can be improved once // Swift gains support for async/await. // More details here: https://gist.github.com/lattner/429b9070918248274f25b714dcfc7619 func fetchPages( request: Request, cumulativeResults: [T], pageingKey: String, completion: @escaping (Result<[T], DisruptiveError>) -> ()) { // Create a new request with a non-expired access token // in the `Authorization` header. authenticateRequest(request) { authResult in switch authResult { case .success(let req): // We now have an authenticated request to fetch the next page req.send(decoder: decoder) { (result: Result<PagedResult<T>, DisruptiveError>) in switch result { case .success(let pagedResult): // Create a new array of all the items received so far let updatedResultsArray = cumulativeResults + pagedResult.results // Check if there are any more pages if let nextPageToken = pagedResult.nextPageToken { // This was not the last page, send request for the next page var nextRequest = req nextRequest.params["page_token"] = [nextPageToken] Disruptive.log("Still more pages to load for \(String(describing: nextRequest.urlRequest()?.url))") // Fetch the next page fetchPages( request : nextRequest, cumulativeResults : updatedResultsArray, pageingKey : pageingKey, completion : completion ) } else { // This was the last page DispatchQueue.main.async { completion(.success(updatedResultsArray)) } } // The request failed case .failure(let err): completion(.failure(err)) } } // Authentication failed case .failure(let err): completion(.failure(err)) } } } fetchPages(request: request, cumulativeResults: [], pageingKey: pagingKey) { completion($0) } } /// Returns a JSONDecoder that replaces the key with the given `pagingKey` with the key "results". Any other /// keys are passed as is (eg. "nextPageToken"). This ensures a normalized JSON format that lets /// us use `PagedResult` in the next step of decoding. /// /// Eg. replaces: /// `{ "devices": [...], "nextPageToken": "abc" }` /// with: /// `{ "results": [...], "nextPageToken": "abc" }` private func pagingJSONDecoder(pagingKey: String) -> JSONDecoder { /// A bare-minimum struct that conforms to `CodingKey` struct PagedKey: CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { return nil } } let decoder = JSONDecoder() decoder.keyDecodingStrategy = .custom { keys in if keys.last!.stringValue == pagingKey { return PagedKey(stringValue: "results")! } else { return keys.last! } } return decoder } }
39.714815
189
0.540754
bf61bdb5912d3fd74f7d7afe0cf5ad3a6706745f
237
// // MultiNestedPrivateExtensionClass.swift // Cuckoo // // Created by Tyler Thompson on 9/18/20. // import Foundation fileprivate extension Multi.Nested { class ThisClassShouldNotBeMocked1 { var property: Int? } }
15.8
42
0.696203
e40fcbfe43d8852b8675cb6e0b9af23bb59d446b
7,341
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser 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 // //===----------------------------------------------------------------------===// import XCTest import ArgumentParserTestHelpers import ArgumentParser final class SubcommandEndToEndTests: XCTestCase { } // MARK: Single value String fileprivate struct Foo: ParsableCommand { static var configuration = CommandConfiguration(subcommands: [CommandA.self, CommandB.self]) @Option() var name: String } fileprivate struct CommandA: ParsableCommand { static var configuration = CommandConfiguration(commandName: "a") @OptionGroup() var foo: Foo @Option() var bar: Int } fileprivate struct CommandB: ParsableCommand { static var configuration = CommandConfiguration(commandName: "b") @OptionGroup() var foo: Foo @Option() var baz: String } extension SubcommandEndToEndTests { func testParsing_SubCommand() throws { AssertParseCommand(Foo.self, CommandA.self, ["--name", "Foo", "a", "--bar", "42"]) { a in XCTAssertEqual(a.bar, 42) XCTAssertEqual(a.foo.name, "Foo") } AssertParseCommand(Foo.self, CommandB.self, ["--name", "A", "b", "--baz", "abc"]) { b in XCTAssertEqual(b.baz, "abc") XCTAssertEqual(b.foo.name, "A") } } func testParsing_SubCommand_manual() throws { AssertParseCommand(Foo.self, CommandA.self, ["--name", "Foo", "a", "--bar", "42"]) { a in XCTAssertEqual(a.bar, 42) XCTAssertEqual(a.foo.name, "Foo") } AssertParseCommand(Foo.self, Foo.self, ["--name", "Foo"]) { foo in XCTAssertEqual(foo.name, "Foo") } } func testParsing_SubCommand_help() throws { let helpFoo = Foo.message(for: CleanExit.helpRequest()) let helpA = Foo.message(for: CleanExit.helpRequest(CommandA.self)) let helpB = Foo.message(for: CleanExit.helpRequest(CommandB.self)) AssertEqualStringsIgnoringTrailingWhitespace(""" USAGE: foo --name <name> <subcommand> OPTIONS: --name <name> -h, --help Show help information. SUBCOMMANDS: a b """, helpFoo) AssertEqualStringsIgnoringTrailingWhitespace(""" USAGE: foo a --name <name> --bar <bar> OPTIONS: --name <name> --bar <bar> -h, --help Show help information. """, helpA) AssertEqualStringsIgnoringTrailingWhitespace(""" USAGE: foo b --name <name> --baz <baz> OPTIONS: --name <name> --baz <baz> -h, --help Show help information. """, helpB) } func testParsing_SubCommand_fails() throws { XCTAssertThrowsError(try Foo.parse(["--name", "Foo", "a", "--baz", "42"]), "'baz' is not an option for the 'a' subcommand.") XCTAssertThrowsError(try Foo.parse(["--name", "Foo", "b", "--bar", "42"]), "'bar' is not an option for the 'b' subcommand.") } } fileprivate var mathDidRun = false fileprivate struct Math: ParsableCommand { enum Operation: String, ExpressibleByArgument { case add case multiply } @Option(default: .add, help: "The operation to perform") var operation: Operation @Flag(name: [.short, .long]) var verbose: Bool @Argument(help: "The first operand") var operands: [Int] func run() { XCTAssertEqual(operation, .multiply) XCTAssertTrue(verbose) XCTAssertEqual(operands, [5, 11]) mathDidRun = true } } extension SubcommandEndToEndTests { func testParsing_SingleCommand() throws { let mathCommand = try Math.parseAsRoot(["--operation", "multiply", "-v", "5", "11"]) XCTAssertFalse(mathDidRun) try mathCommand.run() XCTAssertTrue(mathDidRun) } } // MARK: Nested Command Arguments Validated struct BaseCommand: ParsableCommand { enum BaseCommandError: Error { case baseCommandFailure case subCommandFailure } static let baseFlagValue = "base" static var configuration = CommandConfiguration( commandName: "base", subcommands: [SubCommand.self] ) @Option() var baseFlag: String mutating func validate() throws { guard baseFlag == BaseCommand.baseFlagValue else { throw BaseCommandError.baseCommandFailure } } } extension BaseCommand { struct SubCommand : ParsableCommand { static let subFlagValue = "sub" static var configuration = CommandConfiguration( commandName: "sub", subcommands: [SubSubCommand.self] ) @Option() var subFlag: String mutating func validate() throws { guard subFlag == SubCommand.subFlagValue else { throw BaseCommandError.subCommandFailure } } } } extension BaseCommand.SubCommand { struct SubSubCommand : ParsableCommand, TestableParsableArguments { let didValidateExpectation = XCTestExpectation(singleExpectation: "did validate subcommand") static var configuration = CommandConfiguration( commandName: "subsub" ) @Flag() var subSubFlag: Bool private enum CodingKeys: CodingKey { case subSubFlag } } } extension SubcommandEndToEndTests { func testValidate_subcommands() { // provide a value to base-flag that will throw AssertErrorMessage( BaseCommand.self, ["--base-flag", "foo", "sub", "--sub-flag", "foo", "subsub"], "baseCommandFailure" ) // provide a value to sub-flag that will throw AssertErrorMessage( BaseCommand.self, ["--base-flag", BaseCommand.baseFlagValue, "sub", "--sub-flag", "foo", "subsub"], "subCommandFailure" ) // provide a valid command and make sure both validates succeed AssertParseCommand(BaseCommand.self, BaseCommand.SubCommand.SubSubCommand.self, ["--base-flag", BaseCommand.baseFlagValue, "sub", "--sub-flag", BaseCommand.SubCommand.subFlagValue, "subsub", "--sub-sub-flag"]) { cmd in XCTAssertTrue(cmd.subSubFlag) // make sure that the instance of SubSubCommand provided // had its validate method called, not just that any instance of SubSubCommand was validated wait(for: [cmd.didValidateExpectation], timeout: 0.1) } } } // MARK: Version flags private struct A: ParsableCommand { static var configuration = CommandConfiguration( version: "1.0.0", subcommands: [HasVersionFlag.self, NoVersionFlag.self]) struct HasVersionFlag: ParsableCommand { @Flag() var version: Bool } struct NoVersionFlag: ParsableCommand { @Flag() var hello: Bool } } extension SubcommandEndToEndTests { func testParsingVersionFlags() throws { AssertErrorMessage(A.self, ["--version"], "1.0.0") AssertErrorMessage(A.self, ["no-version-flag", "--version"], "1.0.0") AssertParseCommand(A.self, A.HasVersionFlag.self, ["has-version-flag", "--version"]) { cmd in XCTAssertTrue(cmd.version) } } }
27.912548
161
0.630159
11e4743822793fdba823251b5489b25a0689f1ae
3,703
// // BarHighlighter.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 @objc(BarChartHighlighter) open class BarHighlighter: ChartHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { guard let barData = (self.chart as? BarChartDataProvider)?.barData, let high = super.getHighlight(x: x, y: y) else { return nil } let pos = getValsForTouch(x: x, y: y) if let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet, set.isStacked { return getStackedHighlight(high: high, set: set, xValue: Double(pos.x), yValue: Double(pos.y)) } else { return high } } internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return abs(x1 - x2) } internal override var data: ChartData? { return (chart as? BarChartDataProvider)?.barData } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. /// - parameter high: the Highlight to work with looking for stacked values /// - parameter set: /// - parameter xIndex: /// - parameter yValue: /// - returns: @objc open func getStackedHighlight(high: Highlight, set: IBarChartDataSet, xValue: Double, yValue: Double) -> Highlight? { guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider, let entry = set.entryForXValue(xValue, closestToY: yValue) as? BarChartDataEntry else { return nil } // Not stacked if entry.yValues == nil { return high } guard let ranges = entry.ranges, ranges.count > 0 else { return nil } let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue) if set.colors[stackIndex] == NSUIColor.clear { return nil; } let pixel = chart .getTransformer(forAxis: set.axisDependency) .pixelForValues(x: high.x, y: ranges[stackIndex].to) return Highlight(x: entry.x, y: entry.y, xPx: pixel.x, yPx: pixel.y, dataSetIndex: high.dataSetIndex, stackIndex: stackIndex, axis: high.axis) } /// - returns: The index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter. /// - parameter entry: /// - parameter value: /// - returns: @objc open func getClosestStackIndex(ranges: [Range]?, value: Double) -> Int { guard let ranges = ranges else { return 0 } var stackIndex = 0 for range in ranges { if range.contains(value) { return stackIndex } else { stackIndex += 1 } } let length = max(ranges.count - 1, 0) return (value > ranges[length].to) ? length : 0 } }
30.105691
136
0.521739
d67315590e027460d3231524ac9596d07ff42b9a
1,874
// // InboundDomain.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class InboundDomain: Codable { public enum MxRecordStatus: String, Codable { case valid = "VALID" case invalid = "INVALID" case notAvailable = "NOT_AVAILABLE" } /** Unique Id of the domain such as: example.com */ public var _id: String? public var name: String? /** Mx Record Status */ public var mxRecordStatus: MxRecordStatus? /** Indicates if this a PureCloud sub-domain. If true, then the appropriate DNS records are created for sending/receiving email. */ public var subDomain: Bool? /** The DNS settings if the inbound domain is using a custom Mail From. These settings can only be used on InboundDomains where subDomain is false. */ public var mailFromSettings: MailFromResult? /** The custom SMTP server integration to use when sending outbound emails from this domain. */ public var customSMTPServer: DomainEntityRef? /** The URI for this object */ public var selfUri: String? public init(_id: String?, name: String?, mxRecordStatus: MxRecordStatus?, subDomain: Bool?, mailFromSettings: MailFromResult?, customSMTPServer: DomainEntityRef?, selfUri: String?) { self._id = _id self.name = name self.mxRecordStatus = mxRecordStatus self.subDomain = subDomain self.mailFromSettings = mailFromSettings self.customSMTPServer = customSMTPServer self.selfUri = selfUri } public enum CodingKeys: String, CodingKey { case _id = "id" case name case mxRecordStatus case subDomain case mailFromSettings case customSMTPServer case selfUri } }
29.28125
186
0.655283
e0b6ed54afa007f62161008f82ca7cb081cada1e
1,024
import UIKit public enum MessageBannerType { case success case error case info var backgroundColor: UIColor { switch self { case .success: return .ksr_cobalt_500 case .error: return .ksr_apricot_500 case .info: return .ksr_cobalt_500 } } var iconImageName: String? { switch self { case .success: return "icon--confirmation" case .error: return "icon--alert" default: return nil } } var iconImageTintColor: UIColor? { switch self { case .error: return .black default: return nil } } var textColor: UIColor { switch self { case .success, .info: return .white case .error: return .ksr_soft_black } } var textAlignment: NSTextAlignment { switch self { case .info: return .center default: return .left } } var shouldShowIconImage: Bool { switch self { case .info: return false default: return true } } }
15.515152
38
0.588867
5b0d7d602f2bd57e52d32a41f9259449bbe69cfc
1,944
// // ViewController.swift // PlayingCard // // Created by Ruben on 12/3/17. // Copyright © 2017 Ruben. All rights reserved. // import UIKit /// /// Main view controller /// class ViewController: UIViewController { /// /// The deck of cards (model) /// var deck = PlayingCardDeck() /// /// The playing card view (view) /// @IBOutlet weak var playingCardView: PlayingCardView! { didSet { setupGestureRecognizers() } } /// /// Flip the card /// @IBAction func flipCard(_ sender: UITapGestureRecognizer) { // Make sure tap was successful if sender.state == .ended { playingCardView.isFaceUp = !playingCardView.isFaceUp } } /// /// Get the next card on the deck /// @objc private func nextCard() { // Try to draw a card if let card = deck.draw() { // Configure the view to show the new card playingCardView.rank = card.rank.order playingCardView.suit = card.suit.rawValue } } /// /// Setup gesture recognizers on the playing card: /// - Swipe: Go to next card in the deck /// - Pinch: Zoom the card's face /// /// Note: Tap gesture recognizer (to flip the card) was added /// using interface builder. /// private func setupGestureRecognizers() { // Swipe gesture recognizer to go to next card let swipe = UISwipeGestureRecognizer(target: self, action: #selector(nextCard)) swipe.direction = [.left, .right] playingCardView.addGestureRecognizer(swipe) // Pinch gesture recognizer to zoom the card's face let pinch = UIPinchGestureRecognizer( target: playingCardView, action: #selector(playingCardView.adjustFaceCardScale(gestureRecognizer:)) ) playingCardView.addGestureRecognizer(pinch) } }
26.630137
87
0.595679