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
5054e8d2a33ed42c7aaae58b6ba60cdc51f3bab4
634
// // Int+Random.swift // Help // // Created by Sergey Lukaschuk on 02.06.2021. // import Foundation // MARK: Int + Random /// An extension for Int that returns a random number works with range of numbers. Negative numbers converts to positive. /// Example: 17.random will return 0 to 17 (not including 17) /// Example: -5.random, -5 convert to 5, will return 0 to 5 (not including 5). extension Int { var random: Int { if self > 0 { return Int.random(in: 0..<self) } else if self < 0 { return Int.random(in: 0..<abs(self)) } else { return 0 } } }
21.862069
122
0.589905
e65fa1e7a147b8d41200214cd54fee1689190a81
2,009
// // ViewController.swift // TableView // // Created by Maksim Vialykh on 31/10/2018. // Copyright © 2018 Vialyx. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var table: UITableView! // Create constant data source private let dataSource = TableDataSource() override func viewDidLoad() { super.viewDidLoad() // Attach to table view dataSource.attach(to: table) // Setup data set dataSource.items = ["The", "Best", "Solution", "for", "Data Source", "is", "Separated", "Class"] } } /* The Data Source Pattern is provide element to view depends on data that it's owns */ // TODO: - Move to separated file TableDataSource.swift class TableDataSource: NSObject { var items: [String] = [] func attach(to view: UITableView) { // Setup itself as table data source (Implementation in separated extension) view.dataSource = self // Register element for dequeuing (All dequeuing element must register in table before) view.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)") } } // MARK: - UITableViewDataSource extension TableDataSource: UITableViewDataSource { // Return elements count that must be displayed in table func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } // Instantiate or reused (depend on position and cell type in table view), configure cell element and return it for displaying on table func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "\(UITableViewCell.self)" let item = items[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: identifier) cell.textLabel?.text = item return cell } }
31.888889
142
0.680936
168f75667b31ffc0668198c240c7264a26b3aef4
549
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Created by Sam Deane on 16/02/22. // All code (c) 2022 - present day, Elegant Chaos Limited. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- import Foundation enum GroupType: UInt32 { case top case worldChildren case interiorCellBlock case interiorCellSubBlock case exteriorCellBlock case exteriorCellSubBlock case cellChildren case topicChildren case cellPersistentChildren case cellTemporaryChildren }
27.45
72
0.544627
1c4b6ed97cbb1514bd5038344be5b9e43604bd35
1,859
// // ViewController.swift // EpitechEisenhower // // Created by Teddy Carneiro on 22/03/2018. // Copyright © 2018 Teddy Carneiro. All rights reserved. // import UIKit class SignInViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! var authImp: EpitechEisenhowerAuth? @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setDesign() // Do any additional setup after loading the view, typically from a nib. } private func setDesign() { view.backgroundColor = .lightBlueColor loginButton.backgroundColor = .orangeColor loginButton.roundCorner() signInButton.backgroundColor = .yellowColor signInButton.roundCorner() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func trigger(_ sender: Any) { authImp?.signInUser(email: emailTextField.text, password: passwordTextField.text, completion: {[weak self] (result) in switch result { case .success : let homeVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeVC") let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = homeVC case .failure(let error): print(error) } }) } }
34.425926
140
0.58042
e6f547769111ef1e598d0a14fc5f283132819afa
1,349
// // AppDelegate.swift // CollectionViewPagingLayout // // Created by Amir Khorsandi on 12/23/19. // Copyright © 2019 Amir Khorsandi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController! override init() { super.init() Catalyst.bridge?.initialise() } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow() navigationController = UINavigationController() navigationController.isNavigationBarHidden = true let mainVC = UIDevice.current.userInterfaceIdiom != .phone ? LayoutDesignerViewController.instantiate(viewModel: LayoutDesignerViewModel()) : MainViewController.instantiate() #if targetEnvironment(macCatalyst) if let titlebar = window?.windowScene?.titlebar { titlebar.titleVisibility = .hidden titlebar.toolbar = nil } #endif navigationController.setViewControllers([mainVC], animated: false) window!.rootViewController = navigationController window!.makeKeyAndVisible() return true } }
31.372093
145
0.680504
ed9d4de300222b395aa480804aedb0913fea012c
6,216
// // MusicPlayerViewController.swift // MusicPlayer // // Created by Prethush on 19/02/18. // Copyright © 2018 Prethush. All rights reserved. // import UIKit import MediaPlayer final class MusicPlayerViewController: UIViewController { @IBOutlet weak var constraintControllsHeight: NSLayoutConstraint! @IBOutlet weak var seekSlider: UISlider! @IBOutlet weak var btnPlayPause: UIButton! @IBOutlet weak var imgArtwork: UIImageView! @IBOutlet weak var lblArtist: UILabel! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblAlbum: UILabel! @IBOutlet weak var lblCurrentTime: UILabel! @IBOutlet weak var lblDuration: UILabel! var player: MPMusicPlayerController? var playTimer: Timer? var isPlaying: Bool = false var currentDuration: TimeInterval = 0 override func viewDidLoad() { super.viewDidLoad() if ObjCUtils.isIphoneX() { constraintControllsHeight.constant += 34 } self.title = LocalString("NOW.PLAYING") self.player = MPMusicPlayerController.systemMusicPlayer self.isPlaying = self.player?.playbackState == MPMusicPlaybackState.playing ? true : false self.seekSlider.value = 0 self.imgArtwork.isUserInteractionEnabled = true let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.previousAction(_:))) swipeRight.direction = .right self.imgArtwork.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.nextAction(_:))) swipeLeft.direction = .left self.imgArtwork.addGestureRecognizer(swipeLeft) } override func viewDidAppear(_ animated: Bool){ super.viewDidAppear(animated) let notifyCenter = NotificationCenter.default notifyCenter.addObserver(forName: NSNotification.Name.MPMusicPlayerControllerPlaybackStateDidChange, object: nil, queue: nil) { [weak self] (notification) in self?.updatePlayButtonState() } notifyCenter.addObserver(forName: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: nil, queue: nil) { [weak self] (_) in self?.updateCurrentTrackInfo() } self.player?.beginGeneratingPlaybackNotifications() self.updatePlayButtonState() self.updateCurrentTrackInfo() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) let notifyCenter = NotificationCenter.default notifyCenter.removeObserver(self, name: NSNotification.Name.MPMusicPlayerControllerPlaybackStateDidChange, object: nil) notifyCenter.removeObserver(self, name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: nil) } @IBAction func previousAction(_ sender: Any) { self.player?.skipToPreviousItem() self.player?.play() } @IBAction func nextAction(_ sender: Any) { self.player?.skipToNextItem() self.player?.play() } @IBAction func playAction(_ sender: Any) { if self.isPlaying { self.player?.pause() }else{ self.player?.play() } self.isPlaying = !self.isPlaying } @IBAction func seekBarAction(_ sender: UISlider) { let playTime = self.currentDuration * Double(sender.value) self.player?.currentPlaybackTime = playTime lblCurrentTime.text = format(Duration: playTime) } private func updateCurrentTrackInfo(){ print("track update") if let currentPlayingItem = self.player?.nowPlayingItem, self.player?.playbackState != MPMusicPlaybackState.stopped{ if let artWork = currentPlayingItem.value(forProperty: MPMediaItemPropertyArtwork) as? MPMediaItemArtwork{ self.imgArtwork.image = artWork.image(at: CGSize(width: 320, height: 320)) }else{ self.imgArtwork.image = UIImage(named: "noAlbumArt") } if let title = currentPlayingItem.value(forProperty: MPMediaItemPropertyTitle) as? String{ self.lblTitle.text = title }else{ self.lblTitle.text = LocalString("UNKNOWN.TITLE") } if let artist = currentPlayingItem.value(forProperty: MPMediaItemPropertyArtist) as? String{ self.lblArtist.text = artist }else{ self.lblArtist.text = LocalString("UNKNOWN.ARTIST") } if let album = currentPlayingItem.value(forProperty: MPMediaItemPropertyAlbumTitle) as? String{ self.lblAlbum.text = album }else{ self.lblAlbum.text = LocalString("UNKNOWN.ALBUM") } if let duration = currentPlayingItem.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? TimeInterval{ self.currentDuration = duration lblDuration.text = format(Duration: duration) } } } private func updatePlayButtonState(){ print("play state update") if self.player?.playbackState == MPMusicPlaybackState.playing { self.isPlaying = true self.btnPlayPause.setImage(UIImage(named: "pause"), for: []) self.startPlay() }else{ self.isPlaying = false self.btnPlayPause.setImage(UIImage(named: "play"), for: []) self.stopPlay() } } private func updateSeek(){ self.seekSlider.value = Float((self.player?.currentPlaybackTime ?? 0) / self.currentDuration) } private func startPlay(){ lblCurrentTime.text = format(Duration: self.player?.currentPlaybackTime ?? 0) playTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in self.lblCurrentTime.text = format(Duration: self.player?.currentPlaybackTime ?? 0) self.updateSeek() }) } private func stopPlay(){ playTimer?.invalidate() } }
37.902439
165
0.642857
bb27c2ba9acb7924a8f80b048d2fbaf514edbb1b
4,668
// // ZZTool.swift // ZZSwiftKit // // Created by GODKILLER on 2019/4/29. // Copyright © 2019 ZZSwiftKit. All rights reserved. // import UIKit public class ZZTool: NSObject { /// 根据date获取时间戳 /// /// - Parameter date: 时间 /// - Returns: 时间戳 public class func getTimeStampWithDate(date: Date) -> String { let timeInterval:TimeInterval = date.timeIntervalSince1970 let timeStamp = Int(timeInterval) return "\(timeStamp)" } /// 根据date获取指定格式时间字符串 /// /// - Parameters: /// - date: 时间 /// - formatter: 时间格式 /// - Returns: 指定格式字符串 public class func getTimeStringWithDateAndFormatter(date: Date,formatter: String) -> String { let dateFormatter = DateFormatter() // 时间格式:"hh:mm aa dd/MM/YYYY"等 dateFormatter.dateFormat = formatter return dateFormatter.string(from: date) } /// 根据时间戳获取指定格式时间 /// /// - Parameters: /// - timeStamp: 时间戳 /// - formatter: 格式 /// - Returns: 指定格式时间字符串 public class func getTimeStringWithTimeStampAndFormatter(timeStamp: String,formatter: String) -> String { //转换为时间 let timeInterval:TimeInterval = TimeInterval(Int(timeStamp)!) let date = NSDate(timeIntervalSince1970: timeInterval) //格式话输出 let dformatter = DateFormatter() dformatter.dateFormat = formatter return "\(dformatter.string(from: date as Date))" } /// 根据时间戳获取周几 /// /// - Parameter timeStamp: 时间戳 /// - Returns: 返回周几 public class func getWeek(timeStamp: String) -> String { let time = Double(timeStamp)! let date = NSDate.init(timeIntervalSinceReferenceDate: time) let gregorian = NSCalendar.init(calendarIdentifier: .gregorian) let weekdayComponents = gregorian?.components(.weekday, from: date as Date) let weekday = weekdayComponents?.weekday var weekStr: String = "" if (weekday == 1) { weekStr = "星期日"; }else if (weekday == 2){ weekStr = "星期一"; }else if (weekday == 3){ weekStr = "星期二"; }else if (weekday == 4){ weekStr = "星期三"; }else if (weekday == 5){ weekStr = "星期四"; }else if (weekday == 6){ weekStr = "星期五"; }else if (weekday == 7){ weekStr = "星期六"; } return weekStr } /// 根据字符串生成二维码图片 /// /// - Parameters: /// - QRCodeString: QRCodeString description /// - logo: logo description /// - size: size description /// - Returns: return value description public class func generateQRImage(QRCodeString: String, logo: UIImage?, size: CGSize = CGSize(width: 200, height: 200)) -> UIImage? { guard let data = QRCodeString.data(using: .utf8, allowLossyConversion: false) else { return nil } let imageFilter = CIFilter(name: "CIQRCodeGenerator") imageFilter?.setValue(data, forKey: "inputMessage") imageFilter?.setValue("H", forKey: "inputCorrectionLevel") let ciImage = imageFilter?.outputImage // 创建颜色滤镜 let colorFilter = CIFilter(name: "CIFalseColor") colorFilter?.setDefaults() colorFilter?.setValue(ciImage, forKey: "inputImage") colorFilter?.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0") colorFilter?.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1") // 返回二维码图片 let qrImage = UIImage(ciImage: (colorFilter?.outputImage)!) let imageRect = size.width > size.height ? CGRect(x: (size.width - size.height) / 2, y: 0, width: size.height, height: size.height) : CGRect(x: 0, y: (size.height - size.width) / 2, width: size.width, height: size.width) UIGraphicsBeginImageContextWithOptions(imageRect.size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } qrImage.draw(in: imageRect) if logo != nil { let logoSize = size.width > size.height ? CGSize(width: size.height * 0.25, height: size.height * 0.25) : CGSize(width: size.width * 0.25, height: size.width * 0.25) logo?.draw(in: CGRect(x: (imageRect.size.width - logoSize.width) / 2, y: (imageRect.size.height - logoSize.height) / 2, width: logoSize.width, height: logoSize.height)) } return UIGraphicsGetImageFromCurrentImageContext() } }
33.342857
180
0.578835
62622290e5a2fe2ea1596bed11a51b2f4c8b27be
7,066
import Foundation import Moya import RxSwift enum HTTPHeader: String { case language = "Accept-Language" case expiry = "Expires" case accept = "Accept" case contentType = "Content-Type" } struct StatusCode { static let unauthorized = 401 } /** Public protocol that defines the minimum API that an APIService should expose. The APIService is the component in charge of handling al network request for an specific TargetType. Basic behaviour implemented using callbacks is provided by the BaseManager class. */ public protocol APIService { /// The associated TargetType of the Service. associatedtype ProviderType: TargetType /// The MoyaProvider instance used to make the network requests. var provider: MoyaProvider<ProviderType> { get } /// The JSON decoding strategy used for JSON Responses. var jsonDecoder: JSONDecoder { get } } /** Base ApiService class that implements generic behaviour to be extendended and used by subclassing it. The base service has an associated TargetType, this means that you should have **one and only one** manager for each TargetType. This base implementation provides helpers to make requests with automatic encoding if you provide a propper model as the expected result type. */ open class BaseApiService<T>: APIService where T: TargetType { public typealias ProviderType = T let encoder = JSONEncoder() let decoder = JSONDecoder() var disposeBag = DisposeBag() private var sharedProvider: MoyaProvider<T>! private func JSONResponseDataFormatter(_ data: Data) -> String { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return String(data: prettyData, encoding: .utf8) ?? String(data: data, encoding: .utf8) ?? "" } catch { return String(data: data, encoding: .utf8) ?? "" } } private var plugins: [PluginType] { return [NetworkLoggerPlugin(configuration: .init(formatter: .init(responseData: JSONResponseDataFormatter), logOptions: .verbose))] } /** Default provider implementation as a singleton. It provides networking loggin out of the box and you can override it if you want to add more middleware. */ open var provider: MoyaProvider<T> { guard let provider = sharedProvider else { sharedProvider = MoyaProvider<T>(plugins: plugins) return sharedProvider } return provider } /** Default JSON decoder setup, uses the most common case of keyDecoding, converting from camel_case to snakeCase before attempting to match override this var if you need to customize your JSON decoder. */ open var jsonDecoder: JSONDecoder { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.dateDecodingStrategy = .millisecondsSince1970 return decoder } public required init () {} /** Makes a request to the provided target and tries to decode its response using the provided keyPath and return type and returning it as an Observable. - Parameters: - target: The TargetType used to make the request. - keyPath: The keypath used to decode from JSON (if passed nil, it will try to decode from the root). */ open func request<T>(for target: ProviderType, at keyPath: String? = nil) -> Observable<(T, Response)> where T: Codable { return provider.rx.request(target) .filterSuccessfulStatusCodes() .flatMap { [weak self] response in let decodedValue = try response.map(T.self, atKeyPath: keyPath, using: self?.jsonDecoder ?? JSONDecoder(), failsOnEmptyData: true) return .just((decodedValue, response)) } .asObservable() .catchError { [weak self] error in guard let self = self else { return Observable.error(error) } return Observable.error(self.handleError(with: error)) } } /** Makes a request to the provided target and tries to decode its response as a string using the provided keyPath and returning it as an Observable. - Parameters: - target: The TargetType used to make the request. - keyPath: The keypath used to decode the string (if passed nil, it will try to decode from the root). */ open func requestString(for target: ProviderType, at keyPath: String? = nil) -> Observable<(String, Response)> { return provider.rx.request(target) .filterSuccessfulStatusCodes() .flatMap { response in let decodedValue = try response.mapString(atKeyPath: keyPath) return .just((decodedValue, response)) } .asObservable() .catchError { [weak self] error in guard let self = self else { return Observable.error(error) } return Observable.error(self.handleError(with: error)) } } /** Makes a request to the provided target and returns as an Obserbable - Parameters: - target: The TargetType used to make the request. */ open func request(for target: ProviderType) -> Observable<Response> { return provider.rx.request(target) .filterSuccessfulStatusCodes() .asObservable() .catchError { [weak self] error in guard let self = self else { return Observable.error(error) } return Observable.error(self.handleError(with: error)) } } private func handleError(with error: Error) -> Error { guard let moyaError = error as? MoyaError else { return error } switch moyaError { case .statusCode(let response): return error case .stringMapping, .jsonMapping, .imageMapping: return error case .objectMapping(let mappingError, _): return mappingError case .encodableMapping(let error), .parameterEncoding(let error): return error case .underlying(let underlyingError, _): return underlyingError case .requestMapping: return error } } private func JSONResponseDataFormatter(_ data: Data) -> Data { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return prettyData } catch { return data } } }
37.585106
125
0.623125
62cc4d8413f1d025752774e0c3a06a681f2cf123
2,931
// // MGalleryPeerPhotoItem.swift // Telegram // // Created by keepcoder on 10/02/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCoreMac import PostboxMac import SwiftSignalKitMac import TGUIKit class MGalleryPeerPhotoItem: MGalleryItem { let media:TelegramMediaImage override init(_ account: Account, _ entry: GalleryEntry, _ pagerSize: NSSize) { self.media = entry.photo! super.init(account, entry, pagerSize) } override var sizeValue: NSSize { if let largest = media.representations.last { return largest.dimensions.fitted(pagerSize) } return NSZeroSize } override func smallestValue(for size: NSSize) -> Signal<NSSize, Void> { if let largest = media.representations.last { return .single(largest.dimensions.fitted(size)) } return .single(pagerSize) } override var status:Signal<MediaResourceStatus, Void> { return chatMessagePhotoStatus(account: account, photo: media) } override func request(immediately: Bool) { let account = self.account let media = self.media let result = size.get() |> mapToSignal { [weak self] size -> Signal<NSSize, Void> in if let strongSelf = self { return strongSelf.smallestValue(for: size) } return .complete() } |> distinctUntilChanged |> mapToSignal { size -> Signal<((TransformImageArguments) -> DrawingContext?, TransformImageArguments), Void> in return chatMessagePhoto(account: account, photo: media, scale: System.backingScale) |> deliverOn(account.graphicsThreadPool) |> map { transform in return (transform, TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: NSEdgeInsets())) } } |> mapToThrottled { (transform, arguments) -> Signal<CGImage?, Void> in return .single(transform(arguments)?.generateImage()) } if let representation = media.representations.last { path.set(account.postbox.mediaBox.resourceData(representation.resource) |> mapToSignal { (resource) -> Signal<String, Void> in if resource.complete { return .single(link(path:resource.path, ext:kMediaImageExt)!) } return .never() }) } self.image.set(result |> deliverOnMainQueue) fetch() } override func fetch() -> Void { fetching.set(chatMessagePhotoInteractiveFetched(account: account, photo: media).start()) } override func cancel() -> Void { super.cancel() chatMessagePhotoCancelInteractiveFetch(account: account, photo: media) } }
33.689655
162
0.615148
bfc58d8b8c170411c26d335b217db5cbd3025a3d
523
// // ViewController.swift // FluidTransition // // Created by Grigor Hakobyan on 10/17/2021. // Copyright (c) 2021 Grigor Hakobyan. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.92
80
0.678776
e9b9843e558ea8de2e46825b0d1292cb5d0a5fac
1,809
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Firebase import FirebaseCore import FirebaseAuth import FirebaseFunctions import FirebaseInstallations // import FirebaseInstanceID import FirebaseStorage import FirebaseStorageSwift import GoogleDataTransport import GoogleUtilities_AppDelegateSwizzler import GoogleUtilities_Environment import GoogleUtilities_Logger import GoogleUtilities_MethodSwizzler import GoogleUtilities_Network import GoogleUtilities_NSData import GoogleUtilities_Reachability import GoogleUtilities_UserDefaults import nanopb import XCTest class importTest: XCTestCase { func testImports() { XCTAssertFalse(GULAppEnvironmentUtil.isAppStoreReceiptSandbox()) XCTAssertFalse(GULAppEnvironmentUtil.isFromAppStore()) XCTAssertFalse(GULAppEnvironmentUtil.isSimulator()) XCTAssertFalse(GULAppEnvironmentUtil.isAppExtension()) XCTAssertNil(FirebaseApp.app()) XCTAssertEqual(GULAppEnvironmentUtil.deviceModel(), "x86_64") print("System version? Answer: \(GULAppEnvironmentUtil.systemVersion() ?? "NONE")") print("Storage Version String? Answer: \(String(cString: StorageVersionString))") // print("InstanceIDScopeFirebaseMessaging? Answer: \(InstanceIDScopeFirebaseMessaging)") } }
34.132075
93
0.806523
e95d98b6735cc70196d1685b543c9f05e215a1e9
3,409
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "swift-experimental-string-processing", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "_StringProcessing", targets: ["_StringProcessing"]), .library( name: "Prototypes", targets: ["Prototypes"]), .library( name: "_RegexParser", targets: ["_RegexParser"]), .executable( name: "VariadicsGenerator", targets: ["VariadicsGenerator"]) ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", 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: "_RegexParser", dependencies: [], swiftSettings: [ .unsafeFlags(["-enable-library-evolution"]) ]), .testTarget( name: "MatchingEngineTests", dependencies: [ "_RegexParser", "_StringProcessing"]), .target( name: "_CUnicode", dependencies: []), .target( name: "_StringProcessing", dependencies: ["_RegexParser", "_CUnicode"], swiftSettings: [ .unsafeFlags(["-enable-library-evolution"]), ]), .target( name: "RegexBuilder", dependencies: ["_StringProcessing", "_RegexParser"], swiftSettings: [ .unsafeFlags(["-enable-library-evolution"]), .unsafeFlags(["-Xfrontend", "-enable-experimental-pairwise-build-block"]) ]), .testTarget( name: "RegexTests", dependencies: ["_StringProcessing"]), .testTarget( name: "RegexBuilderTests", dependencies: ["_StringProcessing", "RegexBuilder"], swiftSettings: [ .unsafeFlags(["-Xfrontend", "-enable-experimental-pairwise-build-block"]) ]), .target( name: "Prototypes", dependencies: ["_RegexParser", "_StringProcessing"]), // MARK: Scripts .executableTarget( name: "VariadicsGenerator", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser") ]), .executableTarget( name: "PatternConverter", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), "_RegexParser", "_StringProcessing" ]), // MARK: Exercises .target( name: "Exercises", dependencies: ["_RegexParser", "Prototypes", "_StringProcessing", "RegexBuilder"], swiftSettings: [ .unsafeFlags(["-Xfrontend", "-enable-experimental-pairwise-build-block"]) ]), .testTarget( name: "ExercisesTests", dependencies: ["Exercises"]), ] )
35.884211
122
0.548255
18c315e547187b7a5ae8ee2b23cc8a55ebde281a
663
// // Encodable+Data.swift // LeoNetworkLayer // // Created by Yuriy Savitskiy on 8/23/19. // Copyright © 2019 Yuriy Savitskiy. All rights reserved. // import Foundation public extension Encodable { func toJSONData() -> Data? { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted return try? encoder.encode(self) } func toDictionary() -> [String: Any]? { guard let data = try? JSONEncoder().encode(self) else { return nil } return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] } } }
24.555556
98
0.612368
0eafa02cc63260edd12940bee715ed19be6da355
1,438
/* Copyright NetFoundry Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /** * Class that encapsulate the claims of a Ziti one-time JWT file. * * Claims are verified as part of the enrollment process. * * - See also: * - `Ziti.enroll(_:,_:)` */ public class ZitiClaims : NSObject, Codable { private static let log = ZitiLog(ZitiClaims.self) private var log:ZitiLog { return ZitiClaims.log } /// Subject Clain (Required) public let sub:String /// Issuer Clain public var iss:String? /// Enrollment Method Clain public var em:String? /// Expiration Time Claim public var exp:Int? /// JWT ID Claim @objc public var jti:String? init(_ sub:String, _ iss:String?, _ em:String?, _ exp:Int?, _ jti:String?) { self.sub = sub self.iss = iss self.em = em self.exp = exp self.jti = jti super.init() } }
26.62963
80
0.668985
46b9d828cd33a747107c37515f4cd7d87eaa3f0c
4,422
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** * * @author Sam Harwell */ public final class MurmurHash { private static let DEFAULT_SEED: Int = 0 /** * Initialize the hash using the default seed value. * * @return the intermediate hash value */ public static func initialize() -> Int { return initialize(DEFAULT_SEED) } /** * Initialize the hash using the specified {@code seed}. * * @param seed the seed * @return the intermediate hash value */ public static func initialize(_ seed: Int) -> Int { return seed } /** * Update the intermediate hash value for the next input {@code value}. * * @param hash the intermediate hash value * @param value the value to add to the current hash * @return the updated intermediate hash value */ public static func update2(_ hashIn: Int, _ value: Int) -> Int { let c1: Int32 = -862048943//0xCC9E2D51; let c2: Int32 = 0x1B873593 let r1: Int32 = 15 let r2: Int32 = 13 let m: Int32 = 5 let n: Int32 = -430675100//0xE6546B64; var k: Int32 = Int32(truncatingBitPattern: value) k = Int32.multiplyWithOverflow(k, c1).0 // (k,_) = UInt32.multiplyWithOverflow(k, c1) ;//( k * c1); //TODO: CHECKE >>> k = (k << r1) | (k >>> (Int32(32) - r1)) //k = (k << r1) | (k >>> (32 - r1)); //k = UInt32 (truncatingBitPattern:Int64(Int64(k) * Int64(c2)));//( k * c2); //(k,_) = UInt32.multiplyWithOverflow(k, c2) k = Int32.multiplyWithOverflow(k, c2).0 var hash = Int32(hashIn) hash = hash ^ k hash = (hash << r2) | (hash >>> (Int32(32) - r2))//hash = (hash << r2) | (hash >>> (32 - r2)); (hash, _) = Int32.multiplyWithOverflow(hash, m) (hash, _) = Int32.addWithOverflow(hash, n) //hash = hash * m + n; // print("murmur update2 : \(hash)") return Int(hash) } /** * Update the intermediate hash value for the next input {@code value}. * * @param hash the intermediate hash value * @param value the value to add to the current hash * @return the updated intermediate hash value */ public static func update<T:Hashable>(_ hash: Int, _ value: T?) -> Int { return update2(hash, value != nil ? value!.hashValue : 0) // return update2(hash, value); } /** * Apply the final computation steps to the intermediate value {@code hash} * to form the final result of the MurmurHash 3 hash function. * * @param hash the intermediate hash value * @param numberOfWords the number of integer values added to the hash * @return the final hash result */ public static func finish(_ hashin: Int, _ numberOfWordsIn: Int) -> Int { var hash = Int32(hashin) let numberOfWords = Int32(numberOfWordsIn) hash = hash ^ Int32.multiplyWithOverflow(numberOfWords, Int32(4)).0 //(numberOfWords * UInt32(4)); hash = hash ^ (hash >>> Int32(16)) //hash = hash ^ (hash >>> 16); (hash, _) = Int32.multiplyWithOverflow(hash, Int32(-2048144789))//hash * UInt32(0x85EBCA6B); hash = hash ^ (hash >>> Int32(13))//hash = hash ^ (hash >>> 13); //hash = UInt32(truncatingBitPattern: UInt64(hash) * UInt64(0xC2B2AE35)) ; (hash, _) = Int32.multiplyWithOverflow(hash, Int32(-1028477387)) hash = hash ^ (hash >>> Int32(16))// hash = hash ^ (hash >>> 16); //print("murmur finish : \(hash)") return Int(hash) } /** * Utility function to compute the hash code of an array using the * MurmurHash algorithm. * * @param <T> the array element type * @param data the array data * @param seed the seed for the MurmurHash algorithm * @return the hash code of the data */ public static func hashCode<T:Hashable>(_ data: [T], _ seed: Int) -> Int { var hash: Int = initialize(seed) for value: T in data { //var hashValue = value != nil ? value.hashValue : 0 hash = update(hash, value.hashValue) } hash = finish(hash, data.count) return hash } private init() { } }
34.818898
107
0.584577
037ba0e0343cb1f75af87beda9eff0f382a4890b
6,762
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2018 Jean-David Gadina - www.xs-labs.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 class ALTool { private var username: String private var password: String private var providerShortName: String? class func isAvailable() -> Bool { guard let out = try? ALTool.run( arguments: [ "--help" ] ) else { return false } return out.stdout.count > 0 || out.stderr.count > 0 } init( username: String, password: String, providerShortName: String? ) { self.username = username self.password = password self.providerShortName = providerShortName } func checkPassword() throws { let _ = try ALTool.run( arguments: self.arguments( [ "--notarization-history", "0" ] ) + [ "--output-format", "xml" ] ) } func notarizationHistory( page: Int64 ) throws -> String? { let out = try ALTool.run( arguments: self.arguments( [ "--notarization-history", "\( page )" ] ) + [ "--output-format", "xml" ] ) return out.stdout.trimmingCharacters( in: NSCharacterSet.whitespacesAndNewlines ) } func notarizationInfo( for uuid: String ) throws -> String? { let out = try ALTool.run( arguments: self.arguments( [ "--notarization-info", uuid ] ) + [ "--output-format", "xml" ] ) return out.stdout.trimmingCharacters( in: NSCharacterSet.whitespacesAndNewlines ) } private func arguments( _ arguments: [ String ] ) -> [ String ] { var arguments = arguments arguments.append( "-u" ) arguments.append( self.username ) arguments.append( "-p" ) arguments.append( self.password ) if let name = self.providerShortName { arguments.append( "--asc-provider" ) arguments.append( name ) } return arguments } private class var executablePath: String? { let pipe = Pipe() let process = Process() process.launchPath = "/usr/bin/xcrun" process.arguments = [ "-f", "altool" ] process.standardOutput = pipe do { try process.run() } catch let e as NSError { Swift.print( e ) return nil } process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() guard let out = String( bytes: data, encoding: .utf8 ) else { return nil } return out.trimmingCharacters( in: .whitespacesAndNewlines ) } private class func run( arguments: [ String ] ) throws -> ( stdout: String, stderr: String ) { guard let exec = ALTool.executablePath else { throw NSError( domain: NSCocoaErrorDomain, code: -1, userInfo: [ NSLocalizedDescriptionKey : "altool executable not found" ] ) } let pipeOut = Pipe() let pipeErr = Pipe() let process = Process() process.launchPath = exec process.arguments = arguments process.standardOutput = pipeOut process.standardError = pipeErr do { try process.run() } catch let e as NSError { Swift.print( e ) throw e } process.waitUntilExit() let dataOut = pipeOut.fileHandleForReading.readDataToEndOfFile() let dataErr = pipeErr.fileHandleForReading.readDataToEndOfFile() guard let out = String( bytes: dataOut, encoding: .utf8 ), let err = String( bytes: dataErr, encoding: .utf8 ) else { throw NSError( domain: NSCocoaErrorDomain, code: -1, userInfo: [ NSLocalizedDescriptionKey : "No data received from altool" ] ) } if let data = out.data( using: .utf8 ) { if let dict = try? PropertyListSerialization.propertyList( from: data, options: [], format: nil ) as? [ AnyHashable : Any ] { if let errors = dict[ "product-errors" ] as? [ Any ] { if errors.count > 0, let errorDict = errors[ 0 ] as? [ AnyHashable : Any ] { let code = errorDict[ "code" ] as? NSNumber ?? NSNumber( integerLiteral: 0 ) let message = errorDict[ "message" ] as? String ?? "Unknown error" if let info = errorDict[ "userInfo" ] as? [ AnyHashable : Any ], let failure = info[ "NSLocalizedFailureReason" ] as? String { throw NSError( domain: NSCocoaErrorDomain, code: code.intValue, userInfo: [ NSLocalizedDescriptionKey : message, NSLocalizedRecoverySuggestionErrorKey : failure ] ) } else { throw NSError( domain: NSCocoaErrorDomain, code: code.intValue, userInfo: [ NSLocalizedDescriptionKey : "Error", NSLocalizedRecoverySuggestionErrorKey : message ] ) } } } } } return ( stdout: out, stderr: err ) } }
36.95082
192
0.547767
1abbc376660b49fa591e197203a661cc412705d8
2,304
// // VTScrollView.swift // VirtualViews // // Created by chuthin on 3/1/19. // Copyright © 2019 chuthin. All rights reserved. // import Foundation import UIKit public struct VTScrollView:VirtualView { public let id :String public let style: String public let contentView:VTView public let isHidden:Bool public let isReactive: Bool public init(id:String,style:String = "scrollView",contentView:VTView,isReactive:Bool = false,isHidden:Bool = false ){ self.id = id self.style = style self.contentView = contentView self.isHidden = isHidden self.isReactive = isReactive } public func render(into result:UIScrollView){ result.tag = self.id.hash result.style = self.style result.isHidden = self.isHidden result.reactiveKey = self.isReactive ? self.id : nil } public func update(into existing: UIView) -> UIView { guard let result = existing as? UIScrollView, result.subviews.count == 1 else { return render() } let existingSubview = result.subviews.first! let new = self.contentView.update(into: existingSubview) if new !== existingSubview { existingSubview.removeFromSuperview() result.addSubview(new) } return result } public func render() -> UIView { let subview = self.contentView.render() let result = UIScrollView(frame: .zero) result.translatesAutoresizingMaskIntoConstraints = false result.addSubview(subview) var constraints = [NSLayoutConstraint]() var viewsConstraint:[String: UIView] = [:] viewsConstraint[self.id] = result viewsConstraint[self.contentView.id] = subview constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[\(self.contentView.id)(0@250)]|", metrics:[:], views: viewsConstraint) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[\(self.contentView.id)]|", metrics:[:], views: viewsConstraint) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[\(self.contentView.id)(==\(self.id))]", metrics:[:], views: viewsConstraint) result.addConstraints(constraints) return result } }
36
152
0.653646
11d9b1f0caa796a4da4439a4bedfee8858c045e8
667
// // ImageInterpolation.swift // MasteringSwiftUI // // Created by Keun young Kim on 2020/04/06. // Copyright © 2020 Keun young Kim. All rights reserved. // import SwiftUI struct ImageInterpolation: View { var body: some View { VStack { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) Image("kxcoding-logo") .resizable() .interpolation(.low) Image("kxcoding-logo") .resizable() .interpolation(.high) } } } struct ImageInterpolation_Previews: PreviewProvider { static var previews: some View { ImageInterpolation() } }
20.84375
72
0.590705
565f3fbbe60552d2969142a437ac938d14a2437d
2,965
// Copyright 2021-present 650 Industries. All rights reserved. import Quick import Nimble @testable import ExpoModulesCore final class ExceptionsSpec: QuickSpec { override func spec() { it("has name") { let error = TestException() expect(error.name) == "TestException" } it("has code") { let error = TestException() expect(error.code) == "ERR_TEST" } it("has reason") { let error = TestException() expect(error.reason) == "This is the test exception" } it("can be chained once") { func throwable() throws { do { throw TestExceptionCause() } catch { throw TestException().causedBy(error) } } expect { try throwable() }.to(throwError { error in testChainedExceptionTypes(error: error, types: [TestException.self, TestExceptionCause.self]) }) } it("can be chained twice") { func throwable() throws { do { do { throw TestExceptionCause() } catch { throw TestExceptionCause().causedBy(error) } } catch { throw TestException().causedBy(error) } } expect { try throwable() }.to(throwError { error in testChainedExceptionTypes(error: error, types: [TestException.self, TestExceptionCause.self, TestExceptionCause.self]) }) } it("includes cause description") { func throwable() throws { do { throw TestExceptionCause() } catch { throw TestException().causedBy(error) } } expect { try throwable() }.to(throwError { error in if let error = error as? TestException, let cause = error.cause as? TestExceptionCause { expect(error.description).to(contain(cause.description)) } else { fail("Error and its cause are not of expected types.") } }) } it("has root cause") { let a = TestException() let b = TestException().causedBy(a) let c = TestException().causedBy(b) expect(c.rootCause) === a } } } class TestException: Exception { override var reason: String { "This is the test exception" } } class TestExceptionCause: Exception { override var reason: String { "This is the cause of the test exception" } } /** Tests whether the exception chain matches given types and their order. */ private func testChainedExceptionTypes(error: Error, types: [Error.Type]) { var next: Error? = error for errorType in types { let expectedErrorTypeName = String(describing: errorType) let currentErrorTypeName = String(describing: type(of: next!)) expect(currentErrorTypeName).to(equal(expectedErrorTypeName), description: "The cause is not of type \(expectedErrorTypeName)") if let chainableException = next as? ChainableException { next = chainableException.cause } else { next = nil } } }
26.238938
131
0.617875
7117d3fa303ff9c277751dc15bc8220517b33ca2
1,542
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher 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 ObjectMapper public class AudioAnalysisBeat: Mappable { public private(set) var start: Double! public private(set) var duration: Double! public private(set) var confidence: Double! required public init?(map: Map) { mapping(map: map) } public func mapping(map: Map) { start <- map["start"] duration <- map["duration"] confidence <- map["confidence"] } }
40.578947
147
0.7393
7546fa03d0283990d16937617138a81d64bf7491
1,095
// // String+CKHashing.swift // BlackBook // // Created by Corey Klass on 8/20/16. // Copyright © 2016 Corey Klass. All rights reserved. // // REQUIRES OBJECTIVE-C BRIDGING FILE W/: // #import <CommonCrypto/CommonCrypto.h> import Foundation extension String { // hashing function func sha1() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) CC_SHA1((data as NSData).bytes, CC_LONG(data.count), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joined(separator: "") } /* // Swift 3: func sha1() -> String { let data = self.data(using: String.Encoding.utf8)! var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joined(separator: "") } */ }
21.9
77
0.592694
086866a7d80dd214ce4312576618b9d7ff6ad9fe
686
// // FormCell.swift // SwiftyForm // // Created by iOS on 2020/6/5. // Copyright © 2020 iOS. All rights reserved. // import UIKit import SnapKit open class BaseCell: UITableViewCell, FormableRow { open func updateWithRowFormer(_ rowFormer: RowFormer) { } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } open func setup() { selectionStyle = .none contentView.backgroundColor = .clear } }
20.787879
86
0.638484
d5b0ebc8b476defcb1e523a25237d1b87e32405b
55,465
// Sources/SwiftProtobuf/BinaryDecoder.swift - Binary decoding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Protobuf binary format decoding engine. /// /// This provides the Decoder interface that interacts directly /// with the generated code. /// // ----------------------------------------------------------------------------- import Foundation internal struct BinaryDecoder: Decoder { // Current position private var p : UnsafeRawPointer // Remaining bytes in input. private var available : Int // Position of start of field currently being parsed private var fieldStartP : UnsafeRawPointer // Position of end of field currently being parsed, nil if we don't know. private var fieldEndP : UnsafeRawPointer? // Whether or not the field value has actually been parsed private var consumed = true // Wire format for last-examined field internal var fieldWireFormat = WireFormat.varint // Field number for last-parsed field tag private var fieldNumber: Int = 0 // Collection of extension fields for this decode private var extensions: ExtensionMap? // The current group number. See decodeFullGroup(group:fieldNumber:) for how // this is used. private var groupFieldNumber: Int? // The options for decoding. private var options: BinaryDecodingOptions private var recursionBudget: Int // Collects the unknown data found while decoding a message. private var unknownData: Data? // Custom data to use as the unknown data while parsing a field. Used only by // packed repeated enums; see below private var unknownOverride: Data? private var complete: Bool {return available == 0} internal init( forReadingFrom pointer: UnsafeRawPointer, count: Int, options: BinaryDecodingOptions, extensions: ExtensionMap? = nil ) { // Assuming baseAddress is not nil. p = pointer available = count fieldStartP = p self.extensions = extensions self.options = options recursionBudget = options.messageDepthLimit } internal init( forReadingFrom pointer: UnsafeRawPointer, count: Int, parent: BinaryDecoder ) { self.init(forReadingFrom: pointer, count: count, options: parent.options, extensions: parent.extensions) recursionBudget = parent.recursionBudget } private mutating func incrementRecursionDepth() throws { recursionBudget -= 1 if recursionBudget < 0 { throw BinaryDecodingError.messageDepthLimit } } private mutating func decrementRecursionDepth() { recursionBudget += 1 // This should never happen, if it does, something is probably corrupting memory, and // simply throwing doesn't make much sense. if recursionBudget > options.messageDepthLimit { fatalError("Somehow BinaryDecoding unwound more objects than it started") } } internal mutating func handleConflictingOneOf() throws { /// Protobuf simply allows conflicting oneof values to overwrite } /// Return the next field number or nil if there are no more fields. internal mutating func nextFieldNumber() throws -> Int? { // Since this is called for every field, I've taken some pains // to optimize it, including unrolling a tweaked version of // the varint parser. if fieldNumber > 0 { if let override = unknownOverride { assert(!options.discardUnknownFields) assert(fieldWireFormat != .startGroup && fieldWireFormat != .endGroup) if unknownData == nil { unknownData = override } else { unknownData!.append(override) } unknownOverride = nil } else if !consumed { if options.discardUnknownFields { try skip() } else { let u = try getRawField() if unknownData == nil { unknownData = u } else { unknownData!.append(u) } } } } // Quit if end of input if available == 0 { return nil } // Get the next field number fieldStartP = p fieldEndP = nil let start = p let c0 = start[0] if let wireFormat = WireFormat(rawValue: c0 & 7) { fieldWireFormat = wireFormat } else { throw BinaryDecodingError.malformedProtobuf } if (c0 & 0x80) == 0 { p += 1 available -= 1 fieldNumber = Int(c0) >> 3 } else { fieldNumber = Int(c0 & 0x7f) >> 3 if available < 2 { throw BinaryDecodingError.malformedProtobuf } let c1 = start[1] if (c1 & 0x80) == 0 { p += 2 available -= 2 fieldNumber |= Int(c1) << 4 } else { fieldNumber |= Int(c1 & 0x7f) << 4 if available < 3 { throw BinaryDecodingError.malformedProtobuf } let c2 = start[2] fieldNumber |= Int(c2 & 0x7f) << 11 if (c2 & 0x80) == 0 { p += 3 available -= 3 } else { if available < 4 { throw BinaryDecodingError.malformedProtobuf } let c3 = start[3] fieldNumber |= Int(c3 & 0x7f) << 18 if (c3 & 0x80) == 0 { p += 4 available -= 4 } else { if available < 5 { throw BinaryDecodingError.malformedProtobuf } let c4 = start[4] if c4 > 15 { throw BinaryDecodingError.malformedProtobuf } fieldNumber |= Int(c4 & 0x7f) << 25 p += 5 available -= 5 } } } } if fieldNumber != 0 { consumed = false if fieldWireFormat == .endGroup { if groupFieldNumber == fieldNumber { // Reached the end of the current group, single the // end of the message. return nil } else { // .endGroup when not in a group or for a different // group is an invalid binary. throw BinaryDecodingError.malformedProtobuf } } return fieldNumber } throw BinaryDecodingError.malformedProtobuf } internal mutating func decodeSingularFloatField(value: inout Float) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } try decodeFourByteNumber(value: &value) consumed = true } internal mutating func decodeSingularFloatField(value: inout Float?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } value = try decodeFloat() consumed = true } internal mutating func decodeRepeatedFloatField(value: inout [Float]) throws { switch fieldWireFormat { case WireFormat.fixed32: let i = try decodeFloat() value.append(i) consumed = true case WireFormat.lengthDelimited: let bodyBytes = try decodeVarint() if bodyBytes > 0 { let itemSize = UInt64(MemoryLayout<Float>.size) let itemCount = bodyBytes / itemSize if bodyBytes % itemSize != 0 || bodyBytes > available { throw BinaryDecodingError.truncated } value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount)) for _ in 1...itemCount { value.append(try decodeFloat()) } } consumed = true default: return } } internal mutating func decodeSingularDoubleField(value: inout Double) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } value = try decodeDouble() consumed = true } internal mutating func decodeSingularDoubleField(value: inout Double?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } value = try decodeDouble() consumed = true } internal mutating func decodeRepeatedDoubleField(value: inout [Double]) throws { switch fieldWireFormat { case WireFormat.fixed64: let i = try decodeDouble() value.append(i) consumed = true case WireFormat.lengthDelimited: let bodyBytes = try decodeVarint() if bodyBytes > 0 { let itemSize = UInt64(MemoryLayout<Double>.size) let itemCount = bodyBytes / itemSize if bodyBytes % itemSize != 0 || bodyBytes > available { throw BinaryDecodingError.truncated } value.reserveCapacity(value.count + Int(truncatingIfNeeded: itemCount)) for _ in 1...itemCount { let i = try decodeDouble() value.append(i) } } consumed = true default: return } } internal mutating func decodeSingularInt32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeSingularInt32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeRepeatedInt32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(Int32(truncatingIfNeeded: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(Int32(truncatingIfNeeded: varint)) } consumed = true default: return } } internal mutating func decodeSingularInt64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.varint else { return } let v = try decodeVarint() value = Int64(bitPattern: v) consumed = true } internal mutating func decodeSingularInt64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = Int64(bitPattern: varint) consumed = true } internal mutating func decodeRepeatedInt64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(Int64(bitPattern: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(Int64(bitPattern: varint)) } consumed = true default: return } } internal mutating func decodeSingularUInt32Field(value: inout UInt32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = UInt32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeSingularUInt32Field(value: inout UInt32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = UInt32(truncatingIfNeeded: varint) consumed = true } internal mutating func decodeRepeatedUInt32Field(value: inout [UInt32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(UInt32(truncatingIfNeeded: varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(UInt32(truncatingIfNeeded: t)) } consumed = true default: return } } internal mutating func decodeSingularUInt64Field(value: inout UInt64) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() consumed = true } internal mutating func decodeSingularUInt64Field(value: inout UInt64?) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() consumed = true } internal mutating func decodeRepeatedUInt64Field(value: inout [UInt64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(varint) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(t) } consumed = true default: return } } internal mutating func decodeSingularSInt32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value = ZigZag.decoded(t) consumed = true } internal mutating func decodeSingularSInt32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value = ZigZag.decoded(t) consumed = true } internal mutating func decodeRepeatedSInt32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value.append(ZigZag.decoded(t)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() let t = UInt32(truncatingIfNeeded: varint) value.append(ZigZag.decoded(t)) } consumed = true default: return } } internal mutating func decodeSingularSInt64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = ZigZag.decoded(varint) consumed = true } internal mutating func decodeSingularSInt64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() value = ZigZag.decoded(varint) consumed = true } internal mutating func decodeRepeatedSInt64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(ZigZag.decoded(varint)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let varint = try decoder.decodeVarint() value.append(ZigZag.decoded(varint)) } consumed = true default: return } } internal mutating func decodeSingularFixed32Field(value: inout UInt32) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value = UInt32(littleEndian: i) consumed = true } internal mutating func decodeSingularFixed32Field(value: inout UInt32?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value = UInt32(littleEndian: i) consumed = true } internal mutating func decodeRepeatedFixed32Field(value: inout [UInt32]) throws { switch fieldWireFormat { case WireFormat.fixed32: var i: UInt32 = 0 try decodeFourByteNumber(value: &i) value.append(UInt32(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<UInt32>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: UInt32 = 0 while !decoder.complete { try decoder.decodeFourByteNumber(value: &i) value.append(UInt32(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularFixed64Field(value: inout UInt64) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value = UInt64(littleEndian: i) consumed = true } internal mutating func decodeSingularFixed64Field(value: inout UInt64?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value = UInt64(littleEndian: i) consumed = true } internal mutating func decodeRepeatedFixed64Field(value: inout [UInt64]) throws { switch fieldWireFormat { case WireFormat.fixed64: var i: UInt64 = 0 try decodeEightByteNumber(value: &i) value.append(UInt64(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<UInt64>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: UInt64 = 0 while !decoder.complete { try decoder.decodeEightByteNumber(value: &i) value.append(UInt64(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularSFixed32Field(value: inout Int32) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: Int32 = 0 try decodeFourByteNumber(value: &i) value = Int32(littleEndian: i) consumed = true } internal mutating func decodeSingularSFixed32Field(value: inout Int32?) throws { guard fieldWireFormat == WireFormat.fixed32 else { return } var i: Int32 = 0 try decodeFourByteNumber(value: &i) value = Int32(littleEndian: i) consumed = true } internal mutating func decodeRepeatedSFixed32Field(value: inout [Int32]) throws { switch fieldWireFormat { case WireFormat.fixed32: var i: Int32 = 0 try decodeFourByteNumber(value: &i) value.append(Int32(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<Int32>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: Int32 = 0 while !decoder.complete { try decoder.decodeFourByteNumber(value: &i) value.append(Int32(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularSFixed64Field(value: inout Int64) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: Int64 = 0 try decodeEightByteNumber(value: &i) value = Int64(littleEndian: i) consumed = true } internal mutating func decodeSingularSFixed64Field(value: inout Int64?) throws { guard fieldWireFormat == WireFormat.fixed64 else { return } var i: Int64 = 0 try decodeEightByteNumber(value: &i) value = Int64(littleEndian: i) consumed = true } internal mutating func decodeRepeatedSFixed64Field(value: inout [Int64]) throws { switch fieldWireFormat { case WireFormat.fixed64: var i: Int64 = 0 try decodeEightByteNumber(value: &i) value.append(Int64(littleEndian: i)) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.reserveCapacity(value.count + n / MemoryLayout<Int64>.size) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) var i: Int64 = 0 while !decoder.complete { try decoder.decodeEightByteNumber(value: &i) value.append(Int64(littleEndian: i)) } consumed = true default: return } } internal mutating func decodeSingularBoolField(value: inout Bool) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() != 0 consumed = true } internal mutating func decodeSingularBoolField(value: inout Bool?) throws { guard fieldWireFormat == WireFormat.varint else { return } value = try decodeVarint() != 0 consumed = true } internal mutating func decodeRepeatedBoolField(value: inout [Bool]) throws { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() value.append(varint != 0) consumed = true case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var decoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !decoder.complete { let t = try decoder.decodeVarint() value.append(t != 0) } consumed = true default: return } } internal mutating func decodeSingularStringField(value: inout String) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value = s consumed = true } else { throw BinaryDecodingError.invalidUTF8 } } internal mutating func decodeSingularStringField(value: inout String?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value = s consumed = true } else { throw BinaryDecodingError.invalidUTF8 } } internal mutating func decodeRepeatedStringField(value: inout [String]) throws { switch fieldWireFormat { case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) if let s = utf8ToString(bytes: p, count: n) { value.append(s) consumed = true } else { throw BinaryDecodingError.invalidUTF8 } default: return } } internal mutating func decodeSingularBytesField(value: inout Data) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value = Data(bytes: p, count: n) consumed = true } internal mutating func decodeSingularBytesField(value: inout Data?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value = Data(bytes: p, count: n) consumed = true } internal mutating func decodeRepeatedBytesField(value: inout [Data]) throws { switch fieldWireFormat { case WireFormat.lengthDelimited: var n: Int = 0 let p = try getFieldBodyBytes(count: &n) value.append(Data(bytes: p, count: n)) consumed = true default: return } } internal mutating func decodeSingularEnumField<E: Enum>(value: inout E?) throws where E.RawValue == Int { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value = v consumed = true } } internal mutating func decodeSingularEnumField<E: Enum>(value: inout E) throws where E.RawValue == Int { guard fieldWireFormat == WireFormat.varint else { return } let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value = v consumed = true } } internal mutating func decodeRepeatedEnumField<E: Enum>(value: inout [E]) throws where E.RawValue == Int { switch fieldWireFormat { case WireFormat.varint: let varint = try decodeVarint() if let v = E(rawValue: Int(Int32(truncatingIfNeeded: varint))) { value.append(v) consumed = true } case WireFormat.lengthDelimited: var n: Int = 0 var extras: [Int32]? let p = try getFieldBodyBytes(count: &n) let ints = Varint.countVarintsInBuffer(start: p, count: n) value.reserveCapacity(value.count + ints) var subdecoder = BinaryDecoder(forReadingFrom: p, count: n, parent: self) while !subdecoder.complete { let u64 = try subdecoder.decodeVarint() let i32 = Int32(truncatingIfNeeded: u64) if let v = E(rawValue: Int(i32)) { value.append(v) } else if !options.discardUnknownFields { if extras == nil { extras = [] } extras!.append(i32) } } if let extras = extras { let fieldTag = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited) let bodySize = extras.reduce(0) { $0 + Varint.encodedSize(of: Int64($1)) } let fieldSize = Varint.encodedSize(of: fieldTag.rawValue) + Varint.encodedSize(of: Int64(bodySize)) + bodySize var field = Data(count: fieldSize) field.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var encoder = BinaryEncoder(forWritingInto: baseAddress) encoder.startField(tag: fieldTag) encoder.putVarInt(value: Int64(bodySize)) for v in extras { encoder.putVarInt(value: Int64(v)) } } } unknownOverride = field } consumed = true default: return } } internal mutating func decodeSingularMessageField<M: Message>(value: inout M?) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var count: Int = 0 let p = try getFieldBodyBytes(count: &count) if value == nil { value = M() } var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) try subDecoder.decodeFullMessage(message: &value!) consumed = true } internal mutating func decodeRepeatedMessageField<M: Message>(value: inout [M]) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var newValue = M() var subDecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) try subDecoder.decodeFullMessage(message: &newValue) value.append(newValue) consumed = true } internal mutating func decodeFullMessage<M: Message>(message: inout M) throws { assert(unknownData == nil) try incrementRecursionDepth() try message.decodeMessage(decoder: &self) decrementRecursionDepth() guard complete else { throw BinaryDecodingError.trailingGarbage } if let unknownData = unknownData { message.unknownFields.append(protobufData: unknownData) } } internal mutating func decodeSingularGroupField<G: Message>(value: inout G?) throws { var group = value ?? G() if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) { value = group consumed = true } } internal mutating func decodeRepeatedGroupField<G: Message>(value: inout [G]) throws { var group = G() if try decodeFullGroup(group: &group, fieldNumber: fieldNumber) { value.append(group) consumed = true } } private mutating func decodeFullGroup<G: Message>(group: inout G, fieldNumber: Int) throws -> Bool { guard fieldWireFormat == WireFormat.startGroup else { return false } try incrementRecursionDepth() // This works by making a clone of the current decoder state and // setting `groupFieldNumber` to signal `nextFieldNumber()` to watch // for that as a marker for having reached the end of a group/message. // Groups within groups works because this effectively makes a stack // of decoders, each one looking for their ending tag. var subDecoder = self subDecoder.groupFieldNumber = fieldNumber // startGroup was read, so current tag/data is done (otherwise the // startTag will end up in the unknowns of the first thing decoded). subDecoder.consumed = true // The group (message) doesn't get any existing unknown fields from // the parent. subDecoder.unknownData = nil try group.decodeMessage(decoder: &subDecoder) guard subDecoder.fieldNumber == fieldNumber && subDecoder.fieldWireFormat == .endGroup else { throw BinaryDecodingError.truncated } if let groupUnknowns = subDecoder.unknownData { group.unknownFields.append(protobufData: groupUnknowns) } // Advance over what was parsed. consume(length: available - subDecoder.available) assert(recursionBudget == subDecoder.recursionBudget) decrementRecursionDepth() return true } internal mutating func decodeMapField<KeyType, ValueType: MapValueType>(fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: inout _ProtobufMap<KeyType, ValueType>.BaseType) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType.BaseType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: try ValueType.decodeSingular(value: &v, from: &subdecoder) default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys/values, // so it is safe to use the proto3 default to get the right // integer/string/bytes. The one catch is a proto2 enum (which can be the // value) can have a non zero value, but that case is the next // custom decodeMapField<>() method and handles it. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType.proto3DefaultValue consumed = true } internal mutating func decodeMapField<KeyType, ValueType>(fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: inout _ProtobufEnumMap<KeyType, ValueType>.BaseType) throws where ValueType.RawValue == Int { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: // Keys are basic types try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: // Value is an Enum type try subdecoder.decodeSingularEnumField(value: &v) if v == nil && tag.wireFormat == .varint { // Enum decode fail and wire format was varint, so this had to // have been a proto2 unknown enum value. This whole map entry // into the parent message's unknown fields. If the wire format // was wrong, treat it like an unknown field and drop it with // the map entry. return } default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys, so it // is safe to use the proto3 default to get the right integer/string/bytes. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType() consumed = true } internal mutating func decodeMapField<KeyType, ValueType>(fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: inout _ProtobufMessageMap<KeyType, ValueType>.BaseType) throws { guard fieldWireFormat == WireFormat.lengthDelimited else { return } var k: KeyType.BaseType? var v: ValueType? var count: Int = 0 let p = try getFieldBodyBytes(count: &count) var subdecoder = BinaryDecoder(forReadingFrom: p, count: count, parent: self) while let tag = try subdecoder.getTag() { if tag.wireFormat == .endGroup { throw BinaryDecodingError.malformedProtobuf } let fieldNumber = tag.fieldNumber switch fieldNumber { case 1: // Keys are basic types try KeyType.decodeSingular(value: &k, from: &subdecoder) case 2: // Value is a message type try subdecoder.decodeSingularMessageField(value: &v) default: // Skip any other fields within the map entry object try subdecoder.skip() } } if !subdecoder.complete { throw BinaryDecodingError.trailingGarbage } // A map<> definition can't provide a default value for the keys, so it // is safe to use the proto3 default to get the right integer/string/bytes. value[k ?? KeyType.proto3DefaultValue] = v ?? ValueType() consumed = true } internal mutating func decodeExtensionField( values: inout ExtensionFieldValueSet, messageType: Message.Type, fieldNumber: Int ) throws { if let ext = extensions?[messageType, fieldNumber] { try decodeExtensionField(values: &values, messageType: messageType, fieldNumber: fieldNumber, messageExtension: ext) } } /// Helper to reuse between Extension decoding and MessageSet Extension decoding. private mutating func decodeExtensionField( values: inout ExtensionFieldValueSet, messageType: Message.Type, fieldNumber: Int, messageExtension ext: AnyMessageExtension ) throws { assert(!consumed) assert(fieldNumber == ext.fieldNumber) try values.modify(index: fieldNumber) { fieldValue in // Message/Group extensions both will call back into the matching // decode methods, so the recursion depth will be tracked there. if fieldValue != nil { try fieldValue!.decodeExtensionField(decoder: &self) } else { fieldValue = try ext._protobuf_newField(decoder: &self) } if consumed && fieldValue == nil { // Really things should never get here, if the decoder says // the bytes were consumed, then there should have been a // field that consumed them (existing or created). This // specific error result is to allow this to be more detectable. throw BinaryDecodingError.internalExtensionError } } } internal mutating func decodeExtensionFieldsAsMessageSet( values: inout ExtensionFieldValueSet, messageType: Message.Type ) throws { // Spin looking for the Item group, everything else will end up in unknown fields. while let fieldNumber = try self.nextFieldNumber() { guard fieldNumber == WireFormat.MessageSet.FieldNumbers.item && fieldWireFormat == WireFormat.startGroup else { continue } // This is similiar to decodeFullGroup try incrementRecursionDepth() var subDecoder = self subDecoder.groupFieldNumber = fieldNumber subDecoder.consumed = true let itemResult = try subDecoder.decodeMessageSetItem(values: &values, messageType: messageType) switch itemResult { case .success: // Advance over what was parsed. consume(length: available - subDecoder.available) consumed = true case .handleAsUnknown: // Nothing to do. break case .malformed: throw BinaryDecodingError.malformedProtobuf } assert(recursionBudget == subDecoder.recursionBudget) decrementRecursionDepth() } } private enum DecodeMessageSetItemResult { case success case handleAsUnknown case malformed } private mutating func decodeMessageSetItem( values: inout ExtensionFieldValueSet, messageType: Message.Type ) throws -> DecodeMessageSetItemResult { // This is loosely based on the C++: // ExtensionSet::ParseMessageSetItem() // WireFormat::ParseAndMergeMessageSetItem() // (yes, there have two versions that are almost the same) var msgExtension: AnyMessageExtension? var fieldData: Data? // In this loop, if wire types are wrong, things don't decode, // just bail instead of letting things go into unknown fields. // Wrongly formed MessageSets don't seem don't have real // spelled out behaviors. while let fieldNumber = try self.nextFieldNumber() { switch fieldNumber { case WireFormat.MessageSet.FieldNumbers.typeId: var extensionFieldNumber: Int32 = 0 try decodeSingularInt32Field(value: &extensionFieldNumber) if extensionFieldNumber == 0 { return .malformed } guard let ext = extensions?[messageType, Int(extensionFieldNumber)] else { return .handleAsUnknown // Unknown extension. } msgExtension = ext // If there already was fieldData, decode it. if let data = fieldData { var wasDecoded = false try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var extDecoder = BinaryDecoder(forReadingFrom: baseAddress, count: body.count, parent: self) // Prime the decode to be correct. extDecoder.consumed = false extDecoder.fieldWireFormat = .lengthDelimited try extDecoder.decodeExtensionField(values: &values, messageType: messageType, fieldNumber: fieldNumber, messageExtension: ext) wasDecoded = extDecoder.consumed } } if !wasDecoded { return .malformed } fieldData = nil } case WireFormat.MessageSet.FieldNumbers.message: if let ext = msgExtension { assert(consumed == false) try decodeExtensionField(values: &values, messageType: messageType, fieldNumber: ext.fieldNumber, messageExtension: ext) if !consumed { return .malformed } } else { // The C++ references ends up appending the blocks together as length // delimited blocks, but the parsing will only use the first block. // So just capture a block, and then skip any others that happen to // be found. if fieldData == nil { var d: Data? try decodeSingularBytesField(value: &d) guard let data = d else { return .malformed } // Save it as length delimited let payloadSize = Varint.encodedSize(of: Int64(data.count)) + data.count var payload = Data(count: payloadSize) payload.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in if let baseAddress = body.baseAddress, body.count > 0 { var encoder = BinaryEncoder(forWritingInto: baseAddress) encoder.putBytesValue(value: data) } } fieldData = payload } else { guard fieldWireFormat == .lengthDelimited else { return .malformed } try skip() consumed = true } } default: // Skip everything else try skip() consumed = true } } return .success } // // Private building blocks for the parsing above. // // Having these be private gives the compiler maximum latitude for // inlining. // /// Private: Advance the current position. private mutating func consume(length: Int) { available -= length p += length } /// Private: Skip the body for the given tag. If the given tag is /// a group, it parses up through the corresponding group end. private mutating func skipOver(tag: FieldTag) throws { switch tag.wireFormat { case .varint: // Don't need the value, just ensuring it is validly encoded. let _ = try decodeVarint() case .fixed64: if available < 8 { throw BinaryDecodingError.truncated } p += 8 available -= 8 case .lengthDelimited: let n = try decodeVarint() if n <= UInt64(available) { p += Int(n) available -= Int(n) } else { throw BinaryDecodingError.truncated } case .startGroup: try incrementRecursionDepth() while true { if let innerTag = try getTagWithoutUpdatingFieldStart() { if innerTag.wireFormat == .endGroup { if innerTag.fieldNumber == tag.fieldNumber { decrementRecursionDepth() break } else { // .endGroup for a something other than the current // group is an invalid binary. throw BinaryDecodingError.malformedProtobuf } } else { try skipOver(tag: innerTag) } } else { throw BinaryDecodingError.truncated } } case .endGroup: throw BinaryDecodingError.malformedProtobuf case .fixed32: if available < 4 { throw BinaryDecodingError.truncated } p += 4 available -= 4 } } /// Private: Skip to the end of the current field. /// /// Assumes that fieldStartP was bookmarked by a previous /// call to getTagType(). /// /// On exit, fieldStartP points to the first byte of the tag, fieldEndP points /// to the first byte after the field contents, and p == fieldEndP. private mutating func skip() throws { if let end = fieldEndP { p = end } else { // Rewind to start of current field. available += p - fieldStartP p = fieldStartP guard let tag = try getTagWithoutUpdatingFieldStart() else { throw BinaryDecodingError.truncated } try skipOver(tag: tag) fieldEndP = p } } /// Private: Parse the next raw varint from the input. private mutating func decodeVarint() throws -> UInt64 { if available < 1 { throw BinaryDecodingError.truncated } var start = p var length = available var c = start.load(fromByteOffset: 0, as: UInt8.self) start += 1 length -= 1 if c & 0x80 == 0 { p = start available = length return UInt64(c) } var value = UInt64(c & 0x7f) var shift = UInt64(7) while true { if length < 1 || shift > 63 { throw BinaryDecodingError.malformedProtobuf } c = start.load(fromByteOffset: 0, as: UInt8.self) start += 1 length -= 1 value |= UInt64(c & 0x7f) << shift if c & 0x80 == 0 { p = start available = length return value } shift += 7 } } /// Private: Get the tag that starts a new field. /// This also bookmarks the start of field for a possible skip(). internal mutating func getTag() throws -> FieldTag? { fieldStartP = p fieldEndP = nil return try getTagWithoutUpdatingFieldStart() } /// Private: Parse and validate the next tag without /// bookmarking the start of the field. This is used within /// skip() to skip over fields within a group. private mutating func getTagWithoutUpdatingFieldStart() throws -> FieldTag? { if available < 1 { return nil } let t = try decodeVarint() if t < UInt64(UInt32.max) { guard let tag = FieldTag(rawValue: UInt32(truncatingIfNeeded: t)) else { throw BinaryDecodingError.malformedProtobuf } fieldWireFormat = tag.wireFormat fieldNumber = tag.fieldNumber return tag } else { throw BinaryDecodingError.malformedProtobuf } } /// Private: Return a Data containing the entirety of /// the current field, including tag. private mutating func getRawField() throws -> Data { try skip() return Data(bytes: fieldStartP, count: fieldEndP! - fieldStartP) } /// Private: decode a fixed-length four-byte number. This generic /// helper handles all four-byte number types. private mutating func decodeFourByteNumber<T>(value: inout T) throws { guard available >= 4 else {throw BinaryDecodingError.truncated} withUnsafeMutableBytes(of: &value) { dest -> Void in dest.copyMemory(from: UnsafeRawBufferPointer(start: p, count: 4)) } consume(length: 4) } /// Private: decode a fixed-length eight-byte number. This generic /// helper handles all eight-byte number types. private mutating func decodeEightByteNumber<T>(value: inout T) throws { guard available >= 8 else {throw BinaryDecodingError.truncated} withUnsafeMutableBytes(of: &value) { dest -> Void in dest.copyMemory(from: UnsafeRawBufferPointer(start: p, count: 8)) } consume(length: 8) } private mutating func decodeFloat() throws -> Float { var littleEndianBytes: UInt32 = 0 try decodeFourByteNumber(value: &littleEndianBytes) var nativeEndianBytes = UInt32(littleEndian: littleEndianBytes) var float: Float = 0 let n = MemoryLayout<Float>.size memcpy(&float, &nativeEndianBytes, n) return float } private mutating func decodeDouble() throws -> Double { var littleEndianBytes: UInt64 = 0 try decodeEightByteNumber(value: &littleEndianBytes) var nativeEndianBytes = UInt64(littleEndian: littleEndianBytes) var double: Double = 0 let n = MemoryLayout<Double>.size memcpy(&double, &nativeEndianBytes, n) return double } /// Private: Get the start and length for the body of // a length-delimited field. private mutating func getFieldBodyBytes(count: inout Int) throws -> UnsafeRawPointer { let length = try decodeVarint() if length <= UInt64(available) { count = Int(length) let body = p consume(length: count) return body } throw BinaryDecodingError.truncated } }
37.425776
216
0.562841
87004e25ae296543a473282a62478993bba7ac49
625
// // Extension+Int.swift // CARTE // // Created by tomoki.koga on 2019/06/05. // Copyright © 2019 PLAID, inc. All rights reserved. // import Foundation extension Int: ExtensionCompatible {} extension Extension where Base == Int { var comma: String { let formatter = NumberFormatter() formatter.numberStyle = NumberFormatter.Style.decimal formatter.groupingSeparator = "," formatter.groupingSize = 3 guard let digits = formatter.string(from: NSNumber(value: base as Int)) else { return String(base) } return digits } }
22.321429
86
0.6224
bfa24af04aa609dd3d894f786425803e43d71d61
6,897
import XCTest @testable import MapboxMaps final class LocationManagerTests: XCTestCase { var locationProducer: MockLocationProducer! var puckManager: MockPuckManager! var locationManager: LocationManager! override func setUp() { super.setUp() locationProducer = MockLocationProducer() puckManager = MockPuckManager() locationManager = LocationManager( locationProducer: locationProducer, puckManager: puckManager) } override func tearDown() { locationManager = nil puckManager = nil locationProducer = nil super.tearDown() } func testLocationManagerDefaultInitialization() { XCTAssertEqual(locationManager.options, LocationOptions()) XCTAssertNil(locationManager.delegate) XCTAssertEqual(locationProducer.locationProvider.locationProviderOptions, locationManager.options) XCTAssertEqual(puckManager.puckType, locationManager.options.puckType) XCTAssertEqual(puckManager.puckBearingSource, locationManager.options.puckBearingSource) } func testLatestLocationWhenLocationProducerLatestLocationIsNil() { locationProducer.latestLocation = nil XCTAssertNil(locationManager.latestLocation) } func testLatestLocationWhenLocationProducerLatestLocationIsNonNil() { locationProducer.latestLocation = Location(location: CLLocation(), heading: nil, accuracyAuthorization: .fullAccuracy) XCTAssertTrue(locationManager.latestLocation === locationProducer.latestLocation) } func testLocationProvider() throws { // Note that LocationProvider is not class-bound and may be implemented by a struct or enum. // We should change this in the future, but for now, we cast to AnyObject. If the actual // value is a struct or enum, Swift automatically boxes it into an object (and this test will // fail since the two boxed objects wouldn't be identical), but in this situation we expect // it to always be a class. XCTAssertTrue((locationManager.locationProvider as AnyObject) === (locationProducer.locationProvider as AnyObject)) } func testConsumers() { XCTAssertTrue(locationManager.consumers === locationProducer.consumers) } func testOptionsArePropagatedToLocationProducerAndPuckManager() { var options = LocationOptions() options.distanceFilter = .random(in: 0..<100) options.desiredAccuracy = .random(in: 0..<100) options.activityType = [.automotiveNavigation, .fitness, .other, .otherNavigation].randomElement()! options.puckType = [.puck2D(), .puck3D(Puck3DConfiguration(model: Model()))].randomElement()! options.puckBearingSource = [.heading, .course].randomElement()! locationManager.options = options XCTAssertEqual(locationProducer.locationProvider.locationProviderOptions, options) XCTAssertEqual(puckManager.puckType, options.puckType) XCTAssertEqual(puckManager.puckBearingSource, options.puckBearingSource) } func testOptionsPropagationDoesNotInvokeLocationProviderSetterWhenItIsAClass() { locationManager.options = LocationOptions() XCTAssertTrue(locationProducer.didSetLocationProviderStub.invocations.isEmpty) } func testOptionsPropagationDoesInvokeLocationProviderSetterWhenItIsAValueType() { locationManager.overrideLocationProvider(with: MockLocationProviderStruct()) locationProducer.didSetLocationProviderStub.reset() locationManager.options = LocationOptions() XCTAssertEqual(locationProducer.didSetLocationProviderStub.invocations.count, 1) } func testOverrideLocationProvider() { let customLocationProvider = MockLocationProvider() locationManager.overrideLocationProvider(with: customLocationProvider) // Note that LocationProvider is not class-bound and may be implemented by a struct or enum. // We should change this in the future, but for now, we cast to AnyObject. If the actual // value is a struct or enum, Swift automatically boxes it into an object (and this test will // fail since the boxed object wouldn't be identical to the one created above), but in this // situation we expect it to always be a class. XCTAssertTrue((locationProducer.locationProvider as AnyObject) === customLocationProvider) } func testAddLocationConsumer() { let consumer = MockLocationConsumer() locationManager.addLocationConsumer(newConsumer: consumer) XCTAssertEqual(locationProducer.addStub.invocations.count, 1) XCTAssertTrue(locationProducer.addStub.parameters.first === consumer) } func testRemoveLocationConsumer() { let consumer = MockLocationConsumer() locationManager.removeLocationConsumer(consumer: consumer) XCTAssertEqual(locationProducer.removeStub.invocations.count, 1) XCTAssertTrue(locationProducer.removeStub.parameters.first === consumer) } @available(iOS 14.0, *) func testRequestTemporaryFullAccuracyPermissions() throws { let purposeKey = String.randomASCII(withLength: .random(in: 10...20)) locationManager.requestTemporaryFullAccuracyPermissions(withPurposeKey: purposeKey) let locationProvider = try XCTUnwrap(locationProducer.locationProvider as? MockLocationProvider) XCTAssertEqual(locationProvider.requestTemporaryFullAccuracyAuthorizationStub.parameters, [purposeKey]) } func testLocationProducerDidFailWithError() { let error = MockError() let delegate = MockLocationPermissionsDelegate() locationManager.delegate = delegate locationManager.locationProducer(locationProducer, didFailWithError: error) XCTAssertEqual(delegate.didFailToLocateUserWithErrorStub.invocations.count, 1) XCTAssertTrue(delegate.didFailToLocateUserWithErrorStub.parameters.first?.locationManager === locationManager) XCTAssertTrue(delegate.didFailToLocateUserWithErrorStub.parameters.first?.error as? MockError === error) } func testLocationProducerDidChangeAccuracyAuthorization() { let accuracyAuthorization: CLAccuracyAuthorization = [.fullAccuracy, .reducedAccuracy].randomElement()! let delegate = MockLocationPermissionsDelegate() locationManager.delegate = delegate locationManager.locationProducer(locationProducer, didChangeAccuracyAuthorization: accuracyAuthorization) XCTAssertEqual(delegate.didChangeAccuracyAuthorizationStub.invocations.count, 1) XCTAssertTrue(delegate.didChangeAccuracyAuthorizationStub.parameters.first?.locationManager === locationManager) XCTAssertEqual(delegate.didChangeAccuracyAuthorizationStub.parameters.first?.accuracyAuthorization, accuracyAuthorization) } }
44.785714
130
0.747716
ebbd307bd4472bf93250d3a22c3c0a0a10915cef
1,266
// // UniSelectionFieldUITests.swift // UniSelectionFieldUITests // // Created by Leo Chang on 8/19/16. // Copyright © 2016 Unigreen. All rights reserved. // import XCTest class UniSelectionFieldUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.216216
182
0.669036
79910669f8ee3d3fad6769651b921f8281f9e7cd
7,421
// // SelectEmojisViewController.swift // Emojilist // // Created by Thiago Ricieri on 11/01/2018. // Copyright © 2018 Ghost Ship. All rights reserved. // import Foundation import UIKit import Spring class SelectEmojisViewController: BaseCollectionViewController, SelectPackDelegate { var viewModel: SelectEmojisViewModel! var passListViewModel: EmojiListViewModel! @IBOutlet weak var animationContainer: UIView! @IBOutlet weak var createButton: UIButton! @IBOutlet weak var selectedPackButton: UIButton! @IBOutlet weak var badgeView: SpringView! @IBOutlet weak var badgeCountLabel: UILabel! @IBOutlet weak var clearBarItem: UIBarButtonItem! @IBOutlet weak var itemsInListLabel: UILabel! @IBOutlet weak var separator: UIView! @IBOutlet weak var topFadeDecoration: UIImageView! @IBOutlet weak var bottomFadeDecoration: UIImageView! @IBOutlet weak var indicatorDecoration: UIImageView! // Extra collection @IBOutlet weak var basketCollection: UICollectionView! override func instantiateDependencies() { baseViewModel = SelectEmojisViewModel(listViewModel: passListViewModel) viewModel = baseViewModel as! SelectEmojisViewModel } override func applyTheme(_ theme: Theme) { super.applyTheme(theme) theme.separator(separator) theme.background(basketCollection) theme.actionButton(createButton) theme.badge(badgeView) theme.secondaryText(itemsInListLabel) topFadeDecoration.image = UIImage(named: theme.topDecoration()) bottomFadeDecoration.image = UIImage(named: theme.bottomDecoration()) indicatorDecoration.image = UIImage(named: theme.indicatorDecoration()) } override func setViewStyle() { title = viewModel.listName createButton.setTitle(viewModel.createButtonLabel.localized, for: .normal) createButton.setTitle(viewModel.createButtonLabel.localized, for: .disabled) clearBarItem.title = "SelectEmojis.Clear".localized itemsInListLabel.text = "SelectEmojis.ItemsInList".localized badgeView.layer.cornerRadius = badgeView.bounds.width/2 badgeView.clipsToBounds = true updateBasket() } override func reload() { super.reload() selectedPackButton.setTitle(viewModel.localizedPackName, for: .normal) } // MARK: - Collection View Boilerplate override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let emoji: EmojiPackItemViewModel! if collectionView == collection { emoji = viewModel.item(at: indexPath) } else { emoji = viewModel.item(selectedAt: indexPath) } if !emoji.hasImage { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: AsciiEmojiCell.identifier, for: indexPath) as! AsciiEmojiCell cell.configure(with: emoji) return cell } else { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: ImageEmojiCell.identifier, for: indexPath) as! ImageEmojiCell cell.configure(with: emoji) return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: false) if collectionView == collection { viewModel.select(emojiAt: indexPath) if let cell = collectionView.cellForItem(at: indexPath) as? BaseEmojiCell { cell.springView.animation = "pop" cell.springView.curve = "easeOut" cell.springView.duration = 0.5 cell.springView.animate() } lightImpact() updateBasket() addIndexToBasked(IndexPath(item: 0, section: 0)) } else { viewModel.remove(emojiAt: indexPath) updateBasket() lightImpact() removeIndexFromBasket(indexPath) } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == collection { return viewModel.itemsCount } else { return viewModel.selectedCount } } // MARK: - Pack Selection Delegate func packSelected(pack: EmojiPackViewModel) { viewModel.source = pack navigationController?.popViewController(animated: true) reload() } func selectedPack() -> EmojiPackViewModel { return viewModel.source } // MARK: - Handle Basket func addIndexToBasked(_ indexPath: IndexPath) { basketCollection.performBatchUpdates({ self.basketCollection.insertItems(at: [indexPath]) }, completion: nil) } func removeIndexFromBasket(_ indexPath: IndexPath) { basketCollection.performBatchUpdates({ self.basketCollection.deleteItems(at: [indexPath]) }, completion: nil) } func updateBasket() { let count = viewModel.selectedCount! if count > 0 { badgeView.isHidden = false createButton.isEnabled = true badgeCountLabel.text = viewModel.selectedCountText badgeView.animation = "pop" badgeView.curve = "easeInOut" badgeView.animate() } else { badgeView.isHidden = true createButton.isEnabled = false } if count >= 1 && count <= 2 && itemsInListLabel.alpha == 0 { UIView.animate(withDuration: 0.6) { self.itemsInListLabel.alpha = 1 } } else if (count == 0 || count > 2) && itemsInListLabel.alpha == 1 { UIView.animate(withDuration: 0.6) { self.itemsInListLabel.alpha = 0 } } } // MARK: - Connect to Selection of Pack override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == MainStoryboard.Segue.toSelectPack { let dest = segue.destination as! SelectPackViewController dest.delegate = self } } // MARK: - Actions @IBAction func actionCreate(sender: Any) { if viewModel.shouldUpdateList { viewModel.updateList() } else { viewModel.createList() } navigationController?.popToRootViewController(animated: true) } @IBAction func actionSelectedPack(sender: Any) { performSegue(withIdentifier: MainStoryboard.Segue.toSelectPack, sender: nil) } @IBAction func actionClear(_ sender: Any) { var allIndexes = [IndexPath]() for i in 0...viewModel.selectedCount - 1 { allIndexes.append(IndexPath(item: i, section: 0)) } viewModel.clearList() updateBasket() basketCollection.performBatchUpdates({ self.basketCollection.deleteItems(at: allIndexes) }, completion: nil) } }
33.579186
98
0.619593
33400b0d5d5d370ed1f5718181068f68f9098e84
10,140
// // SocketClient.swift // Hippo // // Created by Arohi Sharma on 21/10/20. // Copyright © 2020 CL-macmini-88. All rights reserved. // import Foundation import SocketIO class SocketClient: NSObject { // MARK: Properties static var shared = SocketClient() private var manager: SocketManager? var socket: SocketIOClient? let channelPrefix = "/" var subscribedChannel = [String : Bool]() //MARK:- Listeners private var onConnectCallBack : ((Array<Any>, SocketAckEmitter) -> ())! private var onDisconnectCallBack : ((Array<Any>, SocketAckEmitter) -> ())! private var handshakeListener : ((Array<Any>, SocketAckEmitter) -> ())! private var subscribeChannelListener : ((Array<Any>, SocketAckEmitter) -> ())! private var unsubscribeChannelListener : ((Array<Any>, SocketAckEmitter) -> ())! private var authentication: [String: Any]{ get { var authData = [String : Any]() authData["en_user_id"] = currentEnUserId() let currentTimeInterval = Int(NSDate().timeIntervalSince1970 * 1000) let difference = HippoConfig.shared.serverTimeDifference let timeToSend = (currentTimeInterval + difference) + (2 * 1000) let dateToSend = (Date(timeIntervalSince1970: TimeInterval(timeToSend/1000))).toUTCFormatString authData["created_at"] = "\(dateToSend)" authData["user_type"] = currentUserType().rawValue if currentUserType() == .agent { authData["access_token"] = HippoConfig.shared.agentDetail?.fuguToken ?? "" }else { authData["device_key"] = HippoConfig.shared.deviceKey } return authData } } // MARK: Computed properties private var socketURL: String { get { return HippoConfig.shared.fayeBaseURLString } } // MARK: Init private override init() { super.init() if currentUserType() == .customer && HippoConfig.shared.deviceKey == ""{ return }else if currentEnUserId() == ""{ return }else if currentUserType() == .agent && HippoConfig.shared.agentDetail?.fuguToken ?? "" == ""{ return } addObserver() deinitializeListeners() manager = nil socket = nil socketSetup() } func connect(){ SocketClient.shared = SocketClient() } func isConnected() -> Bool{ SocketClient.shared.socket?.status == .connected } // MARK: Methods private func socketSetup(){ let auth = jsonToString(json: authentication) let encryptedAuth = CryptoJS.AES().encrypt(auth, password: getSecretKey()) if let url = URL(string: socketURL){ manager = SocketManager(socketURL: url, config: [.reconnectWait(Int(2)), .reconnectAttempts(0), .compress, .forcePolling(false), .forceWebsockets(true), .connectParams(["auth_token" : encryptedAuth, "device_type" : Device_Type_iOS, "device_details" : AgentDetail.getDeviceDetails()])]) } socket = manager?.defaultSocket initListeners() initInitializer() socket?.connect() } func getSecretKey() -> String { let url = HippoConfig.shared.fayeBaseURLString switch url { case SERVERS.liveFaye: return PrivateSocketKeys.live.rawValue case SERVERS.betaFaye: return PrivateSocketKeys.beta.rawValue case SERVERS.devFaye: return PrivateSocketKeys.dev.rawValue default: return "" } } private func initListeners(){ onConnectCallBack = {[weak self](arr, ack) in NotificationCenter.default.post(name: .socketConnected, object: nil) if let userChannelId = HippoUserDetail.HippoUserChannelId, currentUserType() == .customer, self?.isChannelSubscribed(channel: userChannelId) == false{ SocketClient.shared.subscribeSocketChannel(channel: userChannelId) }else if let userChannelId = HippoConfig.shared.agentDetail?.userChannel, currentUserType() == .agent, self?.isChannelSubscribed(channel: userChannelId) == false{ SocketClient.shared.subscribeSocketChannel(channel: userChannelId) } self?.handshake() } onDisconnectCallBack = {(arr, ack) in NotificationCenter.default.post(name: .socketDisconnected, object: nil) } handshakeListener = {(arr, ack) in } subscribeChannelListener = {(arr, ack) in NotificationCenter.default.post(name: .channelSubscribed, object: nil) } unsubscribeChannelListener = {(arr, ack) in} } private func initInitializer(){ socket?.on(clientEvent: .connect, callback: onConnectCallBack) socket?.on(clientEvent: .disconnect, callback: onDisconnectCallBack) socket?.on(SocketEvent.HANDSHAKE_CHANNEL.rawValue, callback: handshakeListener) socket?.on(SocketEvent.SUBSCRIBE_CHAT.rawValue, callback: subscribeChannelListener) socket?.on(SocketEvent.SUBSCRIBE_USER.rawValue, callback: subscribeChannelListener) socket?.on(SocketEvent.UNSUBSCRIBE_CHAT.rawValue, callback: unsubscribeChannelListener) socket?.on(SocketEvent.UNSUBSCRIBE_USER.rawValue, callback: unsubscribeChannelListener) socket?.on(clientEvent: .error, callback: { (data, ack) in print("error", data) }) socket?.on(clientEvent: .pong, callback: { (data, ack) in }) socket?.on(clientEvent: .ping, callback: { (data, ack) in }) socket?.on(SocketEvent.MESSAGE_CHANNEL.rawValue, callback: { (data, ack) in }) } private func deinitializeListeners(){ //off socket events before initialization socket?.off(clientEvent: .connect) socket?.off(clientEvent: .disconnect) socket?.off(SocketEvent.HANDSHAKE_CHANNEL.rawValue) socket?.off(SocketEvent.SUBSCRIBE_CHAT.rawValue) socket?.off(SocketEvent.SUBSCRIBE_USER.rawValue) socket?.off(SocketEvent.UNSUBSCRIBE_CHAT.rawValue) socket?.off(SocketEvent.UNSUBSCRIBE_USER.rawValue) socket?.off(SocketEvent.MESSAGE_CHANNEL.rawValue) socket?.off(SocketEvent.SERVER_PUSH.rawValue) //release memory of calbacks onConnectCallBack = nil onDisconnectCallBack = nil handshakeListener = nil subscribeChannelListener = nil unsubscribeChannelListener = nil } @discardableResult func on(event: String, callback: @escaping ([Any]) -> Void) -> UUID? { return socket?.on(event) { (data, ack) in callback(data) } } func offEvent(for name: String){ socket?.off(name) } func isChannelSubscribed(channel : String)-> Bool{ return subscribedChannel.keys.contains(channel) && subscribedChannel[channel] == true } deinit { deinitializeListeners() socket?.removeAllHandlers() manager = nil socket = nil NotificationCenter.default.removeObserver(self) } func jsonToString(json: [String : Any]) -> String{ do { let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data guard let convertedString = String(data: data1, encoding: String.Encoding.utf8) else { return "" } // the data will be converted to the string return convertedString // <-- here is ur string } catch _ { return "" } } } extension SocketClient { enum SocketError: Int, Error { case fayeNotConnected = 400 case userBlocked = 401 case channelDoesNotExist = 407 case invalidThreadMuid = 408 case userDoesNotBelongToChannel = 409 case messageDeleted = 410 case invalidMuid = 411 case duplicateMuid = 412 case invalidSending = 413 case channelNotSubscribed = 4000 case invalidFileUrl = 418 case resendSameMessage = 420 case versionMismatch = 415 case personalInfoSharedError = 417 init?(reasonInfo: [String: Any]) { guard let statusCode = reasonInfo["statusCode"] as? Int else { return nil } guard let reason = SocketError(rawValue: statusCode) else { return nil } self = reason } } } extension Notification.Name { public static var socketConnected = Notification.Name.init("socketConnected") public static var socketDisconnected = Notification.Name.init("socketDisconnected") public static var channelSubscribed = Notification.Name.init("channelSubscribed") } extension SocketClient { func addObserver() { removeObserver() NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: HippoVariable.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterBackground), name: HippoVariable.didEnterBackgroundNotification, object: nil) } @objc private func applicationWillEnterForeground() { if SocketClient.shared.socket != nil{ if SocketClient.shared.socket?.status != .connected && SocketClient.shared.socket?.status != .connecting{ SocketClient.shared.connect() } } } @objc private func applicationEnterBackground() { if SocketClient.shared.socket?.status != .connected { SocketClient.shared.connect() } } func removeObserver() { NotificationCenter.default.removeObserver(self) } var isConnectionActive: Bool { return socket?.status.active ?? false } }
37.142857
297
0.630375
1eff51a24ae4962cdcc46c00c9f092a123ff7960
370
import UIKit class FilterSliderItem: TableItem { var filter: Filter weak var controlDelegate: FilterControlDelegate? init(filter: Filter, controlDelegate: FilterControlDelegate?) { self.filter = filter self.controlDelegate = controlDelegate } override func cellHeight(tableWidth: CGFloat) -> CGFloat { return 77.0 } }
21.764706
67
0.691892
1e0f6ebb3dd379b7111b02b6b41fc2c1a9c77d7f
2,655
import KsApi import Prelude import ReactiveExtensions import ReactiveSwift private struct CheckoutRetryError: Error {} public protocol CheckoutRacingViewModelInputs { /// Configure with the checkout URL. func configureWith(url: URL) } public protocol CheckoutRacingViewModelOutputs { /// Emits when an alert should be shown. var showAlert: Signal<String, Never> { get } /// Emits when the checkout's state is successful. var goToThanks: Signal<Void, Never> { get } } public protocol CheckoutRacingViewModelType: CheckoutRacingViewModelInputs, CheckoutRacingViewModelOutputs { var inputs: CheckoutRacingViewModelInputs { get } var outputs: CheckoutRacingViewModelOutputs { get } } public final class CheckoutRacingViewModel: CheckoutRacingViewModelType { public init() { let envelope = self.initialURLProperty.signal.skipNil() .map { $0.absoluteString } .promoteError(CheckoutRetryError.self) .switchMap { url in SignalProducer<(), CheckoutRetryError>(value: ()) .ksr_delay(.seconds(1), on: AppEnvironment.current.scheduler) .flatMap { AppEnvironment.current.apiService.fetchCheckout(checkoutUrl: url) .flatMapError { _ in SignalProducer(error: CheckoutRetryError()) } .flatMap { envelope -> SignalProducer<CheckoutEnvelope, CheckoutRetryError> in switch envelope.state { case .authorizing, .verifying: return SignalProducer(error: CheckoutRetryError()) case .failed, .successful: return SignalProducer(value: envelope) } } } .retry(upTo: 9) .timeout(after: 10, raising: CheckoutRetryError(), on: AppEnvironment.current.scheduler) } .materialize() self.goToThanks = envelope .values() .filter { $0.state == .successful } .ignoreValues() let failedCheckoutError = envelope .values() .filter { $0.state == .failed } .map { $0.stateReason } let timedOutError = envelope.errors() .mapConst(Strings.project_checkout_finalizing_timeout_message()) self.showAlert = Signal.merge(failedCheckoutError, timedOutError) } fileprivate let initialURLProperty = MutableProperty<URL?>(nil) public func configureWith(url: URL) { self.initialURLProperty.value = url } public let goToThanks: Signal<Void, Never> public let showAlert: Signal<String, Never> public var inputs: CheckoutRacingViewModelInputs { return self } public var outputs: CheckoutRacingViewModelOutputs { return self } }
32.777778
108
0.680603
38d17216669bbf636eca3caaba1daf97a9aef779
12,036
import JWTDataProvider import JWTMiddleware import CryptoSwift import LingoVapor import SendGrid import Crypto import Fluent import Vapor import JWT /// A route controller that handles user authentication with JWT. final class AuthController: RouteCollection { private let jwtService: JWTService init(jwtService: JWTService) { self.jwtService = jwtService } func boot(router: Router) throws { let auth = router.grouped("current") auth.post("newPassword", use: newPassword) auth.post("accessToken", use: refreshAccessToken) let protected = auth.grouped(JWTAuthenticatableMiddleware<User>()) protected.post("login", use: login) protected.get("status", use: status) if emailConfirmation { auth.get("activate", use: activate) } if openRegistration { auth.post(User.self, at: "register", use: register) } else { let restricted = auth.grouped(PermissionsMiddleware<Payload>(allowed: [.admin])) restricted.post(User.self, at: "register", use: register) } } /// Creates a new `User` model in the database. func register(_ request: Request, _ user: User)throws -> Future<UserSuccessResponse> { // Validate the properties of the new user model using custom validations. try user.validate() // Make sure no user exists yet with the email pssed in. let count = User.query(on: request).filter(\.email == user.email).count() return count.map(to: User.self) { count in guard count < 1 else { throw Abort(.badRequest, reason: "This email is already registered.") } return user }.flatMap(to: User.self) { (user) in user.password = try BCrypt.hash(user.password) // Get the langauge used to translate text to with Lingo. if let language = request.http.headers["Language"].first { // Set the user's `language` property if `language` is not `nil`. user.language = language } if emailConfirmation { // Generate a unique code to verify the user with from the current date and time. user.emailCode = Date().description.md5() } return user.save(on: request) }.flatMap(to: User.self) { (user) in if emailConfirmation && !user.confirmed { guard let confirmation = user.emailCode else { throw Abort(.internalServerError, reason: "Confirmation code was not set") } let config = try request.make(AppConfig.self) return try request.send( email: "email.activation.text", withSubject: "email.activation.title", from: config.emailFrom, to: user.email, localized: user, interpolations: ["url": config.emailURL + confirmation] ).transform(to: user) } else { return request.future(user) } } // Convert the user to its reponse representation // and return is with a success status. .response(on: request, forProfile: true) } /// A route handler that checks that status of the user. /// This could be used to verifiy if they are authenticated. func status(_ request: Request)throws -> Future<UserSuccessResponse> { // Return the authenticated user. return try request.user().response(on: request, forProfile: false) } /// A route handler that generates a new password for a user. func newPassword(_ request: Request)throws -> Future<UserSuccessResponse> { // Get the email of the user to create a new password for. let email = try request.content.syncGet(String.self, at: "email") // Verify a user exists with the given email. let user = User.query(on: request).filter(\.email == email).first().unwrap(or: Abort(.badRequest, reason: "No user found with email '\(email)'.")) return user.flatMap(to: (User, String).self) { user in // Verifiy that the user has confimed their account. guard user.confirmed else { throw Abort(.badRequest, reason: "User not activated.") } // Create a new random password from the current date/time let str = Date().description.md5() let index = str.index(str.startIndex, offsetBy: 8) let password = String(str[..<index]) user.password = try BCrypt.hash(password) return user.save(on: request).and(result: password) }.flatMap(to: UserSuccessResponse.self) { saved in // If there is no API key, just return. This is for testing the service. guard Environment.get("SENDGRID_API_KEY") != nil else { return try saved.0.response(on: request, forProfile: false) } let config = try request.make(AppConfig.self) // Send a verification email. return try request.send( email: "email.password.text", withSubject: "email.password.title", from: config.emailFrom, to: email, localized: saved.0, interpolations: ["password": saved.1] ).transform(to: saved.0).response(on: request, forProfile: false) } } /// A route handler that returns a new access and refresh token for the user. func refreshAccessToken(_ request: Request)throws -> Future<[String: String]> { // Get refresh token from request body and verify it. let refreshToken = try request.content.syncGet(String.self, at: "refreshToken") let refreshJWT = try JWT<RefreshToken>(from: refreshToken, verifiedUsing: self.jwtService.signer) try refreshJWT.payload.verify(using: self.jwtService.signer) // Get the user with the ID that was just fetched. let userID = refreshJWT.payload.id let user = User.find(userID, on: request).unwrap(or: Abort(.badRequest, reason: "No user found with ID '\(userID)'.")) return user.flatMap(to: (JSON, Payload).self) { user in guard user.confirmed else { throw Abort(.badRequest, reason: "User not activated.") } // Construct the new access token payload let payload = try App.Payload(user: user) return try request.payloadData(self.jwtService.sign(payload), with: ["userId": "\(user.requireID())"], as: JSON.self).and(result: payload) }.map(to: [String: String].self) { payloadData in let payload = try payloadData.0.merge(payloadData.1.json()) // Return the signed token with a success status. let token = try self.jwtService.sign(payload) return ["status": "success", "accessToken": token] } } /// Confirms a new user account. func activate(_ request: Request)throws -> Future<UserSuccessResponse> { // Get the user from the database with the email code from the request. let code = try request.query.get(String.self, at: "code") let user = User.query(on: request).filter(\.emailCode == code).first().unwrap(or: Abort(.badRequest, reason: "No user found with the given code.")) return user.flatMap(to: User.self) { user in guard !user.confirmed else { throw Abort(.badRequest, reason: "User already activated.") } // Update the confimation properties and save to the database. user.confirmed = true user.emailCode = nil return user.update(on: request) }.response(on: request, forProfile: false) } /// Authenticates a user with an email and password. /// The actual authentication is handled by the `JWTAuthenticatableMiddleware`. /// The request's body should contain an email and a password for authenticating. func login(_ request: Request)throws -> Future<LoginResponse> { let user = try request.requireAuthenticated(User.self) let userPayload = try Payload(user: user) // Create a payload using the standard data // and the data from the registered `DataService`s let remotePayload = try request.payloadData( self.jwtService.sign(userPayload), with: ["userId": "\(user.requireID())"], as: JSON.self ) // Create a response form the access token, refresh token. and user response data. return remotePayload.map(to: LoginResponse.self) { remotePayload in let payload = try remotePayload.merge(userPayload.json()) let accessToken = try self.jwtService.sign(payload) let refreshToken = try self.jwtService.sign(RefreshToken(user: user)) guard user.confirmed else { throw Abort(.badRequest, reason: "User not activated.") } let userResponse = UserResponse(user: user, attributes: nil) return LoginResponse(accessToken: accessToken, refreshToken: refreshToken, user: userResponse) } } } struct UserSuccessResponse: Content { let status: String = "success" let user: UserResponse } struct LoginResponse: Content { let status = "success" let accessToken: String let refreshToken: String let user: UserResponse } extension Request { /// Sends an email with the SendGrid provider. /// The email is translated to the user's `langauge` value. /// /// - Parameters: /// - body: The body of the email. /// - subject: The subject of the email. /// - address: The email address to send the email to. /// - user: The user to localize the email to. /// - interpolations: The interpolation values to replace placeholders in the email body. func send(email body: String, withSubject subject: String, from: String, to address: String, localized user: User, interpolations: [String: String])throws -> Future<Void> { // Fetch the service from the request so we can translate the email. let lingo = try self.lingo() // Create the SendGrid client servi e so we can send the email. let client = try self.make(SendGridClient.self) // Translate the subject and body. let subject: String = lingo.localize(subject, locale: user.language) let body: String = lingo.localize(body, locale: user.language, interpolations: interpolations) // Put all the data for the email togeather let name = [user.firstname, user.lastname].compactMap({ $0 }).joined(separator: " ") let from = EmailAddress(email: from, name: nil) let address = EmailAddress(email: address, name: name) let header = Personalization(to: [address], subject: subject) let email = SendGridEmail(personalizations: [header], from: from, subject: subject, content: [[ "type": "text", "value": body ]]) return try client.send([email], on: self) } } extension Future { /// Converts a future's value to a dictionary /// using the value in the future as the dictionary's value. /// /// - Parameter key: The key for the value in the dictionary. /// /// - Returns: A dictionary instance of type `[String: T]`, /// using the `key` value passed in as the key and the /// value from the future as the value. func keyed(_ key: String) -> Future<[String: T]> { return self.map(to: [String: T].self) { [key: $0] } } }
43.608696
176
0.602775
568b065667bd40081d379888f8fea597ca1aab93
5,790
// // Created by Jeffrey Bergier on 2020/08/19. // // MIT License // // Copyright (c) 2020 Jeffrey Bergier // // 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 CryptoKit import Foundation import ServerlessLogger protocol MockProtocol { typealias OnDisk = (url: URL, data: Data) static var onDisk: [OnDisk] { get } static var remoteURL: URLComponents { get } static var symmetricKey: SymmetricKey { get } static var event: Event { get } static var configuration: ServerlessLoggerConfigurationProtocol { get set } } enum Mock1: MockProtocol { static let onDisk: [OnDisk] = [ (URL(string: "file:///baseDir/UnitTests/Mock1/Inbox/567890.json")!, "This is some data from the disk".data(using: .utf8)!) ] static let remoteURL = URLComponents(string: "https://www.this-is-a-test.com")! static let symmetricKey = SymmetricKey(data: "Hello World".data(using: .utf8)!) static var configuration: ServerlessLoggerConfigurationProtocol = { let s = Logger.StorageLocation(baseDirectory: URL(string: "file:///baseDir")!, appName: "UnitTests", parentDirectory: "Mock1") var c = Logger.DefaultSecureConfiguration(endpointURL: remoteURL, hmacKey: symmetricKey, storageLocation: s) c.logLevel = .error return c }() static var event: Event = { let details = ServerlessLogger.Event.JSBLogDetails(level: .debug, date: Date(), message: "Mock1EventMessage", functionName: "Mock1FunctionName", fileName: "Mock1FileName", lineNumber: 1000) let event = ServerlessLogger.Event(incident: "Mock1Incident", logDetails: details, errorDetails: nil, extraDetails: nil) return event }() } enum Mock2: MockProtocol { static let onDisk: [OnDisk] = [ (URL(string: "file:///baseDir/UnitTests/Mock2/Inbox/12345.json")!, "This is some data from the disk".data(using: .utf8)!) ] static let remoteURL = URLComponents(string: "https://www.this-is-a-test.com")! static let symmetricKey = SymmetricKey(data: "Hello World".data(using: .utf8)!) static var configuration: ServerlessLoggerConfigurationProtocol = { let s = Logger.StorageLocation(baseDirectory: URL(string: "file:///baseDir")!, appName: "UnitTests", parentDirectory: "Mock2") var c = Logger.DefaultInsecureConfiguration(endpointURL: remoteURL, storageLocation: s) c.logLevel = .debug return c }() static var event: Event = { let details = Event.JSBLogDetails(level: .debug, date: Date(), message: "Mock2EventMessage", functionName: "Mock2FunctionName", fileName: "Mock2FileName", lineNumber: 1000) let event = Event(incident: "Mock2Incident", logDetails: details, deviceDetails: .init(), errorDetails: nil, extraDetails: nil) return event }() } enum EndToEndMock1: MockProtocol { static let remoteURL = URLComponents(string: { () -> String in fatalError("Put your endpoint here") }())! static let symmetricKey = SymmetricKey(data: Data(base64Encoded: { () -> String in fatalError("Put your secret here") }())!) static var configuration: ServerlessLoggerConfigurationProtocol = { let s = Logger.StorageLocation( baseDirectory: URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true), appName: "JSBServerlessLoggerTests", parentDirectory: UUID().uuidString ) var c = Logger.DefaultSecureConfiguration(endpointURL: remoteURL, hmacKey: symmetricKey, storageLocation: s) c.logLevel = .error return c }() static let onDisk: [OnDisk] = { fatalError() }() static var event: Event = { fatalError() }() }
46.693548
130
0.570121
bb0b9498ceaba0cdae8b189c3684b3f4324b3903
2,218
// // ViewController.swift // Color matching game // // Created by Yerbolat Beisenbek on 11.09.17. // Copyright © 2017 Yerbolat Beisenbek. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var noButton: UIButton! @IBOutlet weak var yesButton: UIButton! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var timerLabel: UILabel! let colorArray = [UIColor.blue, UIColor.gray, UIColor.yellow, UIColor.red, UIColor.green] let textColor = ["blue","gray", "yellow", "red", "green"] var textIndex: Int! var colorIndex: Int! var timer: Timer! var score: Int = 0 var answer: Bool = false var timeLeft = 5 @objc func updateCounting(){ timeLeft -= 1 timerLabel.text = String(timeLeft) if timeLeft == 0 { showQuestion() } } func updateTimer() { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounting), userInfo: nil, repeats: true) } override func viewDidLoad() { super.viewDidLoad() showQuestion() self.updateTimer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func returnRandomNumber() -> Int{ let random = Int(arc4random_uniform(UInt32(colorArray.count))) return random } func showQuestion(){ timeLeft = 5 textIndex = returnRandomNumber() colorIndex = returnRandomNumber() if textIndex == colorIndex { answer = true } else { answer = false } textLabel.text = textColor[textIndex] textLabel.backgroundColor = colorArray[colorIndex] } @IBAction func yesButtonClicked(_ sender: UIButton) { if answer { score = score + 100 scoreLabel.text = String(score) } showQuestion() } @IBAction func noButtonClicked(_ sender: UIButton) { if !answer { score = score + 100 scoreLabel.text = String(score) } showQuestion() } }
24.644444
134
0.597836
89c1f9d705d87e98881ad4f5c828365d560942f1
3,775
// // Constants.swift // Anyway // // Created by Aviel Gross on 8/10/15. // Copyright (c) 2015 Hasadna. All rights reserved. // import Foundation /// When launching and the user location is unknown - show this fallback coordinate let fallbackStartLocationCoordinate = CLLocationCoordinate2D(latitude: 32.158091269627874, longitude: 34.88087036877948) /// When launching and zooming to inital location - show this radius let appLaunchZoomRadius = 0.005 struct Config { static let TIMEOUT_INTERVAL_FOR_REQUEST: Double = 15 static let ZOOM: Float = 16 static let BIG_DRAWER_HEIGHT:CGFloat = 150.0 static let SMALL_DRAWER_HEIGHT:CGFloat = 120.0 static let BIG_DRAWER_BUTTON_HEIGHT_OFFSET:CGFloat = 30.0 } struct AnywayColor { static var red = UIColor(red:0.856, green:0.123, blue:0.168, alpha:1) static var orange = UIColor(red:1, green:0.626, blue:0, alpha:1) static var yellow = UIColor(red:1, green:0.853, blue:0, alpha:1) static var blue = UIColor(red:0, green:0.526, blue:0.808, alpha:1) } enum Severity: Int { case fatal = 1, severe, light, various } enum AccidentType: Int { case carToCar = -1 case carToObject = -2 case carToPedestrian = 1 } enum AccidentMinorType: Int { case car_TO_CAR = -1 // Synthetic type case car_TO_OBJECT = -2 // Synthetic type case car_TO_PEDESTRIAN = 1 case front_TO_SIDE = 2 case front_TO_REAR = 3 case side_TO_SIDE = 4 case front_TO_FRONT = 5 case with_STOPPED_CAR_NO_PARKING = 6 case with_STOPPED_CAR_PARKING = 7 case with_STILL_OBJECT = 8 case off_ROAD_OR_SIDEWALK = 9 case rollover = 10 case skid = 11 case hit_PASSSENGER_IN_CAR = 12 case falling_OFF_MOVING_VEHICLE = 13 case fire = 14 case other = 15 case back_TO_FRONT = 17 case back_TO_SIDE = 18 case with_ANIMAL = 19 case with_VEHICLE_LOAD = 20 } func accidentMinorTypeToType(_ type: AccidentMinorType) -> AccidentType? { switch type { case .car_TO_PEDESTRIAN: return .carToPedestrian case .front_TO_SIDE: return .carToCar case .front_TO_REAR: return .carToCar case .side_TO_SIDE: return .carToCar case .front_TO_FRONT: return .carToCar case .with_STOPPED_CAR_NO_PARKING: return .carToCar case .with_STOPPED_CAR_PARKING: return .carToCar case .with_STILL_OBJECT: return .carToObject case .off_ROAD_OR_SIDEWALK: return .carToObject case .rollover: return .carToObject case .skid: return .carToObject case .hit_PASSSENGER_IN_CAR: return .carToCar case .falling_OFF_MOVING_VEHICLE: return .carToObject case .fire: return .carToObject case .other: return .carToObject case .back_TO_FRONT: return .carToCar case .back_TO_SIDE: return .carToCar case .with_ANIMAL: return .carToPedestrian case .with_VEHICLE_LOAD: return .carToCar default: return nil } } /** Accident Providing Organization - CBS: הלמ״ס raw can be 1 or 3 - Ihud: איחוד והצלה raw can be 2 */ enum Provider { case cbs case ihud init?(_ raw: Int) { switch raw { case 1,3: self = .cbs case 2: self = .ihud default: return nil } } var name: String { switch self { case .cbs: return local("PROVIDER_cbs") case .ihud: return local("PROVIDER_ihud") } } var logo: String { switch self { case .cbs: return "cbs" case .ihud: return "ihud" } } var url: String { switch self { case .cbs: return "http://www.cbs.gov.il" case .ihud: return "http://www.1221.org.il" } } }
26.584507
120
0.651656
ac0558b0c387128dc46c2c109c7a6822fdf0f90d
1,089
// // AboutAppPresenter.swift // fuelhunter // // Created by Guntis on 07/07/2019. // Copyright (c) 2019 . 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 AboutAppPresentationLogic { func presentData(response: AboutApp.CompanyCells.Response) } class AboutAppPresenter: AboutAppPresentationLogic { weak var viewController: AboutAppDisplayLogic? // MARK: AboutAppPresentationLogic func presentData(response: AboutApp.CompanyCells.Response) { var array = [AboutApp.CompanyCells.ViewModel.DisplayedCompanyCellItem]() for company in response.fetchedCompanies { let title = company.name ?? "" let imageName = company.logoName ?? "" array.append(AboutApp.CompanyCells.ViewModel.DisplayedCompanyCellItem(title: title, imageName: imageName)) } let viewModel = AboutApp.CompanyCells.ViewModel(displayedCompanyCellItems: array) viewController?.displayData(viewModel: viewModel) } }
28.657895
109
0.754821
181dbe4489912cf53d4b48f5ba4cd9b71bc1b83f
1,672
// // ContractHistory.swift // ECHO // // Created by Vladimir Sharaev on 18/05/2019. // Copyright © 2019 PixelPlex. All rights reserved. // import Foundation /** Represents Contract History object from blockchain */ public struct ContractHistory: ECHOObject, Decodable { private enum ContractHistoryCodingKeys: String, CodingKey { case id case contract case operationId = "operation_id" case sequence case nextId case parentOpId = "parent_op_id" } public var id: String public let contract: Contract public let operationId: String public let sequence: Int public let nextId: String? public let parentOpId: String? public init(id: String, contract: Contract, operationId: String, sequence: Int = 0, nextId: String?, parentOpId: String? = nil) { self.id = id self.contract = contract self.operationId = operationId self.sequence = sequence self.nextId = nextId self.parentOpId = parentOpId } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: ContractHistoryCodingKeys.self) id = try values.decode(String.self, forKey: .id) let contractId = try values.decode(String.self, forKey: .contract) contract = Contract(id: contractId) operationId = try values.decode(String.self, forKey: .operationId) sequence = try values.decode(Int.self, forKey: .sequence) nextId = try? values.decode(String.self, forKey: .nextId) parentOpId = try? values.decode(String.self, forKey: .parentOpId) } }
30.962963
133
0.654306
1d86c59a307c5a4d748269eff2a18a66bedb783a
255
// RUN: %target-parse-verify-swift -parse-stdlib // This file is for tests that used to cause the type checker to crash. class DictStringInt { init(dictionaryLiteral xs: ()...) {} // expected-error{{broken standard library: cannot find Array type}} }
31.875
107
0.721569
f92c64f95b4111046d350c8325b7d389b874c515
329
// // GlucoseTxMessage.swift // xDrip5 // // Created by Nathan Racklyeft on 11/23/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation struct GlucoseTxMessage: TransmitterTxMessage { let opcode: UInt8 = 0x30 var byteSequence: [Any] { return [opcode, opcode.crc16()] } }
17.315789
59
0.671733
dbb899442eeea5de72f5661a7d42df3d824a7f23
1,727
// Tests/SwiftProtobufTests/Test_Merge.swift - Verify merging messages // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf class Test_Merge: XCTestCase, PBTestHelpers { typealias MessageTestType = Proto3Unittest_TestAllTypes func testMergeSimple() throws { var m1 = Proto3Unittest_TestAllTypes() m1.optionalInt32 = 100 var m2 = Proto3Unittest_TestAllTypes() m2.optionalInt64 = 1000 do { try m1.merge(serializedData: m2.serializedData()) XCTAssertEqual(m1.optionalInt32, 100) XCTAssertEqual(m1.optionalInt64, 1000) } catch let e { XCTFail("Merge should not have thrown, but it did: \(e)") } } func testMergePreservesValueSemantics() throws { var original = Proto3Unittest_TestAllTypes() original.optionalInt32 = 100 let copied = original var toMerge = Proto3Unittest_TestAllTypes() toMerge.optionalInt64 = 1000 do { try original.merge(serializedData: toMerge.serializedData()) // The original should have the value from the merged message... XCTAssertEqual(original.optionalInt32, 100) XCTAssertEqual(original.optionalInt64, 1000) // ...but the older copy should not be affected. XCTAssertEqual(copied.optionalInt32, 100) XCTAssertEqual(copied.optionalInt64, 0) } catch let e { XCTFail("Merge should not have thrown, but it did: \(e)") } } }
30.839286
80
0.682687
29e637f93de2750605e10e9930e598cf75f88d6b
2,164
// The MIT License (MIT) // // Copyright (c) 2017 Saoud Rizwan <[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 Foundation extension Disk { public enum ErrorCode: Int { case noFileFound = 0 case serialization = 1 case deserialization = 2 case invalidFileName = 3 case couldNotAccessTemporaryDirectory = 4 case couldNotAccessUserDomainMask = 5 case couldNotAccessSharedContainer = 6 } public static let errorDomain = "DiskErrorDomain" /// Create custom error that FileManager can't account for static func createError(_ errorCode: ErrorCode, description: String?, failureReason: String?, recoverySuggestion: String?) -> Error { let errorInfo: [String: Any] = [NSLocalizedDescriptionKey : description ?? "", NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion ?? "", NSLocalizedFailureReasonErrorKey: failureReason ?? ""] return NSError(domain: errorDomain, code: errorCode.rawValue, userInfo: errorInfo) as Error } }
46.042553
137
0.709335
3370a179b4f6bcc0fdc820d3e8226bc9dae4b134
1,671
// // Alamofire+Promise.swift // PromissumExtensions // // Created by Tom Lokhorst on 2014-10-12. // Copyright (c) 2014 Tom Lokhorst. All rights reserved. // import Foundation import Alamofire public enum AlamofirePromiseError : ErrorType { case JsonDecodeError case HttpNotFound(result: Alamofire.Result<AnyObject>) case HttpError(status: Int, result: Alamofire.Result<AnyObject>?) case UnknownError(error: ErrorType, data: NSData?) } extension Request { public func responseDecodePromise<T>(decoder: AnyObject -> T?) -> Promise<T, AlamofirePromiseError> { return self.responseJSONPromise() .flatMap { json in if let value = decoder(json) { return Promise(value: value) } else { return Promise(error: AlamofirePromiseError.JsonDecodeError) } } } public func responseJSONPromise() -> Promise<AnyObject, AlamofirePromiseError> { let source = PromiseSource<AnyObject, AlamofirePromiseError>() self.responseJSON { (request, response, result) -> Void in if let resp = response { if resp.statusCode == 404 { source.reject(AlamofirePromiseError.HttpNotFound(result: result)) return } if resp.statusCode < 200 || resp.statusCode > 299 { source.reject(AlamofirePromiseError.HttpError(status: resp.statusCode, result: result)) return } } switch result { case let .Success(value): source.resolve(value) case let .Failure(data, error): source.reject(AlamofirePromiseError.UnknownError(error: error, data: data)) } } return source.promise } }
26.52381
103
0.663076
6242b6bc1fcc1d9e56b1b13f3cab43a64cd320e1
697
import UIKit final public class NavigationController: UINavigationController, CoordinatorContainer { // MARK: - Properties weak public var flowDelegate: Delegate? { didSet { DelegateHolder.instance.delegate = flowDelegate } } weak public var uiDelegate: UIDelegate? { didSet { DelegateHolder.instance.uiDelegate = uiDelegate } } var coordinator: NavigationCoordinator? { return navigationCoordinator } var navigationCoordinator: NavigationCoordinator? { didSet { delegate = navigationCoordinator } } }
23.233333
64
0.583931
0884e6b997a89da12af67d487f7ec3a5d29cb47d
2,034
import Basic import Foundation import ProjectDescription import TuistCore import TuistSupport extension TuistCore.Workspace { /// Maps a ProjectDescription.Workspace instance into a TuistCore.Workspace model. /// - Parameters: /// - manifest: Manifest representation of workspace. /// - generatorPaths: Generator paths. static func from(manifest: ProjectDescription.Workspace, path: AbsolutePath, generatorPaths: GeneratorPaths, manifestLoader: ManifestLoading) throws -> TuistCore.Workspace { func globProjects(_ path: Path) throws -> [AbsolutePath] { let resolvedPath = try generatorPaths.resolve(path: path) let projects = FileHandler.shared.glob(AbsolutePath.root, glob: String(resolvedPath.pathString.dropFirst())) .lazy .filter(FileHandler.shared.isFolder) .filter { manifestLoader.manifests(at: $0).contains(.project) } if projects.isEmpty { // FIXME: This should be done in a linter. // Before we can do that we have to change the linters to run with the TuistCore models and not the ProjectDescription ones. Printer.shared.print(warning: "No projects found at: \(path.pathString)") } return Array(projects) } let additionalFiles = try manifest.additionalFiles.flatMap { try TuistCore.FileElement.from(manifest: $0, generatorPaths: generatorPaths) } let schemes = try manifest.schemes.map { try TuistCore.Scheme.from(manifest: $0, generatorPaths: generatorPaths) } return TuistCore.Workspace(path: path, name: manifest.name, projects: try manifest.projects.flatMap(globProjects), schemes: schemes, additionalFiles: additionalFiles) } }
43.276596
140
0.604228
1cd31556b2bc31fe08055c584f548afb4aa8ed27
512
// // UserService.swift // Pozativity // // Created by Alexandru Turcanu on 22/09/2018. // Copyright © 2018 Alexandru Turcanu. All rights reserved. // import Foundation import FirebaseDatabase struct UserService { static func retrieveUser(for uid: String, completion: @escaping (User?) -> ()) { let ref = Database.database().reference().child("users").child(uid) ref.observeSingleEvent(of: .value) { (snapshot) in completion(User(from: snapshot)) } } }
24.380952
84
0.646484
e48cbb328562b7acfcfb3e80457a2f30c17070a9
579
import Foundation let request = NSMutableURLRequest(url: NSURL(string: "https://httpbin.org/anything")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "GET" let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume()
30.473684
116
0.635579
114102e813394c87529d7d53b4e4efc3dafcf02c
6,387
// // EthereumPrivateKeyTests.swift // Web3_Tests // // Created by Koray Koska on 06.02.18. // Copyright © 2018 Boilertalk. All rights reserved. // import Quick import Nimble @testable import Web3 import BigInt class EthereumPrivateKeyTests: QuickSpec { enum OwnErrors: Error { case shouldNotThrow } override func spec() { describe("ethereum private key checks") { context("private key verification") { it("should be a valid private key") { let hex = "0xddeff73b1db1d8ddfd5e4c8e6e9a538938e53f98aaa027403ae69885fc97ddad" let bytes: [UInt8] = [ 0xdd, 0xef, 0xf7, 0x3b, 0x1d, 0xb1, 0xd8, 0xdd, 0xfd, 0x5e, 0x4c, 0x8e, 0x6e, 0x9a, 0x53, 0x89, 0x38, 0xe5, 0x3f, 0x98, 0xaa, 0xa0, 0x27, 0x40, 0x3a, 0xe6, 0x98, 0x85, 0xfc, 0x97, 0xdd, 0xad ] let priv = try? EthereumPrivateKey( hexPrivateKey: hex ) expect(priv).toNot(beNil()) expect(priv?.rawPrivateKey) == bytes let priv2 = try? EthereumPrivateKey( privateKey: bytes ) expect(priv2).toNot(beNil()) expect(priv2?.rawPrivateKey) == bytes // Both should be the same private key expect(priv?.rawPrivateKey) == priv2?.rawPrivateKey } it("should be edge case valid private keys") { let upperEdge = try? EthereumPrivateKey( hexPrivateKey: "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" ) let lowerEdge = try? EthereumPrivateKey( hexPrivateKey: "0x0000000000000000000000000000000000000000000000000000000000000001" ) expect(upperEdge).toNot(beNil()) expect(lowerEdge).toNot(beNil()) } } context("public key verification") { it("should be a valid public key") { let publicKey = try? EthereumPrivateKey( hexPrivateKey: "0x026cf37c61297a451e340cdc7fbc71b6789a3b1cb27dcdc9a9a2a32c16ce2afc" ).publicKey expect(publicKey?.rawPublicKey) == [ 0xf8, 0x52, 0x1a, 0x0e, 0x42, 0x7d, 0xd3, 0xec, 0xd7, 0x1a, 0xf4, 0xf2, 0x17, 0xdf, 0x8f, 0xef, 0xf2, 0x6b, 0x85, 0x72, 0x95, 0x38, 0xb7, 0x59, 0x0c, 0x20, 0x98, 0x60, 0x55, 0x46, 0x7f, 0xb6, 0x0c, 0xce, 0xd0, 0x8f, 0x6b, 0x2c, 0x56, 0x76, 0x75, 0x08, 0xf3, 0xe7, 0x97, 0x6d, 0x5b, 0xcc, 0xd5, 0x2c, 0x91, 0xbf, 0x59, 0x77, 0xbb, 0x5d, 0x95, 0x43, 0x82, 0x67, 0x52, 0x26, 0x79, 0x18 ] } // We don't destroy the context as for these tests this is not really a security problem and quite // cumbersome (How do we know the tests are really finished?) // It should nevertheless always be done for real applications. let oCtx = try? secp256k1_default_ctx_create(errorThrowable: OwnErrors.shouldNotThrow) it("should be a valid ctx pointer") { expect(oCtx).toNot(beNil()) } guard let ctx = oCtx else { return } it("should work with own ctx") { let publicKey = try? EthereumPrivateKey( hexPrivateKey: "0x026cf37c61297a451e340cdc7fbc71b6789a3b1cb27dcdc9a9a2a32c16ce2afc", ctx: ctx ).publicKey expect(publicKey?.rawPublicKey) == [ 0xf8, 0x52, 0x1a, 0x0e, 0x42, 0x7d, 0xd3, 0xec, 0xd7, 0x1a, 0xf4, 0xf2, 0x17, 0xdf, 0x8f, 0xef, 0xf2, 0x6b, 0x85, 0x72, 0x95, 0x38, 0xb7, 0x59, 0x0c, 0x20, 0x98, 0x60, 0x55, 0x46, 0x7f, 0xb6, 0x0c, 0xce, 0xd0, 0x8f, 0x6b, 0x2c, 0x56, 0x76, 0x75, 0x08, 0xf3, 0xe7, 0x97, 0x6d, 0x5b, 0xcc, 0xd5, 0x2c, 0x91, 0xbf, 0x59, 0x77, 0xbb, 0x5d, 0x95, 0x43, 0x82, 0x67, 0x52, 0x26, 0x79, 0x18 ] } it("should work with own ctx twice") { let publicKey = try? EthereumPrivateKey( hexPrivateKey: "0x026cf37c61297a451e340cdc7fbc71b6789a3b1cb27dcdc9a9a2a32c16ce2afc", ctx: ctx ).publicKey expect(publicKey?.rawPublicKey) == [ 0xf8, 0x52, 0x1a, 0x0e, 0x42, 0x7d, 0xd3, 0xec, 0xd7, 0x1a, 0xf4, 0xf2, 0x17, 0xdf, 0x8f, 0xef, 0xf2, 0x6b, 0x85, 0x72, 0x95, 0x38, 0xb7, 0x59, 0x0c, 0x20, 0x98, 0x60, 0x55, 0x46, 0x7f, 0xb6, 0x0c, 0xce, 0xd0, 0x8f, 0x6b, 0x2c, 0x56, 0x76, 0x75, 0x08, 0xf3, 0xe7, 0x97, 0x6d, 0x5b, 0xcc, 0xd5, 0x2c, 0x91, 0xbf, 0x59, 0x77, 0xbb, 0x5d, 0x95, 0x43, 0x82, 0x67, 0x52, 0x26, 0x79, 0x18 ] } } context("hashable") { it("should produce correct hashValues") { let p1 = try? EthereumPrivateKey( hexPrivateKey: "0xddeff73b1db1d8ddfd5e4c8e6e9a538938e53f98aaa027403ae69885fc97ddad" ) let p2 = try? EthereumPrivateKey( hexPrivateKey: "0xddeff73b1db1d8ddfd5e4c8e6e9a538938e53f98aaa027403ae69885fc97ddad" ) expect(p1?.hashValue) == p2?.hashValue } it("should produce different hashValues") { let p1 = try? EthereumPrivateKey( hexPrivateKey: "0xddeff73b1db1d8ddfd5e4c8e6e9a538938e53f98aaa027403ae69885fc97ddad" ) let p2 = try? EthereumPrivateKey( hexPrivateKey: "0xad028828bbe74b01302dfcd0b8f06cdc8fc50668649ce5859926bd69a947667f" ) expect(p1?.hashValue) != p2?.hashValue } } } } }
46.282609
119
0.518866
502939c4c8428fca6836fa2ff6a57d8c1bf5e503
398
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "TBX", products: [ .library(name: "TBX", targets: ["TBX"]) ], dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", .exact("4.9.0")), ], targets: [ .target(name: "TBX", dependencies: [ "Alamofire", ], path: "Sources") ] )
20.947368
85
0.542714
6ad2e8dfb4774a6bb59d4f92409a01cbefed67a7
7,945
// // CellSlideActionManager.swift // TaskScheduler // // Created by Ben Oztalay on 1/4/16. // Copyright © 2016 Ben Oztalay. All rights reserved. // import UIKit // A delegate for controllers to conform to to get notified // when the user triggers an action by sliding a cell over protocol CellSlideActionManagerDelegate { // Called when a cell's mark complete action is triggered func cellSlideMarkCompleteActionTriggered(tableView: UITableView, indexPath: NSIndexPath) // Called when a cell's mark incomplete action is triggered func cellSlideMarkIncompleteActionTriggered(tableView: UITableView, indexPath: NSIndexPath) // Called when a cell's delete action is triggered func cellSlideDeleteActionTriggered(tableView: UITableView, indexPath: NSIndexPath) } // Holds some attributes for the cell slide actions, // just here for easier configuration struct CellSlideActionAttributes { static let generalFraction: CGFloat = 0.20 static let generalElasticity: CGFloat = 50.0 static let generalIconColor = UIColor.whiteColor() static let markCompleteActiveBackgroundColor = TaskSchedulerColors.TaskComplete static let markCompleteInactiveBackgroundColor = TaskSchedulerColors.TaskInProgess static let markCompleteIcon = UIImage(named: "check") static let markIncompleteActiveBackgroundColor = TaskSchedulerColors.TaskInProgess static let markIncompleteInactiveBackgroundColor = TaskSchedulerColors.TaskComplete static let markIncompleteIcon = UIImage(named: "uncheck") static let deleteActionActiveBackgroundColor = TaskSchedulerColors.TaskDropped static let deleteActionInactiveBackgroundColor = TaskSchedulerColors.TaskInProgess static let deleteIcon = UIImage(named: "delete") } class CellSlideActionManager: NSObject { private var markCompleteAction: DRCellSlideAction private var markIncompleteAction: DRCellSlideAction private var deleteAction: DRCellSlideAction private var knownGestureRecognizers: [DRCellSlideGestureRecognizer] = [] var delegate: CellSlideActionManagerDelegate? override init() { // Need to initialize them first, then call super.init self.markCompleteAction = DRCellSlideAction(forFraction: CellSlideActionAttributes.generalFraction) self.markIncompleteAction = DRCellSlideAction(forFraction: CellSlideActionAttributes.generalFraction) self.deleteAction = DRCellSlideAction(forFraction: -CellSlideActionAttributes.generalFraction) super.init() // Set up the mark complete action self.markCompleteAction.behavior = DRCellSlideActionBehavior.PullBehavior self.markCompleteAction.elasticity = CellSlideActionAttributes.generalElasticity self.markCompleteAction.activeBackgroundColor = CellSlideActionAttributes.markCompleteActiveBackgroundColor self.markCompleteAction.inactiveBackgroundColor = CellSlideActionAttributes.markCompleteInactiveBackgroundColor self.markCompleteAction.icon = CellSlideActionAttributes.markCompleteIcon self.markCompleteAction.activeColor = CellSlideActionAttributes.generalIconColor self.markCompleteAction.inactiveColor = CellSlideActionAttributes.generalIconColor self.markCompleteAction.didTriggerBlock = self.markCompleteActionTriggered // Set up the mark incomplete action self.markIncompleteAction.behavior = DRCellSlideActionBehavior.PullBehavior self.markIncompleteAction.elasticity = CellSlideActionAttributes.generalElasticity self.markIncompleteAction.activeBackgroundColor = CellSlideActionAttributes.markIncompleteActiveBackgroundColor self.markIncompleteAction.inactiveBackgroundColor = CellSlideActionAttributes.markIncompleteInactiveBackgroundColor self.markIncompleteAction.icon = CellSlideActionAttributes.markIncompleteIcon self.markIncompleteAction.activeColor = CellSlideActionAttributes.generalIconColor self.markIncompleteAction.inactiveColor = CellSlideActionAttributes.generalIconColor self.markIncompleteAction.didTriggerBlock = self.markIncompleteActionTriggered // Set up the delete action self.deleteAction.behavior = DRCellSlideActionBehavior.PushBehavior self.deleteAction.elasticity = CellSlideActionAttributes.generalElasticity self.deleteAction.activeBackgroundColor = CellSlideActionAttributes.deleteActionActiveBackgroundColor self.deleteAction.inactiveBackgroundColor = CellSlideActionAttributes.deleteActionInactiveBackgroundColor self.deleteAction.icon = CellSlideActionAttributes.deleteIcon self.deleteAction.activeColor = CellSlideActionAttributes.generalIconColor self.deleteAction.inactiveColor = CellSlideActionAttributes.generalIconColor self.deleteAction.didTriggerBlock = self.deleteActionTriggered } // Called whenever the mark complete action is triggered private func markCompleteActionTriggered(tableView: UITableView?, indexPath: NSIndexPath?) { self.delegate?.cellSlideMarkCompleteActionTriggered(tableView!, indexPath: indexPath!) } // Called whenever the mark incomplete action is triggered private func markIncompleteActionTriggered(tableView: UITableView?, indexPath: NSIndexPath?) { self.delegate?.cellSlideMarkIncompleteActionTriggered(tableView!, indexPath: indexPath!) } // Called whenever the delete action is triggered private func deleteActionTriggered(tableView: UITableView?, indexPath: NSIndexPath?) { self.delegate?.cellSlideDeleteActionTriggered(tableView!, indexPath: indexPath!) } // Configures the given cell to have mark complete and // delete cell slide actions func addMarkCompleteAndDeleteSlideActionsToCell(cell: UITableViewCell) { self.removeKnownGestureRecognizersFromCell(cell) let gestureRecognizer = DRCellSlideGestureRecognizer() gestureRecognizer.addActions([self.markCompleteAction, self.deleteAction]) cell.addGestureRecognizer(gestureRecognizer) } // Configures the given cell to have mark incomplete and // delete cell slide actions func addMarkIncompleteAndDeleteSlideActionsToCell(cell: UITableViewCell) { self.removeKnownGestureRecognizersFromCell(cell) let gestureRecognizer = DRCellSlideGestureRecognizer() gestureRecognizer.addActions([self.markIncompleteAction, self.deleteAction]) cell.addGestureRecognizer(gestureRecognizer) } // Configures the given cell to have only the // mark complete cell slide action func addMarkCompleteSlideActionToCell(cell: UITableViewCell) { self.removeKnownGestureRecognizersFromCell(cell) let gestureRecognizer = DRCellSlideGestureRecognizer() gestureRecognizer.addActions([self.markCompleteAction]) cell.addGestureRecognizer(gestureRecognizer) } // Configures the given cell to have only the // mark incomplete cell slide action func addMarkIncompleteSlideActionToCell(cell: UITableViewCell) { self.removeKnownGestureRecognizersFromCell(cell) let gestureRecognizer = DRCellSlideGestureRecognizer() gestureRecognizer.addActions([self.markIncompleteAction]) cell.addGestureRecognizer(gestureRecognizer) } // Removes all DRCellSlideGestureRecognizers from the given cell private func removeKnownGestureRecognizersFromCell(cell: UITableViewCell) { if let cellGestureRecognizers = cell.gestureRecognizers { for gestureRecognizer in cellGestureRecognizers { if let gestureRecognizer = gestureRecognizer as? DRCellSlideGestureRecognizer { cell.removeGestureRecognizer(gestureRecognizer) } } } } }
49.347826
123
0.769792
f7cfa763b6ebfe15323f78e339343f31a38b4265
1,564
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // -------------------------------------------------------------------------- import AzureCore import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable identifier_name // swiftlint:disable line_length // swiftlint:disable cyclomatic_complexity public struct Animal: Codable { // MARK: Properties public let aniType: String? // MARK: Initializers /// Initialize a `Animal` structure. /// - Parameters: /// - aniType: public init( aniType: String? = nil ) { self.aniType = aniType } // MARK: Codable enum CodingKeys: String, CodingKey { case aniType = "aniType" } /// Initialize a `Animal` structure from decoder public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.aniType = try? container.decode(String.self, forKey: .aniType) } /// Encode a `Animal` structure public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if aniType != nil { try? container.encode(aniType, forKey: .aniType) } } }
30.076923
78
0.61445
502172e084af4f0fd3f5e40756b76ca74123773e
14,263
// ArrayLoader // Written in 2015 by Nate Stedman <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import ReactiveCocoa import Result /// An array loader that uses strategy functions to retrieve and combine element arrays, and provides an `Info` /// parameter where arbitrary non-element data can be stored for the previous and next page. This data will be passed /// to load strategies as part of an `InfoLoadRequest` value. public final class InfoStrategyArrayLoader<Element, Info, Error: ErrorType> { // MARK: - Strategy Types /// The function type used to load additional array pages. /// /// Currently, only a single `next` value is supported. Subsequent values will be discarded. public typealias LoadStrategy = InfoLoadRequest<Element, Info> -> SignalProducer<InfoLoadResult<Element, Info>, Error> // MARK: - Initialization /** Initializes a strategy array loader. - parameter nextInfo: The initial next page info value. - parameter previousInfo: The initial previous page info value. - parameter load: The load strategy to use. */ public init(nextInfo: Info, previousInfo: Info, load: LoadStrategy) { loadStrategy = load infoState = MutableProperty(InfoLoaderState( loaderState: LoaderState( elements: [], nextPageState: .HasMore, previousPageState: .HasMore ), nextInfo: nextInfo, previousInfo: previousInfo )) state = infoState.map({ $0.loaderState }) } deinit { nextPageDisposable.dispose() previousPageDisposable.dispose() } // MARK: - State /// A backing property for `state`, which also holds the array loader's info values. let infoState: MutableProperty<InfoLoaderState<Element, Info, Error>> /// The current state of the array loader. public let state: AnyProperty<LoaderState<Element, Error>> // MARK: - Strategies /// The load strategy. let loadStrategy: LoadStrategy // MARK: - Pipes /// A backing pipe for `events`. private let eventsPipe = Signal<LoaderEvent<Element, Error>, NoError>.pipe() // MARK: - Page Disposables /// A disposable for the operation loading the next page. private let nextPageDisposable = SerialDisposable() /// A disposable for the operation loading the previous page. private let previousPageDisposable = SerialDisposable() } // MARK: - ArrayLoader extension InfoStrategyArrayLoader: ArrayLoader { // MARK: - Page Events /// The array loader's events. public var events: SignalProducer<LoaderEvent<Element, Error>, NoError> { return state.producer.take(1).map(LoaderEvent.Current).concat(SignalProducer(signal: eventsPipe.0)) } // MARK: - Loading Pages /// Loads the next page of the array loader, if one is available. If the next page is already loading, or no next /// page is available, this function does nothing. /// /// Although load strategies can execute synchronously, the next page state of the array loader will always /// change to `.Loading` when this function is called, as long as the next page state is not `.Completed`. public func loadNextPage() { guard state.value.nextPageState.isHasMore || state.value.nextPageState.error != nil else { return } // set the next page state to loading let current = infoState.modify({ current in InfoLoaderState( loaderState: LoaderState( elements: current.loaderState.elements, nextPageState: .Loading, previousPageState: current.loaderState.previousPageState ), nextInfo: current.nextInfo, previousInfo: current.previousInfo ) }) eventsPipe.1.sendNext(.NextPageLoading(state: infoState.value.loaderState, previousState: current.loaderState)) nextPageDisposable.innerDisposable = loadStrategy(.Next(current: current.loaderState.elements, info: current.nextInfo)) .take(1) .startWithResult({ [weak self] result in self?.nextPageCompletion(result: result) }) } /// Loads the previous page of the array loader, if one is available. If the previous page is already loading, or no /// previous page is available, this function does nothing. /// /// Although load strategies can execute synchronously, the next page state of the array loader will always /// change to `.Loading` when this function is called, as long as the next page state is not `.Completed`. public func loadPreviousPage() { guard state.value.previousPageState.isHasMore || state.value.previousPageState.error != nil else { return } // set the previous page state to loading let current = infoState.modify({ current in InfoLoaderState( loaderState: LoaderState( elements: current.loaderState.elements, nextPageState: current.loaderState.previousPageState, previousPageState: .Loading ), nextInfo: current.nextInfo, previousInfo: current.previousInfo ) }) eventsPipe.1.sendNext(.PreviousPageLoading( state: infoState.value.loaderState, previousState: current.loaderState )) previousPageDisposable.innerDisposable = loadStrategy(.Previous(current: current.loaderState.elements, info: current.previousInfo)) .take(1) .startWithResult({ [weak self] result in self?.previousPageCompletion(result: result) }) } } extension InfoStrategyArrayLoader { // MARK: - Function Types private typealias PageStateForSuccess = (current: PageState<Error>, mutation: Mutation<Bool>) -> PageState<Error> private typealias PageStateForFailure = (current: PageState<Error>, error: Error) -> PageState<Error> /// A function type to transform an `InfoLoaderState` value. private typealias InfoLoaderStateTransform = InfoLoaderState<Element, Info, Error> -> InfoLoaderState<Element, Info, Error> /// A function type for creating a loader event from a current loader state, a previous loader state, and an array /// of newly-loaded elements. private typealias LoaderEventForStatesAndElements = (LoaderState<Element, Error>, LoaderState<Element, Error>, [Element]) -> LoaderEvent<Element, Error> /// A function type for creating a loader event from a current loader state and a previous loader state. private typealias LoaderEventForStates = (LoaderState<Element, Error>, LoaderState<Element, Error>) -> LoaderEvent<Element, Error> static func currentIfNoMutation(current current: PageState<Error>, mutation: Mutation<Bool>) -> PageState<Error> { return mutation.value.map({ hasMore in hasMore ? .HasMore : .Completed }) ?? current } static func hasMoreIfNoMutation(current current: PageState<Error>, mutation: Mutation<Bool>) -> PageState<Error> { return mutation.value.map({ hasMore in hasMore ? .HasMore : .Completed }) ?? .HasMore } // MARK: - Load Request Completion private typealias PageResult = Result<InfoLoadResult<Element, Info>, Error> /// Completes loading of the next page. /// /// - parameter result: The result from loading the next page. private func nextPageCompletion(result result: PageResult) { pageCompletion( result: result, combine: { current, new in current + new } , loaderEventForLoaded: LoaderEvent<Element, Error>.NextPageLoaded, loaderEventForFailed: LoaderEvent.NextPageFailed, nextPageStateForSuccess: InfoStrategyArrayLoader.hasMoreIfNoMutation, previousPageStateForSuccess: InfoStrategyArrayLoader.currentIfNoMutation, nextPageStateForFailure: { _, error in .Failed(error) }, previousPageStateForFailure: { current, _ in current } ) } /// Completes loading of the previous page. /// /// - parameter result: The result from loading the previous page. private func previousPageCompletion(result result: PageResult) { pageCompletion( result: result, combine: { current, new in new + current }, loaderEventForLoaded: LoaderEvent<Element, Error>.PreviousPageLoaded, loaderEventForFailed: LoaderEvent.PreviousPageFailed, nextPageStateForSuccess: InfoStrategyArrayLoader.currentIfNoMutation, previousPageStateForSuccess: InfoStrategyArrayLoader.hasMoreIfNoMutation, nextPageStateForFailure: { current, _ in current }, previousPageStateForFailure: { _, error in .Failed(error) } ) } /// Modifies the info loader state for a page completion event. /// /// - parameter transform: The info loader state transform. /// - parameter pageEvent: A function to create a page event, given the current and previous loader states. private func modifyStateForPageCompletion(transform transform: InfoLoaderStateTransform, pageEvent: LoaderEventForStates) { var newState: InfoLoaderState<Element, Info, Error>? let previousState = infoState.modify({ current in newState = transform(current) return newState! }) eventsPipe.1.sendNext(pageEvent(newState!.loaderState, previousState.loaderState)) } /// Completes the loading of a page. /// /// - parameter result: The result of loading the page. /// - parameter combine: A function to combine the current and newly loaded elements. /// - parameter loaderEventForLoaded: A function to create a page event for a successfully loaded page. /// - parameter loaderEventForFailed: A function to create a page event for a failed page load. /// - parameter nextPageStateForSuccess: A function to determine the next page state for a successfully loaded /// page. /// - parameter previousPageStateForSuccess: A function to determine the previous page state for a successfully /// loaded page. /// - parameter nextPageStateForFailure: A function to determine the next page state for a failed page load. /// - parameter previousPageStateForFailure: A function to determine the previous page state for a failed page load. private func pageCompletion(result result: PageResult, combine: (current: [Element], new: [Element]) -> [Element], loaderEventForLoaded: LoaderEventForStatesAndElements, loaderEventForFailed: LoaderEventForStates, nextPageStateForSuccess: PageStateForSuccess, previousPageStateForSuccess: PageStateForSuccess, nextPageStateForFailure: PageStateForFailure, previousPageStateForFailure: PageStateForFailure) { switch result { case let .Success(loadResult): modifyStateForPageCompletion( transform: { current in InfoLoaderState( loaderState: LoaderState( elements: combine(current: current.loaderState.elements, new: loadResult.elements), nextPageState: nextPageStateForSuccess( current: current.loaderState.nextPageState, mutation: loadResult.nextPageHasMore ), previousPageState: previousPageStateForSuccess( current: current.loaderState.previousPageState, mutation: loadResult.previousPageHasMore ) ), nextInfo: loadResult.nextPageInfo.value ?? current.nextInfo, previousInfo: loadResult.previousPageInfo.value ?? current.previousInfo ) }, pageEvent: { current, previous in loaderEventForLoaded(current, previous, loadResult.elements) } ) case let .Failure(error): modifyStateForPageCompletion( transform: { current in InfoLoaderState( loaderState: LoaderState( elements: current.loaderState.elements, nextPageState: nextPageStateForFailure( current: current.loaderState.nextPageState, error: error ), previousPageState: previousPageStateForFailure( current: current.loaderState.previousPageState, error: error ) ), nextInfo: current.nextInfo, previousInfo: current.previousInfo ) }, pageEvent: loaderEventForFailed ) } } } struct InfoLoaderState<Element, Info, Error: ErrorType> { let loaderState: LoaderState<Element, Error> let nextInfo: Info let previousInfo: Info }
43.751534
122
0.623992
1677d56a14c1cddc16fb263b32c640094910f54e
3,539
import Foundation import azureSwiftRuntime public protocol RouteTablesCreateOrUpdate { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var routeTableName : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } var parameters : RouteTableProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (RouteTableProtocol?, Error?) -> Void) -> Void ; } extension Commands.RouteTables { // CreateOrUpdate create or updates a route table in a specified resource group. This method may poll for completion. // Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel polling and any // outstanding HTTP requests. internal class CreateOrUpdateCommand : BaseCommand, RouteTablesCreateOrUpdate { public var resourceGroupName : String public var routeTableName : String public var subscriptionId : String public var apiVersion = "2018-01-01" public var parameters : RouteTableProtocol? public init(resourceGroupName: String, routeTableName: String, subscriptionId: String, parameters: RouteTableProtocol) { self.resourceGroupName = resourceGroupName self.routeTableName = routeTableName self.subscriptionId = subscriptionId self.parameters = parameters super.init() self.method = "Put" self.isLongRunningOperation = true self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{routeTableName}"] = String(describing: self.routeTableName) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) self.body = parameters } public override func encodeBody() throws -> Data? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let encoder = try CoderFactory.encoder(for: mimeType) let encodedValue = try encoder.encode(parameters as? RouteTableData) return encodedValue } throw DecodeError.unknownMimeType } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(RouteTableData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (RouteTableProtocol?, Error?) -> Void) -> Void { client.executeAsyncLRO(command: self) { (result: RouteTableData?, error: Error?) in completionHandler(result, error) } } } }
48.479452
150
0.644815
1d69a84469084b08cbd8b0568711d6e876d5eee6
3,262
// // AUICollectionViewDataSource.swift // PocketDoc // // Created by branderstudio on 10/29/18. // Copyright © 2018 BRANDER. All rights reserved. // import UIKit // MARK: - AUICollectionViewDelegateProxyDelegate public protocol AUICollectionViewDelegateProxyDelegate: class { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) } // MARK: - AUIScrollViewDelegateProxyDelegate public protocol AUIScrollViewDelegate: class { func scrollViewDidScroll(_ scrollView: UIScrollView) func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) } public protocol AUIScrollWillBeginDraggingDelegate: class { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) } // MARK: - AUICollectionViewDelegateProxy open class AUICollectionViewDelegateProxy: NSObject, UICollectionViewDelegate { open weak var delegate: AUICollectionViewDelegateProxyDelegate? open weak var scrollDelegate: AUIScrollViewDelegate? open weak var scrollWillBeginDraggingDelegate: AUIScrollWillBeginDraggingDelegate? open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.collectionView(collectionView, didSelectItemAt: indexPath) } open func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return delegate?.collectionView(collectionView, shouldSelectItemAt: indexPath) ?? true } open func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return delegate?.collectionView(collectionView, shouldHighlightItemAt: indexPath) ?? true } open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { delegate?.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath) } open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { delegate?.collectionView(collectionView, didEndDisplaying: cell, forItemAt: indexPath) } open func scrollViewDidScroll(_ scrollView: UIScrollView) { scrollDelegate?.scrollViewDidScroll(scrollView) } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollDelegate?.scrollViewDidEndDecelerating(scrollView) } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { scrollDelegate?.scrollViewDidEndScrollingAnimation(scrollView) } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { scrollWillBeginDraggingDelegate?.scrollViewWillBeginDragging(scrollView) } }
41.820513
141
0.813611
764964645887f46f1b5e6ea1b8d9f07cd0d06355
1,554
import UIKit /// An extension on CarouselSpot to object specific behavior. extension CarouselSpot { /// Update and return the size for the item at index path. /// /// - parameter indexPath: indexPath: An NSIndexPath. /// /// - returns: CGSize of the item at index path. public func sizeForItem(at indexPath: IndexPath) -> CGSize { guard indexPath.item < component.items.count else { return CGSize.zero } var width = collectionView.frame.width let gridableLayout = layout if let layout = component.layout { if layout.span > 0.0 { if dynamicSpan && Double(component.items.count) < layout.span { width = collectionView.frame.width / CGFloat(component.items.count) width -= gridableLayout.sectionInset.left / CGFloat(component.items.count) width -= gridableLayout.minimumInteritemSpacing } else { width = collectionView.frame.width / CGFloat(layout.span) width -= gridableLayout.sectionInset.left / CGFloat(layout.span) width -= gridableLayout.minimumInteritemSpacing } component.items[indexPath.item].size.width = width } } if component.items[indexPath.item].size.height == 0.0 { component.items[indexPath.item].size.height = collectionView.frame.height - layout.sectionInset.top - layout.sectionInset.bottom - layout.headerReferenceSize.height } return CGSize( width: ceil(component.items[indexPath.item].size.width), height: ceil(component.items[indexPath.item].size.height)) } }
37
170
0.688546
676a9f98b6ac54603719f0839b7b9793648ff2d2
5,552
// Copyright © 2017 Károly Lőrentey. // This file is part of Attabench: https://github.com/attaswift/Attabench // For licensing information, see the file LICENSE.md in the Git repository above. import Foundation protocol ChartScale { var min: Double { get } var max: Double { get } var grid: (major: Double, minor: Double) { get } var gridlines: [Gridline] { get } func position(for value: Double) -> CGFloat } struct EmptyScale: ChartScale { let min: Double = 0 let max: Double = 1 let grid: (major: Double, minor: Double) = (1, 1) let gridlines: [Gridline] = [] func position(for value: Double) -> CGFloat { return CGFloat(value) } } struct LogarithmicScale: ChartScale { let decimal: Bool let labeler: (Int) -> String let min: Double let max: Double let minExponent: Int let maxExponent: Int let grid: (major: Double, minor: Double) init(_ range: ClosedRange<Double>, decimal: Bool, labeler: @escaping (Int) -> String) { let range = (range.lowerBound > 0 ? range : 1e-30 ... range.upperBound) self.decimal = decimal self.labeler = labeler let step = decimal ? 10.0 : 2.0 let smudge = 0.001 // Find last major gridline below range. let rescaledUpperBound: Double if range.lowerBound < 1 { var s: Double = 1 var minExponent = 0 while range.lowerBound * s + smudge < 1 { s *= step minExponent -= 1 } self.min = 1 / s self.minExponent = minExponent rescaledUpperBound = range.upperBound * s } else { var s: Double = 1 var minExponent = 0 while s * step <= range.lowerBound { s *= step minExponent += 1 } self.min = s self.minExponent = minExponent rescaledUpperBound = range.upperBound / s } // Find first major gridline above range. var maxExponent = minExponent var s: Double = 1 repeat { s *= step maxExponent += 1 } while s < rescaledUpperBound * (1 - smudge) self.max = self.min * s self.maxExponent = maxExponent self.grid = (major: log(step) / (log(max) - log(min)), minor: decimal ? log(2) / (log(max) - log(min)) : 0) } var gridlines: [Gridline] { var gridlines: [Gridline] = [] let step = decimal ? 10.0 : 2.0 for exponent in minExponent ... maxExponent { let position = self.position(for: pow(step, Double(exponent))) let label = self.labeler(exponent) gridlines.append(Gridline(.major, position: position, label: label)) } if decimal { var value = 2 * min while true { let position = self.position(for: value) if position > 1.0001 { break } gridlines.append(Gridline(.minor, position: position)) value *= 2 } } return gridlines } func position(for value: Double) -> CGFloat { if value <= 0 { return 0 } return CGFloat((log2(value) - log2(min)) / (log2(max) - log2(min))) } } struct LinearScale: ChartScale { let decimal: Bool let labeler: (Double) -> String let min: Double let max: Double private let majorScale: Double private let minorScale: Double let grid: (major: Double, minor: Double) init(_ range: ClosedRange<Double>, decimal: Bool, labeler: @escaping (Double) -> String) { self.decimal = decimal self.labeler = labeler let steps = (decimal ? [5.0, 2.0] : [2.0]).looped() let desiredDelta: Range<Double> = decimal ? 5.0 ..< 20.0 : 4.0 ..< 16.0 let delta = range.upperBound - range.lowerBound var scale = 1.0 if delta < desiredDelta.lowerBound { while scale * delta < desiredDelta.lowerBound { scale *= steps.next()! } scale = 1 / scale } else if delta > desiredDelta.upperBound { while delta > scale * desiredDelta.upperBound { scale *= steps.next()! } } self.min = scale * floor(range.lowerBound / scale) self.max = scale * ceil(range.upperBound / scale) self.majorScale = scale self.minorScale = scale / 4 self.grid = (major: scale / (max - min), minor: decimal ? minorScale / (max - min) : 0) } var gridlines: [Gridline] { var gridlines: [Gridline] = [] var value = self.min while true { let position = self.position(for: value) if position > 1.0001 { break } let label = self.labeler(value) gridlines.append(Gridline(.major, position: position, label: label)) if decimal { var v = value + minorScale while v < value + majorScale { let p = self.position(for: v) if p > 1.0001 { break } gridlines.append(Gridline(.minor, position: p, label: self.labeler(v))) v += minorScale } } value += majorScale } return gridlines } func position(for value: Double) -> CGFloat { return CGFloat((value - min) / (max - min)) } }
31.908046
94
0.536924
d93f022f55b59a714dacf99ec951b05eaed1512b
3,187
// // EpisodeFilterView.swift // Recast // // Created by Jack Thompson on 10/25/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit enum FilterType: String, CaseIterable { case newest = "Newest" case oldest = "Oldest" case popular = "Popular" case unlistened = "Unlistened" func tag() -> Int { switch self { case .newest: return 0 case .oldest: return 1 case .popular: return 2 case .unlistened: return 3 } } } protocol EpisodeFilterDelegate { func filterEpisodes(by filterType: FilterType) } class EpisodeFilterView: UIView { // MARK: - Variables var stackView: UIStackView! var underline: UIView! var divider: UIView! var selected: FilterType = .newest weak var delegate: PodcastDetailViewController? // MARK: - Constants let underlineHeight = 2.5 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .black stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .equalSpacing for filter in FilterType.allCases { let button = UIButton() button.tag = filter.tag() button.setTitle(filter.rawValue, for: .normal) button.addTarget(self, action: #selector(didSelect), for: .touchUpInside) stackView.addArrangedSubview(button) } underline = UIView() underline.backgroundColor = .white underline.setCornerRadius(forView: .small) divider = UIView() divider.backgroundColor = .gray addSubview(stackView) addSubview(underline) addSubview(divider) setUpConstraints() } func setUpConstraints() { // MARK: - Constants let edgeInset = 22 let dividerHeight = 0.5 stackView.snp.makeConstraints { make in make.top.bottom.equalToSuperview() make.leading.trailing.equalToSuperview().inset(edgeInset) } underline.snp.makeConstraints { make in make.height.equalTo(underlineHeight) make.leading.trailing.equalTo(stackView.subviews[selected.tag()]) make.centerY.equalTo(stackView.snp.bottom) } divider.snp.makeConstraints { make in make.height.equalTo(dividerHeight) make.leading.trailing.equalToSuperview() make.centerY.equalTo(underline.snp.bottom) } } @objc func didSelect(sender: UIButton) { selected = FilterType.allCases[sender.tag] delegate?.filterEpisodes(by: selected) UIView.animate(withDuration: 0.25) { self.underline.snp.remakeConstraints { make in make.height.equalTo(self.underlineHeight) make.leading.trailing.equalTo(self.stackView.subviews[self.selected.tag()]) make.centerY.equalTo(self.stackView.snp.bottom) } self.layoutSubviews() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
27.239316
91
0.620333
d991fec1f087e6f5fef6ce25994f43c8e718b6eb
1,024
import Depressed import Foundation import Nimble import Quick import ResearchKit class FindingHelpViewModelSpec: QuickSpec { override func spec() { var viewModel: FindingHelpViewModel! let infoModel = FindingHelpInformation(url: NSURL(string: "http://example.com")!, organizationName: "Example Alliance Against Depression") beforeEach { viewModel = FindingHelpViewModel(info: infoModel) } describe(".url") { it("is the URL of the model") { expect(viewModel.url).to(equal(infoModel.url)) } } describe(".credits") { it("is the localized string 'find_help_credits_format' and the organization name") { let expectedString = String(format: NSLocalizedString("find_help_credits_format", comment: ""), infoModel.organizationName) expect(viewModel.credits).to(equal(expectedString)) } } } }
29.257143
146
0.600586
e83b95a8b0f7d362b5a58ad2cc24d9e5db9b24bc
2,577
// // ChartDataEntry.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation open class ChartDataEntry: NSObject { /// the actual value (y axis) open var value = Double(0.0) /// the index on the x-axis open var xIndex = Int(0) /// optional spot for additional data this Entry represents open var data: AnyObject? public override required init() { super.init() } public init(value: Double, xIndex: Int) { super.init() self.value = value self.xIndex = xIndex } public init(value: Double, xIndex: Int, data: AnyObject?) { super.init() self.value = value self.xIndex = xIndex self.data = data } // MARK: NSObject open override func isEqual(_ object: Any?) -> Bool { if (object == nil) { return false } if (!(object! as AnyObject).isKind(of: type(of: self))) { return false } if ((object! as AnyObject).data !== data && !((object! as AnyObject).data??.isEqual(self.data))!) { return false } if ((object! as AnyObject).xIndex != xIndex) { return false } if (fabs((object! as AnyObject).value - value) > 0.00001) { return false } return true } // MARK: NSObject open override var description: String { return "ChartDataEntry, xIndex: \(xIndex), value \(value)" } // MARK: NSCopying open func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = type(of: self).init() copy.value = value copy.xIndex = xIndex copy.data = data return copy } } public func ==(lhs: ChartDataEntry, rhs: ChartDataEntry) -> Bool { if (lhs === rhs) { return true } if (!lhs.isKind(of: type(of: rhs))) { return false } if (lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data)) { return false } if (lhs.xIndex != rhs.xIndex) { return false } if (fabs(lhs.value - rhs.value) > 0.00001) { return false } return true }
19.522727
105
0.507955
11c236873d72c74d86ab79de93a2c55445ecb4b4
6,330
import UIKit // MARK: - Color Builders public extension UIColor { convenience init(hex string: String) { var hex = string.hasPrefix("#") ? String(string.dropFirst()) : string guard hex.count == 3 || hex.count == 6 else { self.init(white: 1.0, alpha: 0.0) return } if hex.count == 3 { for (index, char) in hex.enumerated() { hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2)) } } self.init( red: CGFloat((Int(hex, radix: 16)! >> 16) & 0xFF) / 255.0, green: CGFloat((Int(hex, radix: 16)! >> 8) & 0xFF) / 255.0, blue: CGFloat((Int(hex, radix: 16)!) & 0xFF) / 255.0, alpha: 1.0) } @available(*, deprecated: 1.1.2) public static func hex(string: String) -> UIColor { return UIColor(hex: string) } public func colorWithMinimumSaturation(minSaturation: CGFloat) -> UIColor { var (hue, saturation, brightness, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0) getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return saturation < minSaturation ? UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha) : self } public func alpha(_ value: CGFloat) -> UIColor { return withAlphaComponent(value) } } // MARK: - Helpers public extension UIColor { public func hex(_ withPrefix: Bool = true) -> String { var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0) getRed(&r, green: &g, blue: &b, alpha: &a) let prefix = withPrefix ? "#" : "" return String(format: "\(prefix)%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } internal func rgbComponents() -> [CGFloat] { guard let RGB = cgColor.components, RGB.count == 3 else { return [0,0,0] } return RGB } public var isDark: Bool { let RGB = rgbComponents() return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5 } public var isBlackOrWhite: Bool { let RGB = rgbComponents() return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public var isBlack: Bool { let RGB = rgbComponents() return (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public var isWhite: Bool { let RGB = rgbComponents() return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) } public func isDistinctFrom(_ color: UIColor) -> Bool { let bg = rgbComponents() let fg = color.rgbComponents() let threshold: CGFloat = 0.25 var result = false if fabs(bg[0] - fg[0]) > threshold || fabs(bg[1] - fg[1]) > threshold || fabs(bg[2] - fg[2]) > threshold { if fabs(bg[0] - bg[1]) < 0.03 && fabs(bg[0] - bg[2]) < 0.03 { if fabs(fg[0] - fg[1]) < 0.03 && fabs(fg[0] - fg[2]) < 0.03 { result = false } } result = true } return result } public func isContrastingWith(_ color: UIColor) -> Bool { let bg = rgbComponents() let fg = color.rgbComponents() let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2] let contrast = bgLum > fgLum ? (bgLum + 0.05) / (fgLum + 0.05) : (fgLum + 0.05) / (bgLum + 0.05) return 1.6 < contrast } } // MARK: - Gradient public extension Array where Element : UIColor { public func gradient(_ transform: ((_ gradient: inout CAGradientLayer) -> CAGradientLayer)? = nil) -> CAGradientLayer { var gradient = CAGradientLayer() gradient.colors = self.map { $0.cgColor } if let transform = transform { gradient = transform(&gradient) } return gradient } } // MARK: - Components public extension UIColor { var redComponent : CGFloat { get { var r : CGFloat = 0 self.getRed(&r, green: nil , blue: nil, alpha: nil) return r } } var greenComponent : CGFloat { get { var g : CGFloat = 0 self.getRed(nil, green: &g , blue: nil, alpha: nil) return g } } var blueComponent : CGFloat { get { var b : CGFloat = 0 self.getRed(nil, green: nil , blue: &b, alpha: nil) return b } } var alphaComponent : CGFloat { get { var a : CGFloat = 0 self.getRed(nil, green: nil , blue: nil, alpha: &a) return a } } } // MARK: - Blending public extension UIColor { /**adds hue, saturation, and brightness to the HSB components of this color (self)*/ public func addHue(_ hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> UIColor { var (oldHue, oldSat, oldBright, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) getHue(&oldHue, saturation: &oldSat, brightness: &oldBright, alpha: &oldAlpha) return UIColor(hue: oldHue + hue, saturation: oldSat + saturation, brightness: oldBright + brightness, alpha: oldAlpha + alpha) } /**adds red, green, and blue to the RGB components of this color (self)*/ public func addRed(_ red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor { var (oldRed, oldGreen, oldBlue, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) getRed(&oldRed, green: &oldGreen, blue: &oldBlue, alpha: &oldAlpha) return UIColor(red: oldRed + red, green: oldGreen + green, blue: oldBlue + blue, alpha: oldAlpha + alpha) } public func addHSB(color: UIColor) -> UIColor { var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return self.addHue(h, saturation: s, brightness: b, alpha: 0) } public func addRGB(color: UIColor) -> UIColor { return self.addRed(color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: 0) } public func addHSBA(color: UIColor) -> UIColor { var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0) color.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return self.addHue(h, saturation: s, brightness: b, alpha: a) } /**adds the rgb components of two colors*/ public func addRGBA(_ color: UIColor) -> UIColor { return self.addRed(color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: color.alphaComponent) } }
29.71831
131
0.605687
8ff876807d25e45f89325648de6f2c72b1f11702
1,673
import XCTest import Nimble import FileKit @testable import Switt private let lexicalAnalyzer = LexicalAnalyzerImpl(grammarFactory: CachedSwiftGrammarFactory.instance) private func testFile(file: TextFile) -> Bool { do { let contents: String = try file.read() let tree = lexicalAnalyzer.analyze(contents) expect(tree).toNot(beNil(), description: "Can not parse file at \(file.path)") return tree != nil } catch let exception { fail("Unexpected exception: \(exception)") return false } } class TestLexicalAnalyzerOnProjectFilesTests: XCTestCase { func test() { var folder = Path(#file).parent let rootFilename = "Switt.xcodeproj" let rootFolderName = "Switt" while !(folder.contains { $0.fileName == rootFilename }) { folder = folder.parent } let rootFolder = folder + rootFolderName let files = rootFolder.find { (path) -> Bool in path.pathExtension == "swift" } let startDate = NSDate() let timeout: NSTimeInterval = 40 var fails = 0 var testedFiles = 0 for file in (files.map { TextFile(path: $0) }) { testedFiles += 1 if !testFile(file) { fails += 1 if NSDate().timeIntervalSinceDate(startDate) > timeout { break } } } if fails > 0 { // Nice log fail("Lexical analyzer failed to parse \(fails) of \(testedFiles) files") } } }
27.883333
101
0.542738
212a75d0e561017fcbda4c33d445c8d1b275b4c2
232
import Foundation class PostRepository { private var posts = [Post]() func timelineOf(user: User) -> [Post] { return posts.filter { $0.user == user } } func store(post: Post) { posts.append(post) } }
13.647059
41
0.594828
11005e4581d31a1475a8d50f24379fdbb223a037
305
import XCTest @testable import TeslaAPI extension TeslaAPITests { func username() -> String { return "" } func password() -> String { return "" } func accessToken() -> String { return "" } func vehicleIdentifier() -> String { return "" } }
16.944444
40
0.537705
eb0321bfe7ec234347a94a818430b5c45b393d8d
1,450
import UIKit protocol ExportGenericViewModelBinding { func bind(stringViewModel: ExportStringViewModel, locale: Locale) -> UIView func bind(multilineViewModel: ExportStringViewModel, locale: Locale) -> UIView func bind(mnemonicViewModel: ExportMnemonicViewModel, locale: Locale) -> UIView } protocol ExportGenericViewModelProtocol { var option: ExportOption { get } var networkType: Chain { get } var derivationPath: String? { get } var cryptoType: CryptoType { get } func accept(binder: ExportGenericViewModelBinding, locale: Locale) -> UIView } struct ExportStringViewModel: ExportGenericViewModelProtocol { let option: ExportOption let networkType: Chain let derivationPath: String? let cryptoType: CryptoType let data: String func accept(binder: ExportGenericViewModelBinding, locale: Locale) -> UIView { if option == .seed { return binder.bind(multilineViewModel: self, locale: locale) } else { return binder.bind(stringViewModel: self, locale: locale) } } } struct ExportMnemonicViewModel: ExportGenericViewModelProtocol { let option: ExportOption let networkType: Chain let derivationPath: String? let cryptoType: CryptoType let mnemonic: [String] func accept(binder: ExportGenericViewModelBinding, locale: Locale) -> UIView { binder.bind(mnemonicViewModel: self, locale: locale) } }
27.358491
83
0.717241
795ee13ec5226deae4cd6f96f5be4e047063d065
10,162
import Foundation import UIKit public extension UITableView { typealias Complition = (() -> Void) typealias HeaderFooterTuple = (header: UIView?, footer: UIView?) typealias VisibleHeaderFooter = [Int: HeaderFooterTuple] public enum AnimationType { case simple(duration: TimeInterval, direction: Direction, constantDelay: TimeInterval) case spring(duration: TimeInterval, damping: CGFloat, velocity: CGFloat, direction: Direction, constantDelay: TimeInterval) public func animate(tableView: UITableView, reversed: Bool = false, completion: Complition? = nil) { var duration: TimeInterval! var damping: CGFloat = 1 var velocity: CGFloat = 0 var constantDelay: TimeInterval! var direction: Direction! switch self { case .simple(let _duration, let _direction, let _constantDelay): duration = _duration direction = _direction constantDelay = _constantDelay case .spring(let _duration, let _damping, let _velocity, let _direction, let _constantDelay): duration = _duration damping = _damping velocity = _velocity direction = _direction constantDelay = _constantDelay } let _ = tableView.visibleCells let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows let grouped = indexPathsForVisibleRows?.grouped(by: { (indexPath: IndexPath) -> Int in return indexPath.section }).sorted(by: { $0.key < $1.key }) let visibleHeaderFooter = tableView.visibleSectionIndexes() var visibleViews = [UIView]() for items in grouped! { var currentViews: [UIView] = items.value.flatMap { tableView.cellForRow(at: $0) } if let header = visibleHeaderFooter[items.key]?.header { currentViews.insert(header, at: 0) } if let footer = visibleHeaderFooter[items.key]?.footer { currentViews.append(footer) } visibleViews += currentViews } let visibleCellsCount = Double(visibleViews.count) let cells = direction.reverse(for: reversed ? visibleViews.reversed() : visibleViews) cells.enumerated().forEach { item in let delay: TimeInterval = duration / visibleCellsCount * Double(item.offset) + Double(item.offset) * constantDelay direction.startValues(tableView: tableView, for: item.element) let anchor = item.element.layer.anchorPoint UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .curveEaseInOut, animations: { direction.endValues(tableView: tableView, for: item.element) }, completion: { finished in item.element.layer.anchorPoint = anchor completion?() }) // print(duration, delay) } } } public enum Direction { case left(useCellsFrame: Bool) case top(useCellsFrame: Bool) case right(useCellsFrame: Bool) case bottom(useCellsFrame: Bool) case rotation(angle: Double) case rotation3D(type: TransformType) // For testing only init?(rawValue: Int, useCellsFrame: Bool) { switch rawValue { case 0: self = Direction.left(useCellsFrame: useCellsFrame) case 1: self = Direction.top(useCellsFrame: useCellsFrame) case 2: self = Direction.right(useCellsFrame: useCellsFrame) case 3: self = Direction.bottom(useCellsFrame: useCellsFrame) case 4: self = Direction.rotation(angle: -Double.pi / 2) default: return nil } } func startValues(tableView: UITableView, for cell: UIView) { cell.alpha = 0 switch self { case .left(let useCellsFrame): cell.frame.origin.x += useCellsFrame ? cell.frame.width : tableView.frame.width case .top(let useCellsFrame): cell.frame.origin.y += useCellsFrame ? cell.frame.height : tableView.frame.height case .right(let useCellsFrame): cell.frame.origin.x -= useCellsFrame ? cell.frame.width : tableView.frame.width case .bottom(let useCellsFrame): cell.frame.origin.y -= useCellsFrame ? cell.frame.height : tableView.frame.height case .rotation(let angle): cell.transform = CGAffineTransform(rotationAngle: CGFloat(angle)) case .rotation3D(let type): type.set(for: cell) } } func endValues(tableView: UITableView, for cell: UIView) { cell.alpha = 1 switch self { case .left(let useCellsFrame): cell.frame.origin.x -= useCellsFrame ? cell.frame.width : tableView.frame.width case .top(let useCellsFrame): cell.frame.origin.y -= useCellsFrame ? cell.frame.height : tableView.frame.height case .right(let useCellsFrame): cell.frame.origin.x += useCellsFrame ? cell.frame.width : tableView.frame.width case .bottom(let useCellsFrame): cell.frame.origin.y += useCellsFrame ? cell.frame.height : tableView.frame.height case .rotation(_): cell.transform = .identity case .rotation3D(_): cell.layer.transform = CATransform3DIdentity } } func reverse(for cells: [UIView]) -> [UIView] { switch self { case .bottom(_): return cells.reversed() default: return cells } } public enum TransformType { case ironMan case thor case spiderMan case captainMarvel case hulk case daredevil case deadpool case doctorStrange func set(for cell: UIView) { let oldFrame = cell.frame var transform = CATransform3DIdentity transform.m34 = 1.0 / -500 switch self { case .ironMan: cell.layer.anchorPoint = CGPoint(x: 0, y: 0.5) transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 0, 1, 0) case .thor: cell.layer.anchorPoint = CGPoint(x: 0, y: 0.5) transform = CATransform3DRotate(transform, -CGFloat(Double.pi / 2), 0, 1, 0) case .spiderMan: cell.layer.anchorPoint = .zero transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 0, 1, 1) case .captainMarvel: cell.layer.anchorPoint = CGPoint(x: 1, y: 1) transform = CATransform3DRotate(transform, -CGFloat(Double.pi / 2), 1, 1, 1) case .hulk: cell.layer.anchorPoint = CGPoint(x: 1, y: 1) transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 1, 1, 1) case .daredevil: cell.layer.anchorPoint = CGPoint(x: 1, y: 0.5) transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 0, 1, 0) case .deadpool: cell.layer.anchorPoint = CGPoint(x: 1, y: 0.5) transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 1, 0, 1) case .doctorStrange: cell.layer.anchorPoint = CGPoint(x: 0.5, y: 0) transform = CATransform3DRotate(transform, -CGFloat(Double.pi / 2), 1, 0, 0) } cell.frame = oldFrame cell.layer.transform = transform } } } public func reloadData(with animation: AnimationType, reversed: Bool = false, completion: Complition? = nil) { reloadData() animation.animate(tableView: self, reversed: reversed, completion: completion) } } extension UITableView { fileprivate func visibleSectionIndexes() -> VisibleHeaderFooter { let visibleTableViewRect = CGRect(x: contentOffset.x, y: contentOffset.y, width: bounds.size.width, height: bounds.size.height) var visibleHeaderFooter: VisibleHeaderFooter = [:] (0..<numberOfSections).forEach { let headerRect = rectForHeader(inSection: $0) let footerRect = rectForFooter(inSection: $0) let header: UIView? = visibleTableViewRect.intersects(headerRect) ? headerView(forSection: $0) : nil let footer: UIView? = visibleTableViewRect.intersects(footerRect) ? footerView(forSection: $0) : nil let headerFooterTuple: HeaderFooterTuple = (header: header, footer: footer) visibleHeaderFooter[$0] = headerFooterTuple } return visibleHeaderFooter } } extension Array { fileprivate func grouped<T>(by criteria: (Element) -> T) -> [T: [Element]] { var groups = [T: [Element]]() for element in self { let key = criteria(element) if groups.keys.contains(key) == false { groups[key] = [Element]() } groups[key]?.append(element) } return groups } }
41.647541
135
0.546054
dea56d79bdbf3cb736237e817cc0edf19cc9be1e
2,801
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // AppDelegate.swift // AdMobExampleSwift // // [START gmp_config] import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { var configureError:NSError? // Use Google library to configure APIs GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") return true } // [END gmp_config] 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:. } }
45.177419
281
0.76794
08886eeb15089b1f8c3987451ceb7966cd7e0a04
6,493
// // CJServer.swift // libSwerve // // Created by Curtis Jones on 2016.03.15. // Copyright © 2016 Symphonic Systems, Inc. All rights reserved. // import Foundation import Security public struct CJServerStatus: OptionSetType { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } static let None = CJServerStatus(rawValue: 0) static let Starting = CJServerStatus(rawValue: 1 << 0) static let Running = CJServerStatus(rawValue: 2 << 0) static let Stopping = CJServerStatus(rawValue: 3 << 0) static let Stopped = CJServerStatus(rawValue: 4 << 0) } public protocol CJConnection { var context: Any? { get set } var readHandler: CJConnectionReadHandler? { get set } var readHandler2: CJConnectionReadHandler2? { get set } var closeHandler: ((CJConnection) -> Void)? { get set } func open() func close() func pause() func resume() func write(bytes: UnsafePointer<Void>, size: Int, completionHandler: ((Bool) -> Void)?) func write(data: NSData, completionHandler: ((Bool) -> Void)?) func write(string: String, completionHandler: ((Bool) -> Void)?) func log(string: String) } extension CJConnection { func write(data: NSData, completionHandler: ((Bool) -> Void)?) { write(data.bytes, size: data.length, completionHandler: completionHandler) } func write(string: String, completionHandler: ((Bool) -> Void)?) { if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { write(data, completionHandler: completionHandler) } } } public protocol CJTlsConnection: CJConnection { var tlsIdentity: SecIdentity? { get set } var tlsContext: SSLContext? { get set } var tlsObject: AnyObject { get } var tlsReadHandler: SSLReadFunc { get } var tlsWriteHandler: SSLWriteFunc { get } mutating func setupTLS() -> Bool mutating func startTLS() -> Bool func tlsReadCallback(connection: SSLConnectionRef, data: UnsafeMutablePointer<Void>, dataLength: UnsafeMutablePointer<Int>) -> OSStatus func tlsWriteCallback(connection: SSLConnectionRef, data: UnsafePointer<Void>, dataLength: UnsafeMutablePointer<Int>) -> OSStatus } extension CJTlsConnection { mutating func setupTLS() -> Bool { var status: OSStatus = 0 guard let tlsIdentity = self.tlsIdentity else { DLog("self.tlsIdentity must be configured before setupTLS() is called.") return false } // create the new ssl context guard let tlsContext = SSLCreateContext(nil, .ServerSide, .StreamType) else { DLog("Failed to SSLCreateContext!") return false } // configure our callback functions status = SSLSetIOFuncs(tlsContext, tlsReadHandler, tlsWriteHandler) if status != errSecSuccess { DLog("Failed to SSLSetIOFuncs(), \(status)"); return false } // disable unsecure protocol versions status = SSLSetProtocolVersionMin(tlsContext, .TLSProtocol11) if status != errSecSuccess { DLog("Failed to SSLSetProtocolVersionMin(), \(status)"); return false } // set the context object status = SSLSetConnection(tlsContext, UnsafePointer<Void>(Unmanaged.passUnretained(tlsObject).toOpaque())) if status != errSecSuccess { DLog("Failed to SSLSetConnection(), \(status)"); return false } // disable certificate authentication status = SSLSetSessionOption(tlsContext, .BreakOnServerAuth, true) if status != errSecSuccess { DLog("Failed to SSLSetSessionOption(.BreakOnServerAuth), \(status)"); return false } // configure the server certificate status = SSLSetCertificate(tlsContext, [tlsIdentity] as CFArray) if status != errSecSuccess { DLog("Failed to SSLSetCertificate(), \(status)"); return false } // // enable resumable ssl connections // status = SSLSetPeerID(tlsContext, <#T##peerID: UnsafePointer<Void>##UnsafePointer<Void>#>, <#T##peerIDLen: Int##Int#>) // if status != errSecSuccess { DLog("Failed to SSLSetPeerID(), \(status)"); return false } self.tlsIdentity = tlsIdentity self.tlsContext = tlsContext return true } func startTLS() -> Bool { var status: OSStatus = 0 guard let tlsContext = self.tlsContext else { DLog("You may not call startTLS() until after you call setupTLS().") return false } status = SSLHandshake(tlsContext) // this'll happen every time if our server certificate is not "authentic" (ie, paid for with // the moneyz); we'll make it work either way though if status == errSSLPeerAuthCompleted { var peerTrust: SecTrust? var trustResult: SecTrustResultType = 0 // get the peer trust status = SSLCopyPeerTrust(tlsContext, &peerTrust) if status != errSecSuccess || peerTrust == nil { DLog("Failed to SSLCopyPeerTrust(), \(status)"); return false } // we'll allow expired certs status = SecTrustSetOptions(peerTrust!, .AllowExpired) if status != errSecSuccess { DLog("Failed to SecTrustSetOption(.AllowExpired), \(status)"); return false } // evaluate trust for the certificate status = SecTrustEvaluate(peerTrust!, &trustResult) if status != errSecSuccess { DLog("Failed to SecTrustEvaluate(), \(status)"); return false } // explicitly trusted (eg, user clicked always trust) or otherwise valid due to ca if trustResult == UInt32(kSecTrustResultProceed) || trustResult == UInt32(kSecTrustResultUnspecified) { status = SSLHandshake(tlsContext) //DLog("SSLHandshake() = \(status)") } // not trusted for reason other than expiration else if trustResult == UInt32(kSecTrustResultRecoverableTrustFailure) { DLog("Bad cert [1]") return false } else { DLog("Bad cert [1]") return false } } return status == noErr } } public protocol CJTlsSocketConnection: CJTlsConnection, CJSocketConnection { } public typealias CJConnectionReadHandler = (UnsafePointer<Void>, Int) -> Void public typealias CJConnectionReadHandler2 = (dispatch_data_t, Int) -> Void public typealias CJServerAcceptHandler = (CJConnection) -> Void public protocol CJServer { var serverStatus: CJServerStatus { get } var acceptHandler: CJServerAcceptHandler? { get set } mutating func start() throws mutating func stop() throws } /// /// http://codereview.stackexchange.com/questions/71861/pure-swift-solution-for-socket-programming /// internal func CJAddrToString(addr: in_addr, family: sa_family_t) -> String? { var addrstr = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0) var addr = addr inet_ntop(Int32(family), &addr, &addrstr, socklen_t(INET6_ADDRSTRLEN)) return String.fromCString(addrstr) }
32.628141
136
0.72016
e0aef67f6b6637df2826d3e7ceb4592c58639697
4,473
// // Localizer.swift // Localizer // // Created by Vladislav Khambir on 9/8/18. // Copyright (c) RxSwiftCommunity // import RxSwift import RxCocoa public protocol LocalizerType { /// The code of the current language (e.g. en, fr, es) var currentLanguageCode: Driver<String?> { get } /// The code of the current language (e.g. en, fr, es). Use this value for getting the language in a synchronous code. var currentLanguageCodeValue: String? { get } /// Trigger which is used for changing current language. Element is a language code (e.g. en, fr, es). var changeLanguage: PublishRelay<String?> { get } /// Trigger which is used for changing localizer configuration. var changeConfiguration: PublishRelay<LocalizerConfig> { get } /// Localizes the string, using Rx /// /// - Parameter string: String which will be localized /// - Returns: Localized string func localized(_ string: String) -> Driver<String> /// Localizes the string synchronously /// /// - Parameter string: String which will be localized /// - Returns: Localized string func localized(_ string: String) -> String /// Localizes the string, using Rx /// /// - Parameter string: String which will be localized /// - Parameter args: Arguments used to fill the localized string /// - Returns: Localized string func localized(_ string: String, _ args: CVarArg...) -> Driver<String> /// Localizes the string, using Rx /// /// - Parameter string: String which will be localized /// - Parameter args: Arguments used to fill the localized string /// - Returns: Localized string func localized(_ string: String, _ args: CVarArg...) -> String } public class Localizer: LocalizerType { public static let shared: LocalizerType = Localizer() public let changeLanguage = PublishRelay<String?>() public let changeConfiguration = PublishRelay<LocalizerConfig>() public let currentLanguageCode: Driver<String?> public private(set) var currentLanguageCodeValue: String? private let localizationBundle = BehaviorRelay<Bundle>(value: .main) private let configuration = BehaviorRelay<LocalizerConfig>(value: LocalizerConfig()) private let disposeBag = DisposeBag() public func localized(_ string: String) -> Driver<String> { return localizationBundle.asDriver().withLatestFrom(configuration.asDriver()) { $0.localizedString(forKey: string, value: "Unlocalized String", table: $1.tableName) } } public func localized(_ string: String) -> String { return localizationBundle.value.localizedString(forKey: string, value: "Unlocalized String", table: configuration.value.tableName) } public func localized(_ string: String, _ args: CVarArg...) -> Driver<String> { return localizationBundle.asDriver().withLatestFrom(configuration.asDriver()) { String(format: $0.localizedString(forKey: string, value: "Unlocalized String", table: $1.tableName), arguments: args) } } public func localized(_ string: String, _ args: CVarArg...) -> String { return String(format: localizationBundle.value.localizedString(forKey: string, value: "Unlocalized String", table: configuration.value.tableName), arguments: args) } private init() { currentLanguageCode = .combineLatest(changeLanguage.distinctUntilChanged().asDriver(onErrorJustReturn: nil), configuration.asDriver()) { [localizationBundle] languageCode, configuration in configuration.defaults.currentLanguage = languageCode localizationBundle.accept(configuration.bundle.path(forResource: languageCode, ofType: "lproj").flatMap(Bundle.init) ?? localizationBundle.value) return languageCode } currentLanguageCode.drive(onNext: { [weak self] in self?.currentLanguageCodeValue = $0 }).disposed(by: disposeBag) if let currentLanguage = configuration.value.defaults.currentLanguage { changeLanguage.accept(currentLanguage) } else { let preferredLocalization = configuration.value.bundle.preferredLocalizations.first { $0.count < 3 } changeLanguage.accept(preferredLocalization ?? Locale.current.languageCode ?? "en") } changeConfiguration.bind(to: configuration).disposed(by: disposeBag) } }
44.287129
171
0.683881
1ed668b0c4d51fc95a8c31a36367437fd70f6e18
1,641
// // BackgroundView.swift // CrownControl // // Created by Daniel Huri on 11/11/18. // Copyright © 2018 Daniel Huri. All rights reserved. // import UIKit class BackgroundView: UIView { // MARK: - Properties private let styleView = StyleView() private let shadowView = ShadowView() private let flashView = UIView() // MARK: - Setup init(background: CrownAttributes.Style) { super.init(frame: UIScreen.main.bounds) addSubview(shadowView) shadowView.fillSuperview() shadowView.shadow = background.shadow addSubview(styleView) styleView.fillSuperview() styleView.background = background.content styleView.border = background.border addSubview(flashView) flashView.fillSuperview() flashView.isUserInteractionEnabled = false flashView.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() flashView.layer.cornerRadius = min(bounds.width, bounds.height) * 0.5 } func flash(with type: CrownAttributes.Feedback.Descripter.Flash) { switch type { case .active(color: let color, fadeDuration: let duration): flashView.backgroundColor = color UIView.animate(withDuration: duration, delay: 0.0, options: [], animations: { self.flashView.backgroundColor = .clear }, completion: nil) case .none: break } } }
27.813559
89
0.622182
f4eedcd5ea072a74da863ee3f280f819d54560d5
1,390
// // PXResultViewModel+CustomViews.swift // MercadoPagoSDK // // Created by Eden Torres on 1/5/18. // Copyright © 2018 MercadoPago. All rights reserved. // import Foundation internal extension PXResultViewModel { func buildTopCustomView() -> UIView? { if let customView = preference.getTopCustomView(), self.paymentResult.isApproved() { return buildComponentView(customView) } else { return nil } } func buildBottomCustomView() -> UIView? { if let customView = preference.getBottomCustomView(), self.paymentResult.isApproved() { return buildComponentView(customView) } else { return nil } } private func buildComponentView(_ customView: UIView) -> UIView { let componentView = UIView() componentView.translatesAutoresizingMaskIntoConstraints = false customView.translatesAutoresizingMaskIntoConstraints = false PXLayout.setHeight(owner: customView, height: customView.frame.height).isActive = true componentView.addSubview(customView) PXLayout.centerHorizontally(view: customView).isActive = true PXLayout.pinTop(view: customView).isActive = true PXLayout.pinBottom(view: customView).isActive = true PXLayout.matchWidth(ofView: customView).isActive = true return componentView } }
33.902439
95
0.682014
11d905ff325a3858b640ce297166a5c030f0a6c9
2,163
protocol Verifiable { func verify(signatureBase64: String, objectData: Data, keyBase64: String) -> Bool } internal struct Verifier: Verifiable { func verify(signatureBase64: String, objectData: Data, keyBase64: String) -> Bool { Logger.v("Verify data for \(String(data: objectData, encoding: .utf8) ?? "<nil>") with signature \(signatureBase64) and key \(keyBase64)") guard let secKey = createSecKey(for: keyBase64), let signatureData = Data(base64Encoded: signatureBase64) else { return false } var error: Unmanaged<CFError>? let verified = SecKeyVerifySignature(secKey, .ecdsaSignatureMessageX962SHA256, objectData as CFData, signatureData as CFData, &error) Logger.v("Verified: \(String(describing: verified))") if let err = error as? Error { Logger.e(err.localizedDescription) } return verified } private func createSecKey(for base64String: String) -> SecKey? { let attributes: [String: Any] = [ kSecAttrKeyClass as String: kSecAttrKeyClassPublic, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256 ] guard let secKeyData = Data(base64Encoded: base64String) else { return nil } var error: Unmanaged<CFError>? guard let secKey = SecKeyCreateWithData(secKeyData as CFData, attributes as CFDictionary, &error) else { if let err = error?.takeRetainedValue() { Logger.e(err.localizedDescription) } return nil } Logger.v("Key created: \(String(describing: secKey))") if !SecKeyIsAlgorithmSupported(secKey, .verify, .ecdsaSignatureMessageX962SHA256) { Logger.e("Key doesn't support algorithm ecdsaSignatureMessageX962SHA256") return nil } return secKey } }
38.625
146
0.579288
dec812099675bb5c807e245a49ef6f089dfdebc1
693
// // MemeDetailsViewController.swift // MemeMe // // Created by Jess Gates on 6/10/16. // Copyright © 2016 Jess Gates. All rights reserved. // import UIKit class MemeDetailsViewController: UIViewController { @IBOutlet weak var memeDetailImage: UIImageView! var savedMeme: MemeProperties! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = true memeDetailImage.image = savedMeme.memedImage } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tabBarController?.tabBar.isHidden = false } }
23.896552
55
0.683983
67364dad40f644655d9ba5bb7a64aaaa060c0d28
1,400
public struct Group { public let group : GroupSummary public let parentGroups: Groups public let childGroups: Groups public let users: Users public let roles: Roles public let properties: Parameters init?(dictionary: [String: AnyObject]) { guard let group = GroupSummary(dictionary: dictionary), let parentGroupsDictionary = dictionary["parent-groups"] as? [String: AnyObject], let parentGroups = Groups(dictionary: parentGroupsDictionary), let childGroupsDictionary = dictionary["child-groups"] as? [String: AnyObject], let childGroups = Groups(dictionary: childGroupsDictionary), let usersDictionary = dictionary["users"] as? [String: AnyObject], let users = Users(dictionary: usersDictionary), let rolesDictionary = dictionary["roles"] as? [String: AnyObject], let roles = Roles(dictionary: rolesDictionary), let propertiesDictionary = dictionary["properties"] as? [String: AnyObject], let properties = Parameters(dictionary: propertiesDictionary) else { return nil } self.group = group self.parentGroups = parentGroups self.childGroups = childGroups self.users = users self.roles = roles self.properties = properties } }
41.176471
95
0.635
1dc0ac8e221be6957110765d4fe8d912c7302ff1
108,677
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import Darwin import _SwiftFoundationOverlayShims //===----------------------------------------------------------------------===// // NSError (as an out parameter). //===----------------------------------------------------------------------===// public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>? // Note: NSErrorPointer becomes ErrorPointer in Swift 3. public typealias ErrorPointer = NSErrorPointer public // COMPILER_INTRINSIC let _nilObjCError: Error = _GenericObjCError.nilError public // COMPILER_INTRINSIC func _convertNSErrorToError(_ error: NSError?) -> Error { if let error = error { return error } return _nilObjCError } public // COMPILER_INTRINSIC func _convertErrorToNSError(_ error: Error) -> NSError { return unsafeDowncast(_bridgeErrorToNSError(error), to: NSError.self) } /// Describes an error that provides localized messages describing why /// an error occurred and provides more information about the error. public protocol LocalizedError : Error { /// A localized message describing what error occurred. var errorDescription: String? { get } /// A localized message describing the reason for the failure. var failureReason: String? { get } /// A localized message describing how one might recover from the failure. var recoverySuggestion: String? { get } /// A localized message providing "help" text if the user requests help. var helpAnchor: String? { get } } public extension LocalizedError { var errorDescription: String? { return nil } var failureReason: String? { return nil } var recoverySuggestion: String? { return nil } var helpAnchor: String? { return nil } } /// Class that implements the informal protocol /// NSErrorRecoveryAttempting, which is used by NSError when it /// attempts recovery from an error. class _NSErrorRecoveryAttempter { @objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:) func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int, delegate: AnyObject?, didRecoverSelector: Selector, contextInfo: UnsafeMutableRawPointer?) { let error = nsError as Error as! RecoverableError error.attemptRecovery(optionIndex: recoveryOptionIndex) { success in __NSErrorPerformRecoverySelector(delegate, didRecoverSelector, success, contextInfo) } } @objc(attemptRecoveryFromError:optionIndex:) func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int) -> Bool { let error = nsError as Error as! RecoverableError return error.attemptRecovery(optionIndex: recoveryOptionIndex) } } /// Describes an error that may be recoverable by presenting several /// potential recovery options to the user. public protocol RecoverableError : Error { /// Provides a set of possible recovery options to present to the user. var recoveryOptions: [String] { get } /// Attempt to recover from this error when the user selected the /// option at the given index. This routine must call handler and /// indicate whether recovery was successful (or not). /// /// This entry point is used for recovery of errors handled at a /// "document" granularity, that do not affect the entire /// application. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) /// Attempt to recover from this error when the user selected the /// option at the given index. Returns true to indicate /// successful recovery, and false otherwise. /// /// This entry point is used for recovery of errors handled at /// the "application" granularity, where nothing else in the /// application can proceed until the attempted error recovery /// completes. func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool } public extension RecoverableError { /// Default implementation that uses the application-model recovery /// mechanism (``attemptRecovery(optionIndex:)``) to implement /// document-modal recovery. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) { handler(attemptRecovery(optionIndex: recoveryOptionIndex)) } } /// Describes an error type that specifically provides a domain, code, /// and user-info dictionary. public protocol CustomNSError : Error { /// The domain of the error. static var errorDomain: String { get } /// The error code within the given domain. var errorCode: Int { get } /// The user-info dictionary. var errorUserInfo: [String : Any] { get } } public extension CustomNSError { /// Default domain of the error. static var errorDomain: String { return String(reflecting: self) } /// The error code within the given domain. var errorCode: Int { return _getDefaultErrorCode(self) } /// The default user-info dictionary. var errorUserInfo: [String : Any] { return [:] } } extension CustomNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { // The error code of Error with integral raw values is the raw value. public var errorCode: Int { return numericCast(self.rawValue) } } extension CustomNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { // The error code of Error with integral raw values is the raw value. public var errorCode: Int { return numericCast(self.rawValue) } } public extension Error where Self : CustomNSError { /// Default implementation for customized NSErrors. var _domain: String { return Self.errorDomain } /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: SignedInteger { /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error where Self: CustomNSError, Self: RawRepresentable, Self.RawValue: UnsignedInteger { /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error { /// Retrieve the localized description for this error. var localizedDescription: String { return (self as NSError).localizedDescription } } internal let _errorDomainUserInfoProviderQueue = DispatchQueue( label: "SwiftFoundation._errorDomainUserInfoProviderQueue") /// Retrieve the default userInfo dictionary for a given error. public func _getErrorDefaultUserInfo<T: Error>(_ error: T) -> AnyObject? { let hasUserInfoValueProvider: Bool // If the OS supports user info value providers, use those // to lazily populate the user-info dictionary for this domain. if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { // Note: the Cocoa error domain specifically excluded from // user-info value providers. let domain = error._domain if domain != NSCocoaErrorDomain { _errorDomainUserInfoProviderQueue.sync { if NSError.userInfoValueProvider(forDomain: domain) != nil { return } NSError.setUserInfoValueProvider(forDomain: domain) { (nsError, key) in let error = nsError as Error switch key { case NSLocalizedDescriptionKey: return (error as? LocalizedError)?.errorDescription case NSLocalizedFailureReasonErrorKey: return (error as? LocalizedError)?.failureReason case NSLocalizedRecoverySuggestionErrorKey: return (error as? LocalizedError)?.recoverySuggestion case NSHelpAnchorErrorKey: return (error as? LocalizedError)?.helpAnchor case NSLocalizedRecoveryOptionsErrorKey: return (error as? RecoverableError)?.recoveryOptions case NSRecoveryAttempterErrorKey: if error is RecoverableError { return _NSErrorRecoveryAttempter() } return nil default: return nil } } } assert(NSError.userInfoValueProvider(forDomain: domain) != nil) hasUserInfoValueProvider = true } else { hasUserInfoValueProvider = false } } else { hasUserInfoValueProvider = false } // Populate the user-info dictionary var result: [String : Any] // Initialize with custom user-info. if let customNSError = error as? CustomNSError { result = customNSError.errorUserInfo } else { result = [:] } // Handle localized errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let localizedError = error as? LocalizedError { if let description = localizedError.errorDescription { result[NSLocalizedDescriptionKey] = description } if let reason = localizedError.failureReason { result[NSLocalizedFailureReasonErrorKey] = reason } if let suggestion = localizedError.recoverySuggestion { result[NSLocalizedRecoverySuggestionErrorKey] = suggestion } if let helpAnchor = localizedError.helpAnchor { result[NSHelpAnchorErrorKey] = helpAnchor } } // Handle recoverable errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let recoverableError = error as? RecoverableError { result[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter() } return result as AnyObject } // NSError and CFError conform to the standard Error protocol. Compiler // magic allows this to be done as a "toll-free" conversion when an NSError // or CFError is used as an Error existential. extension NSError : Error { @nonobjc public var _domain: String { return domain } @nonobjc public var _code: Int { return code } @nonobjc public var _userInfo: AnyObject? { return userInfo as NSDictionary } /// The "embedded" NSError is itself. @nonobjc public func _getEmbeddedNSError() -> AnyObject? { return self } } extension CFError : Error { public var _domain: String { return CFErrorGetDomain(self) as String } public var _code: Int { return CFErrorGetCode(self) } public var _userInfo: AnyObject? { return CFErrorCopyUserInfo(self) as AnyObject } /// The "embedded" NSError is itself. public func _getEmbeddedNSError() -> AnyObject? { return self } } // An error value to use when an Objective-C API indicates error // but produces a nil error object. public enum _GenericObjCError : Error { case nilError } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectiveCBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// A hook for the runtime to use _ObjectiveCBridgeableError in order to /// attempt an "errorTypeValue as? SomeError" cast. /// /// If the bridge succeeds, the bridged value is written to the uninitialized /// memory pointed to by 'out', and true is returned. Otherwise, 'out' is /// left uninitialized, and false is returned. public func _bridgeNSErrorToError< T : _ObjectiveCBridgeableError >(_ error: NSError, out: UnsafeMutablePointer<T>) -> Bool { if let bridged = T(_bridgedNSError: error) { out.initialize(to: bridged) return true } else { return false } } /// Helper protocol for _BridgedNSError, which used to provide /// default implementations. public protocol __BridgedNSError : Error { static var _nsErrorDomain: String { get } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue == rhs.rawValue } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public var _domain: String { return Self._nsErrorDomain } public var _code: Int { return Int(rawValue) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(IntMax(_bridgedNSError.code))) } public var hashValue: Int { return _code } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue == rhs.rawValue } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public var _domain: String { return Self._nsErrorDomain } public var _code: Int { return Int(bitPattern: UInt(rawValue)) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code)))) } public var hashValue: Int { return _code } } /// Describes a raw representable type that is bridged to a particular /// NSError domain. /// /// This protocol is used primarily to generate the conformance to /// _ObjectiveCBridgeableError for such an enum. public protocol _BridgedNSError : __BridgedNSError, RawRepresentable, _ObjectiveCBridgeableError, Hashable { /// The NSError domain to which this type is bridged. static var _nsErrorDomain: String { get } } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : __BridgedNSError, _ObjectiveCBridgeableError, CustomNSError, Hashable { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } /// TODO: Better way to do this? internal func _stringDictToAnyHashableDict(_ input: [String : Any]) -> [AnyHashable : Any] { var result = [AnyHashable : Any](minimumCapacity: input.count) for (k, v) in input { result[k] = v } return result } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: _stringDictToAnyHashableDict(userInfo))) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return errorUserInfo } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: _stringDictToAnyHashableDict(userInfo))) } } /// Implementation of __BridgedNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { /// Default implementation of ``init(_bridgedNSError)`` to provide /// bridging from NSError. public init?(_bridgedNSError error: NSError) { if error.domain != Self._nsErrorDomain { return nil } self.init(_nsError: error) } } /// Implementation of CustomNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { // FIXME: Would prefer to have a clear "extract an NSError // directly" operation. static var errorDomain: String { return _nsErrorDomain } var errorCode: Int { return _nsError.code } var errorUserInfo: [String : Any] { var result: [String : Any] = [:] for (key, value) in _nsError.userInfo { guard let stringKey = key.base as? String else { continue } result[stringKey] = value } return result } } /// Implementation of Hashable for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { var hashValue: Int { return _nsError.hashValue } } /// Describes the code of an error. public protocol _ErrorCodeProtocol : Equatable { /// The corresponding error code. associatedtype _ErrorType // FIXME: We want _ErrorType to be _BridgedStoredNSError and have its // Code match Self, but we cannot express those requirements yet. } extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError { /// Allow one to match an error code against an arbitrary error. public static func ~=(match: Self, error: Error) -> Bool { guard let specificError = error as? Self._ErrorType else { return false } // FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code. let specificCode = specificError.code as! Self return match == specificCode } } extension _BridgedStoredNSError { /// Retrieve the embedded NSError from a bridged, stored NSError. public func _getEmbeddedNSError() -> AnyObject? { return _nsError } public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._nsError.isEqual(rhs._nsError) } } @available(*, unavailable, renamed: "CocoaError") public typealias NSCocoaError = CocoaError /// Describes errors within the Cocoa error domain. public struct CocoaError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSCocoaErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSCocoaErrorDomain } /// The error code itself. public struct Code : RawRepresentable, Hashable, _ErrorCodeProtocol { public typealias _ErrorType = CocoaError public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue } } } public extension CocoaError { private var _nsUserInfo: [AnyHashable : Any] { return (self as NSError).userInfo } /// The file path associated with the error, if any. var filePath: String? { return _nsUserInfo[NSFilePathErrorKey as NSString] as? String } /// The string encoding associated with this error, if any. var stringEncoding: String.Encoding? { return (_nsUserInfo[NSStringEncodingErrorKey as NSString] as? NSNumber) .map { String.Encoding(rawValue: $0.uintValue) } } /// The underlying error behind this error, if any. var underlying: Error? { return _nsUserInfo[NSUnderlyingErrorKey as NSString] as? Error } /// The URL associated with this error, if any. var url: URL? { return _nsUserInfo[NSURLErrorKey as NSString] as? URL } } public extension CocoaError { public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable : Any]? = nil, url: URL? = nil) -> Error { var info: [AnyHashable : Any] = userInfo ?? [:] if let url = url { info[NSURLErrorKey] = url } return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info) } } extension CocoaError.Code { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } public static var coderInvalidValue: CocoaError.Code { return CocoaError.Code(rawValue: 4866) } } extension CocoaError.Code { @available(*, deprecated, renamed: "fileNoSuchFile") public static var fileNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 4) } @available(*, deprecated, renamed: "fileLocking") public static var fileLockingError: CocoaError.Code { return CocoaError.Code(rawValue: 255) } @available(*, deprecated, renamed: "fileReadUnknown") public static var fileReadUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 256) } @available(*, deprecated, renamed: "fileReadNoPermission") public static var fileReadNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 257) } @available(*, deprecated, renamed: "fileReadInvalidFileName") public static var fileReadInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 258) } @available(*, deprecated, renamed: "fileReadCorruptFile") public static var fileReadCorruptFileError: CocoaError.Code { return CocoaError.Code(rawValue: 259) } @available(*, deprecated, renamed: "fileReadNoSuchFile") public static var fileReadNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 260) } @available(*, deprecated, renamed: "fileReadInapplicableStringEncoding") public static var fileReadInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 261) } @available(*, deprecated, renamed: "fileReadUnsupportedScheme") public static var fileReadUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadTooLarge") public static var fileReadTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadUnknownStringEncoding") public static var fileReadUnknownStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 264) } @available(*, deprecated, renamed: "fileWriteUnknown") public static var fileWriteUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 512) } @available(*, deprecated, renamed: "fileWriteNoPermission") public static var fileWriteNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 513) } @available(*, deprecated, renamed: "fileWriteInvalidFileName") public static var fileWriteInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) @available(*, deprecated, renamed: "fileWriteFileExists") public static var fileWriteFileExistsError: CocoaError.Code { return CocoaError.Code(rawValue: 516) } @available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding") public static var fileWriteInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 517) } @available(*, deprecated, renamed: "fileWriteUnsupportedScheme") public static var fileWriteUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 518) } @available(*, deprecated, renamed: "fileWriteOutOfSpace") public static var fileWriteOutOfSpaceError: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "fileWriteVolumeReadOnly") public static var fileWriteVolumeReadOnlyError: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountUnknown") public static var fileManagerUnmountUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountBusy") public static var fileManagerUnmountBusyError: CocoaError.Code { return CocoaError.Code(rawValue: 769) } @available(*, deprecated, renamed: "keyValueValidation") public static var keyValueValidationError: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } @available(*, deprecated, renamed: "formatting") public static var formattingError: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } @available(*, deprecated, renamed: "userCancelled") public static var userCancelledError: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) @available(*, deprecated, renamed: "featureUnsupported") public static var featureUnsupportedError: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableNotLoadable") public static var executableNotLoadableError: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableArchitectureMismatch") public static var executableArchitectureMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableRuntimeMismatch") public static var executableRuntimeMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLoad") public static var executableLoadError: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLink") public static var executableLinkError: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadCorrupt") public static var propertyListReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadUnknownVersion") public static var propertyListReadUnknownVersionError: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadStream") public static var propertyListReadStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListWriteStream") public static var propertyListWriteStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "propertyListWriteInvalid") public static var propertyListWriteInvalidError: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileUnavailable") public static var ubiquitousFileUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffFailed") public static var userActivityHandoffFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityConnectionUnavailable") public static var userActivityConnectionUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut") public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge") public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderReadCorrupt") public static var coderReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderValueNotFound") public static var coderValueNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } public static var coderInvalidValue: CocoaError.Code { return CocoaError.Code(rawValue: 4866) } } extension CocoaError { @available(*, deprecated, renamed: "fileNoSuchFile") public static var fileNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 4) } @available(*, deprecated, renamed: "fileLocking") public static var fileLockingError: CocoaError.Code { return CocoaError.Code(rawValue: 255) } @available(*, deprecated, renamed: "fileReadUnknown") public static var fileReadUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 256) } @available(*, deprecated, renamed: "fileReadNoPermission") public static var fileReadNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 257) } @available(*, deprecated, renamed: "fileReadInvalidFileName") public static var fileReadInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 258) } @available(*, deprecated, renamed: "fileReadCorruptFile") public static var fileReadCorruptFileError: CocoaError.Code { return CocoaError.Code(rawValue: 259) } @available(*, deprecated, renamed: "fileReadNoSuchFile") public static var fileReadNoSuchFileError: CocoaError.Code { return CocoaError.Code(rawValue: 260) } @available(*, deprecated, renamed: "fileReadInapplicableStringEncoding") public static var fileReadInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 261) } @available(*, deprecated, renamed: "fileReadUnsupportedScheme") public static var fileReadUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 262) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadTooLarge") public static var fileReadTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 263) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "fileReadUnknownStringEncoding") public static var fileReadUnknownStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 264) } @available(*, deprecated, renamed: "fileWriteUnknown") public static var fileWriteUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 512) } @available(*, deprecated, renamed: "fileWriteNoPermission") public static var fileWriteNoPermissionError: CocoaError.Code { return CocoaError.Code(rawValue: 513) } @available(*, deprecated, renamed: "fileWriteInvalidFileName") public static var fileWriteInvalidFileNameError: CocoaError.Code { return CocoaError.Code(rawValue: 514) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 5.0) @available(*, deprecated, renamed: "fileWriteFileExists") public static var fileWriteFileExistsError: CocoaError.Code { return CocoaError.Code(rawValue: 516) } @available(*, deprecated, renamed: "fileWriteInapplicableStringEncoding") public static var fileWriteInapplicableStringEncodingError: CocoaError.Code { return CocoaError.Code(rawValue: 517) } @available(*, deprecated, renamed: "fileWriteUnsupportedScheme") public static var fileWriteUnsupportedSchemeError: CocoaError.Code { return CocoaError.Code(rawValue: 518) } @available(*, deprecated, renamed: "fileWriteOutOfSpace") public static var fileWriteOutOfSpaceError: CocoaError.Code { return CocoaError.Code(rawValue: 640) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "fileWriteVolumeReadOnly") public static var fileWriteVolumeReadOnlyError: CocoaError.Code { return CocoaError.Code(rawValue: 642) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountUnknown") public static var fileManagerUnmountUnknownError: CocoaError.Code { return CocoaError.Code(rawValue: 768) } @available(OSX, introduced: 10.11) @available(iOS, unavailable) @available(*, deprecated, renamed: "fileManagerUnmountBusy") public static var fileManagerUnmountBusyError: CocoaError.Code { return CocoaError.Code(rawValue: 769) } @available(*, deprecated, renamed: "keyValueValidation") public static var keyValueValidationError: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } @available(*, deprecated, renamed: "formatting") public static var formattingError: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } @available(*, deprecated, renamed: "userCancelled") public static var userCancelledError: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) @available(*, deprecated, renamed: "featureUnsupported") public static var featureUnsupportedError: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableNotLoadable") public static var executableNotLoadableError: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableArchitectureMismatch") public static var executableArchitectureMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableRuntimeMismatch") public static var executableRuntimeMismatchError: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLoad") public static var executableLoadError: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) @available(*, deprecated, renamed: "executableLink") public static var executableLinkError: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadCorrupt") public static var propertyListReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadUnknownVersion") public static var propertyListReadUnknownVersionError: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListReadStream") public static var propertyListReadStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) @available(*, deprecated, renamed: "propertyListWriteStream") public static var propertyListWriteStreamError: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "propertyListWriteInvalid") public static var propertyListWriteInvalidError: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileUnavailable") public static var ubiquitousFileUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) @available(*, deprecated, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var ubiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffFailed") public static var userActivityHandoffFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityConnectionUnavailable") public static var userActivityConnectionUnavailableError: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityRemoteApplicationTimedOut") public static var userActivityRemoteApplicationTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) @available(*, deprecated, renamed: "userActivityHandoffUserInfoTooLarge") public static var userActivityHandoffUserInfoTooLargeError: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderReadCorrupt") public static var coderReadCorruptError: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) @available(*, deprecated, renamed: "coderValueNotFound") public static var coderValueNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } extension CocoaError { @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public var isCoderError: Bool { return code.rawValue >= 4864 && code.rawValue <= 4991 } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public var isExecutableError: Bool { return code.rawValue >= 3584 && code.rawValue <= 3839 } public var isFileError: Bool { return code.rawValue >= 0 && code.rawValue <= 1023 } public var isFormattingError: Bool { return code.rawValue >= 2048 && code.rawValue <= 2559 } @available(OSX, introduced: 10.6) @available(iOS, introduced: 4.0) public var isPropertyListError: Bool { return code.rawValue >= 3840 && code.rawValue <= 4095 } @available(OSX, introduced: 10.9) @available(iOS, introduced: 7.0) public var isUbiquitousFileError: Bool { return code.rawValue >= 4352 && code.rawValue <= 4607 } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public var isUserActivityError: Bool { return code.rawValue >= 4608 && code.rawValue <= 4863 } public var isValidationError: Bool { return code.rawValue >= 1024 && code.rawValue <= 2047 } @available(OSX, introduced: 10.8) @available(iOS, introduced: 6.0) public var isXPCConnectionError: Bool { return code.rawValue >= 4096 && code.rawValue <= 4224 } } extension CocoaError.Code { @available(*, unavailable, renamed: "fileNoSuchFile") public static var FileNoSuchFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileLocking") public static var FileLockingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknown") public static var FileReadUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoPermission") public static var FileReadNoPermissionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInvalidFileName") public static var FileReadInvalidFileNameError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadCorruptFile") public static var FileReadCorruptFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadNoSuchFile") public static var FileReadNoSuchFileError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadInapplicableStringEncoding") public static var FileReadInapplicableStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnsupportedScheme") public static var FileReadUnsupportedSchemeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadTooLarge") public static var FileReadTooLargeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileReadUnknownStringEncoding") public static var FileReadUnknownStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnknown") public static var FileWriteUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteNoPermission") public static var FileWriteNoPermissionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInvalidFileName") public static var FileWriteInvalidFileNameError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteFileExists") public static var FileWriteFileExistsError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteInapplicableStringEncoding") public static var FileWriteInapplicableStringEncodingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteUnsupportedScheme") public static var FileWriteUnsupportedSchemeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteOutOfSpace") public static var FileWriteOutOfSpaceError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileWriteVolumeReadOnly") public static var FileWriteVolumeReadOnlyError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountUnknown") public static var FileManagerUnmountUnknownError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileManagerUnmountBusy") public static var FileManagerUnmountBusyError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "keyValueValidation") public static var KeyValueValidationError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "formatting") public static var FormattingError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelled") public static var UserCancelledError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "featureUnsupported") public static var FeatureUnsupportedError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableNotLoadable") public static var ExecutableNotLoadableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableArchitectureMismatch") public static var ExecutableArchitectureMismatchError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableRuntimeMismatch") public static var ExecutableRuntimeMismatchError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLoad") public static var ExecutableLoadError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "executableLink") public static var ExecutableLinkError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadCorrupt") public static var PropertyListReadCorruptError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadUnknownVersion") public static var PropertyListReadUnknownVersionError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListReadStream") public static var PropertyListReadStreamError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteStream") public static var PropertyListWriteStreamError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "propertyListWriteInvalid") public static var PropertyListWriteInvalidError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInterrupted") public static var XPCConnectionInterrupted: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionInvalid") public static var XPCConnectionInvalid: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "xpcConnectionReplyInvalid") public static var XPCConnectionReplyInvalid: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUnavailable") public static var UbiquitousFileUnavailableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileNotUploadedDueToQuota") public static var UbiquitousFileNotUploadedDueToQuotaError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "ubiquitousFileUbiquityServerNotAvailable") public static var UbiquitousFileUbiquityServerNotAvailable: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffFailed") public static var UserActivityHandoffFailedError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityConnectionUnavailable") public static var UserActivityConnectionUnavailableError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityRemoteApplicationTimedOut") public static var UserActivityRemoteApplicationTimedOutError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userActivityHandoffUserInfoTooLarge") public static var UserActivityHandoffUserInfoTooLargeError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderReadCorrupt") public static var CoderReadCorruptError: CocoaError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "coderValueNotFound") public static var CoderValueNotFoundError: CocoaError.Code { fatalError("unavailable accessor can't be called") } } /// Describes errors in the URL error domain. public struct URLError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSURLErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSURLErrorDomain } /// The error code itself. public struct Code : RawRepresentable, Hashable, _ErrorCodeProtocol { public typealias _ErrorType = URLError public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue } } } public extension URLError.Code { public static var unknown: URLError.Code { return URLError.Code(rawValue: -1) } public static var cancelled: URLError.Code { return URLError.Code(rawValue: -999) } public static var badURL: URLError.Code { return URLError.Code(rawValue: -1000) } public static var timedOut: URLError.Code { return URLError.Code(rawValue: -1001) } public static var unsupportedURL: URLError.Code { return URLError.Code(rawValue: -1002) } public static var cannotFindHost: URLError.Code { return URLError.Code(rawValue: -1003) } public static var cannotConnectToHost: URLError.Code { return URLError.Code(rawValue: -1004) } public static var networkConnectionLost: URLError.Code { return URLError.Code(rawValue: -1005) } public static var dnsLookupFailed: URLError.Code { return URLError.Code(rawValue: -1006) } public static var httpTooManyRedirects: URLError.Code { return URLError.Code(rawValue: -1007) } public static var resourceUnavailable: URLError.Code { return URLError.Code(rawValue: -1008) } public static var notConnectedToInternet: URLError.Code { return URLError.Code(rawValue: -1009) } public static var redirectToNonExistentLocation: URLError.Code { return URLError.Code(rawValue: -1010) } public static var badServerResponse: URLError.Code { return URLError.Code(rawValue: -1011) } public static var userCancelledAuthentication: URLError.Code { return URLError.Code(rawValue: -1012) } public static var userAuthenticationRequired: URLError.Code { return URLError.Code(rawValue: -1013) } public static var zeroByteResource: URLError.Code { return URLError.Code(rawValue: -1014) } public static var cannotDecodeRawData: URLError.Code { return URLError.Code(rawValue: -1015) } public static var cannotDecodeContentData: URLError.Code { return URLError.Code(rawValue: -1016) } public static var cannotParseResponse: URLError.Code { return URLError.Code(rawValue: -1017) } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var appTransportSecurityRequiresSecureConnection: URLError.Code { return URLError.Code(rawValue: -1022) } public static var fileDoesNotExist: URLError.Code { return URLError.Code(rawValue: -1100) } public static var fileIsDirectory: URLError.Code { return URLError.Code(rawValue: -1101) } public static var noPermissionsToReadFile: URLError.Code { return URLError.Code(rawValue: -1102) } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var dataLengthExceedsMaximum: URLError.Code { return URLError.Code(rawValue: -1103) } public static var secureConnectionFailed: URLError.Code { return URLError.Code(rawValue: -1200) } public static var serverCertificateHasBadDate: URLError.Code { return URLError.Code(rawValue: -1201) } public static var serverCertificateUntrusted: URLError.Code { return URLError.Code(rawValue: -1202) } public static var serverCertificateHasUnknownRoot: URLError.Code { return URLError.Code(rawValue: -1203) } public static var serverCertificateNotYetValid: URLError.Code { return URLError.Code(rawValue: -1204) } public static var clientCertificateRejected: URLError.Code { return URLError.Code(rawValue: -1205) } public static var clientCertificateRequired: URLError.Code { return URLError.Code(rawValue: -1206) } public static var cannotLoadFromNetwork: URLError.Code { return URLError.Code(rawValue: -2000) } public static var cannotCreateFile: URLError.Code { return URLError.Code(rawValue: -3000) } public static var cannotOpenFile: URLError.Code { return URLError.Code(rawValue: -3001) } public static var cannotCloseFile: URLError.Code { return URLError.Code(rawValue: -3002) } public static var cannotWriteToFile: URLError.Code { return URLError.Code(rawValue: -3003) } public static var cannotRemoveFile: URLError.Code { return URLError.Code(rawValue: -3004) } public static var cannotMoveFile: URLError.Code { return URLError.Code(rawValue: -3005) } public static var downloadDecodingFailedMidStream: URLError.Code { return URLError.Code(rawValue: -3006) } public static var downloadDecodingFailedToComplete: URLError.Code { return URLError.Code(rawValue: -3007) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var internationalRoamingOff: URLError.Code { return URLError.Code(rawValue: -1018) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var callIsActive: URLError.Code { return URLError.Code(rawValue: -1019) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var dataNotAllowed: URLError.Code { return URLError.Code(rawValue: -1020) } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var requestBodyStreamExhausted: URLError.Code { return URLError.Code(rawValue: -1021) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionRequiresSharedContainer: URLError.Code { return URLError.Code(rawValue: -995) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionInUseByAnotherProcess: URLError.Code { return URLError.Code(rawValue: -996) } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionWasDisconnected: URLError.Code { return URLError.Code(rawValue: -997) } } public extension URLError { private var _nsUserInfo: [AnyHashable : Any] { return (self as NSError).userInfo } /// The URL which caused a load to fail. public var failingURL: URL? { return _nsUserInfo[NSURLErrorFailingURLErrorKey as NSString] as? URL } /// The string for the URL which caused a load to fail. public var failureURLString: String? { return _nsUserInfo[NSURLErrorFailingURLStringErrorKey as NSString] as? String } /// The state of a failed SSL handshake. public var failureURLPeerTrust: SecTrust? { if let secTrust = _nsUserInfo[NSURLErrorFailingURLPeerTrustErrorKey as NSString] { return (secTrust as! SecTrust) } return nil } } public extension URLError { public static var unknown: URLError.Code { return .unknown } public static var cancelled: URLError.Code { return .cancelled } public static var badURL: URLError.Code { return .badURL } public static var timedOut: URLError.Code { return .timedOut } public static var unsupportedURL: URLError.Code { return .unsupportedURL } public static var cannotFindHost: URLError.Code { return .cannotFindHost } public static var cannotConnectToHost: URLError.Code { return .cannotConnectToHost } public static var networkConnectionLost: URLError.Code { return .networkConnectionLost } public static var dnsLookupFailed: URLError.Code { return .dnsLookupFailed } public static var httpTooManyRedirects: URLError.Code { return .httpTooManyRedirects } public static var resourceUnavailable: URLError.Code { return .resourceUnavailable } public static var notConnectedToInternet: URLError.Code { return .notConnectedToInternet } public static var redirectToNonExistentLocation: URLError.Code { return .redirectToNonExistentLocation } public static var badServerResponse: URLError.Code { return .badServerResponse } public static var userCancelledAuthentication: URLError.Code { return .userCancelledAuthentication } public static var userAuthenticationRequired: URLError.Code { return .userAuthenticationRequired } public static var zeroByteResource: URLError.Code { return .zeroByteResource } public static var cannotDecodeRawData: URLError.Code { return .cannotDecodeRawData } public static var cannotDecodeContentData: URLError.Code { return .cannotDecodeContentData } public static var cannotParseResponse: URLError.Code { return .cannotParseResponse } @available(OSX, introduced: 10.11) @available(iOS, introduced: 9.0) public static var appTransportSecurityRequiresSecureConnection: URLError.Code { return .appTransportSecurityRequiresSecureConnection } public static var fileDoesNotExist: URLError.Code { return .fileDoesNotExist } public static var fileIsDirectory: URLError.Code { return .fileIsDirectory } public static var noPermissionsToReadFile: URLError.Code { return .noPermissionsToReadFile } @available(OSX, introduced: 10.5) @available(iOS, introduced: 2.0) public static var dataLengthExceedsMaximum: URLError.Code { return .dataLengthExceedsMaximum } public static var secureConnectionFailed: URLError.Code { return .secureConnectionFailed } public static var serverCertificateHasBadDate: URLError.Code { return .serverCertificateHasBadDate } public static var serverCertificateUntrusted: URLError.Code { return .serverCertificateUntrusted } public static var serverCertificateHasUnknownRoot: URLError.Code { return .serverCertificateHasUnknownRoot } public static var serverCertificateNotYetValid: URLError.Code { return .serverCertificateNotYetValid } public static var clientCertificateRejected: URLError.Code { return .clientCertificateRejected } public static var clientCertificateRequired: URLError.Code { return .clientCertificateRequired } public static var cannotLoadFromNetwork: URLError.Code { return .cannotLoadFromNetwork } public static var cannotCreateFile: URLError.Code { return .cannotCreateFile } public static var cannotOpenFile: URLError.Code { return .cannotOpenFile } public static var cannotCloseFile: URLError.Code { return .cannotCloseFile } public static var cannotWriteToFile: URLError.Code { return .cannotWriteToFile } public static var cannotRemoveFile: URLError.Code { return .cannotRemoveFile } public static var cannotMoveFile: URLError.Code { return .cannotMoveFile } public static var downloadDecodingFailedMidStream: URLError.Code { return .downloadDecodingFailedMidStream } public static var downloadDecodingFailedToComplete: URLError.Code { return .downloadDecodingFailedToComplete } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var internationalRoamingOff: URLError.Code { return .internationalRoamingOff } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var callIsActive: URLError.Code { return .callIsActive } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var dataNotAllowed: URLError.Code { return .dataNotAllowed } @available(OSX, introduced: 10.7) @available(iOS, introduced: 3.0) public static var requestBodyStreamExhausted: URLError.Code { return .requestBodyStreamExhausted } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionRequiresSharedContainer: Code { return .backgroundSessionRequiresSharedContainer } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionInUseByAnotherProcess: Code { return .backgroundSessionInUseByAnotherProcess } @available(OSX, introduced: 10.10) @available(iOS, introduced: 8.0) public static var backgroundSessionWasDisconnected: Code { return .backgroundSessionWasDisconnected } } extension URLError { @available(*, unavailable, renamed: "unknown") public static var Unknown: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cancelled") public static var Cancelled: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badURL") public static var BadURL: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "timedOut") public static var TimedOut: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "unsupportedURL") public static var UnsupportedURL: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotFindHost") public static var CannotFindHost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotConnectToHost") public static var CannotConnectToHost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "networkConnectionLost") public static var NetworkConnectionLost: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dnsLookupFailed") public static var DNSLookupFailed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "httpTooManyRedirects") public static var HTTPTooManyRedirects: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "resourceUnavailable") public static var ResourceUnavailable: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "notConnectedToInternet") public static var NotConnectedToInternet: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "redirectToNonExistentLocation") public static var RedirectToNonExistentLocation: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "badServerResponse") public static var BadServerResponse: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userCancelledAuthentication") public static var UserCancelledAuthentication: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "userAuthenticationRequired") public static var UserAuthenticationRequired: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "zeroByteResource") public static var ZeroByteResource: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeRawData") public static var CannotDecodeRawData: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotDecodeContentData") public static var CannotDecodeContentData: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotParseResponse") public static var CannotParseResponse: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "appTransportSecurityRequiresSecureConnection") public static var AppTransportSecurityRequiresSecureConnection: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileDoesNotExist") public static var FileDoesNotExist: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "fileIsDirectory") public static var FileIsDirectory: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "noPermissionsToReadFile") public static var NoPermissionsToReadFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dataLengthExceedsMaximum") public static var DataLengthExceedsMaximum: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "secureConnectionFailed") public static var SecureConnectionFailed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasBadDate") public static var ServerCertificateHasBadDate: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateUntrusted") public static var ServerCertificateUntrusted: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateHasUnknownRoot") public static var ServerCertificateHasUnknownRoot: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "serverCertificateNotYetValid") public static var ServerCertificateNotYetValid: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRejected") public static var ClientCertificateRejected: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "clientCertificateRequired") public static var ClientCertificateRequired: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotLoadFromNetwork") public static var CannotLoadFromNetwork: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCreateFile") public static var CannotCreateFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotOpenFile") public static var CannotOpenFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotCloseFile") public static var CannotCloseFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotWriteToFile") public static var CannotWriteToFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotRemoveFile") public static var CannotRemoveFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "cannotMoveFile") public static var CannotMoveFile: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedMidStream") public static var DownloadDecodingFailedMidStream: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "downloadDecodingFailedToComplete") public static var DownloadDecodingFailedToComplete: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "internationalRoamingOff") public static var InternationalRoamingOff: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "callIsActive") public static var CallIsActive: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "dataNotAllowed") public static var DataNotAllowed: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "requestBodyStreamExhausted") public static var RequestBodyStreamExhausted: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionRequiresSharedContainer") public static var BackgroundSessionRequiresSharedContainer: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionInUseByAnotherProcess") public static var BackgroundSessionInUseByAnotherProcess: URLError.Code { fatalError("unavailable accessor can't be called") } @available(*, unavailable, renamed: "backgroundSessionWasDisconnected") public static var BackgroundSessionWasDisconnected: URLError.Code { fatalError("unavailable accessor can't be called") } } /// Describes an error in the POSIX error domain. public struct POSIXError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSPOSIXErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSPOSIXErrorDomain } public typealias Code = POSIXErrorCode } extension POSIXErrorCode : _ErrorCodeProtocol { public typealias _ErrorType = POSIXError } extension POSIXError { public static var EPERM: POSIXErrorCode { return .EPERM } /// No such file or directory. public static var ENOENT: POSIXErrorCode { return .ENOENT } /// No such process. public static var ESRCH: POSIXErrorCode { return .ESRCH } /// Interrupted system call. public static var EINTR: POSIXErrorCode { return .EINTR } /// Input/output error. public static var EIO: POSIXErrorCode { return .EIO } /// Device not configured. public static var ENXIO: POSIXErrorCode { return .ENXIO } /// Argument list too long. public static var E2BIG: POSIXErrorCode { return .E2BIG } /// Exec format error. public static var ENOEXEC: POSIXErrorCode { return .ENOEXEC } /// Bad file descriptor. public static var EBADF: POSIXErrorCode { return .EBADF } /// No child processes. public static var ECHILD: POSIXErrorCode { return .ECHILD } /// Resource deadlock avoided. public static var EDEADLK: POSIXErrorCode { return .EDEADLK } /// Cannot allocate memory. public static var ENOMEM: POSIXErrorCode { return .ENOMEM } /// Permission denied. public static var EACCES: POSIXErrorCode { return .EACCES } /// Bad address. public static var EFAULT: POSIXErrorCode { return .EFAULT } /// Block device required. public static var ENOTBLK: POSIXErrorCode { return .ENOTBLK } /// Device / Resource busy. public static var EBUSY: POSIXErrorCode { return .EBUSY } /// File exists. public static var EEXIST: POSIXErrorCode { return .EEXIST } /// Cross-device link. public static var EXDEV: POSIXErrorCode { return .EXDEV } /// Operation not supported by device. public static var ENODEV: POSIXErrorCode { return .ENODEV } /// Not a directory. public static var ENOTDIR: POSIXErrorCode { return .ENOTDIR } /// Is a directory. public static var EISDIR: POSIXErrorCode { return .EISDIR } /// Invalid argument. public static var EINVAL: POSIXErrorCode { return .EINVAL } /// Too many open files in system. public static var ENFILE: POSIXErrorCode { return .ENFILE } /// Too many open files. public static var EMFILE: POSIXErrorCode { return .EMFILE } /// Inappropriate ioctl for device. public static var ENOTTY: POSIXErrorCode { return .ENOTTY } /// Text file busy. public static var ETXTBSY: POSIXErrorCode { return .ETXTBSY } /// File too large. public static var EFBIG: POSIXErrorCode { return .EFBIG } /// No space left on device. public static var ENOSPC: POSIXErrorCode { return .ENOSPC } /// Illegal seek. public static var ESPIPE: POSIXErrorCode { return .ESPIPE } /// Read-only file system. public static var EROFS: POSIXErrorCode { return .EROFS } /// Too many links. public static var EMLINK: POSIXErrorCode { return .EMLINK } /// Broken pipe. public static var EPIPE: POSIXErrorCode { return .EPIPE } /// math software. /// Numerical argument out of domain. public static var EDOM: POSIXErrorCode { return .EDOM } /// Result too large. public static var ERANGE: POSIXErrorCode { return .ERANGE } /// non-blocking and interrupt i/o. /// Resource temporarily unavailable. public static var EAGAIN: POSIXErrorCode { return .EAGAIN } /// Operation would block. public static var EWOULDBLOCK: POSIXErrorCode { return .EWOULDBLOCK } /// Operation now in progress. public static var EINPROGRESS: POSIXErrorCode { return .EINPROGRESS } /// Operation already in progress. public static var EALREADY: POSIXErrorCode { return .EALREADY } /// ipc/network software -- argument errors. /// Socket operation on non-socket. public static var ENOTSOCK: POSIXErrorCode { return .ENOTSOCK } /// Destination address required. public static var EDESTADDRREQ: POSIXErrorCode { return .EDESTADDRREQ } /// Message too long. public static var EMSGSIZE: POSIXErrorCode { return .EMSGSIZE } /// Protocol wrong type for socket. public static var EPROTOTYPE: POSIXErrorCode { return .EPROTOTYPE } /// Protocol not available. public static var ENOPROTOOPT: POSIXErrorCode { return .ENOPROTOOPT } /// Protocol not supported. public static var EPROTONOSUPPORT: POSIXErrorCode { return .EPROTONOSUPPORT } /// Socket type not supported. public static var ESOCKTNOSUPPORT: POSIXErrorCode { return .ESOCKTNOSUPPORT } /// Operation not supported. public static var ENOTSUP: POSIXErrorCode { return .ENOTSUP } /// Protocol family not supported. public static var EPFNOSUPPORT: POSIXErrorCode { return .EPFNOSUPPORT } /// Address family not supported by protocol family. public static var EAFNOSUPPORT: POSIXErrorCode { return .EAFNOSUPPORT } /// Address already in use. public static var EADDRINUSE: POSIXErrorCode { return .EADDRINUSE } /// Can't assign requested address. public static var EADDRNOTAVAIL: POSIXErrorCode { return .EADDRNOTAVAIL } /// ipc/network software -- operational errors /// Network is down. public static var ENETDOWN: POSIXErrorCode { return .ENETDOWN } /// Network is unreachable. public static var ENETUNREACH: POSIXErrorCode { return .ENETUNREACH } /// Network dropped connection on reset. public static var ENETRESET: POSIXErrorCode { return .ENETRESET } /// Software caused connection abort. public static var ECONNABORTED: POSIXErrorCode { return .ECONNABORTED } /// Connection reset by peer. public static var ECONNRESET: POSIXErrorCode { return .ECONNRESET } /// No buffer space available. public static var ENOBUFS: POSIXErrorCode { return .ENOBUFS } /// Socket is already connected. public static var EISCONN: POSIXErrorCode { return .EISCONN } /// Socket is not connected. public static var ENOTCONN: POSIXErrorCode { return .ENOTCONN } /// Can't send after socket shutdown. public static var ESHUTDOWN: POSIXErrorCode { return .ESHUTDOWN } /// Too many references: can't splice. public static var ETOOMANYREFS: POSIXErrorCode { return .ETOOMANYREFS } /// Operation timed out. public static var ETIMEDOUT: POSIXErrorCode { return .ETIMEDOUT } /// Connection refused. public static var ECONNREFUSED: POSIXErrorCode { return .ECONNREFUSED } /// Too many levels of symbolic links. public static var ELOOP: POSIXErrorCode { return .ELOOP } /// File name too long. public static var ENAMETOOLONG: POSIXErrorCode { return .ENAMETOOLONG } /// Host is down. public static var EHOSTDOWN: POSIXErrorCode { return .EHOSTDOWN } /// No route to host. public static var EHOSTUNREACH: POSIXErrorCode { return .EHOSTUNREACH } /// Directory not empty. public static var ENOTEMPTY: POSIXErrorCode { return .ENOTEMPTY } /// quotas & mush. /// Too many processes. public static var EPROCLIM: POSIXErrorCode { return .EPROCLIM } /// Too many users. public static var EUSERS: POSIXErrorCode { return .EUSERS } /// Disc quota exceeded. public static var EDQUOT: POSIXErrorCode { return .EDQUOT } /// Network File System. /// Stale NFS file handle. public static var ESTALE: POSIXErrorCode { return .ESTALE } /// Too many levels of remote in path. public static var EREMOTE: POSIXErrorCode { return .EREMOTE } /// RPC struct is bad. public static var EBADRPC: POSIXErrorCode { return .EBADRPC } /// RPC version wrong. public static var ERPCMISMATCH: POSIXErrorCode { return .ERPCMISMATCH } /// RPC prog. not avail. public static var EPROGUNAVAIL: POSIXErrorCode { return .EPROGUNAVAIL } /// Program version wrong. public static var EPROGMISMATCH: POSIXErrorCode { return .EPROGMISMATCH } /// Bad procedure for program. public static var EPROCUNAVAIL: POSIXErrorCode { return .EPROCUNAVAIL } /// No locks available. public static var ENOLCK: POSIXErrorCode { return .ENOLCK } /// Function not implemented. public static var ENOSYS: POSIXErrorCode { return .ENOSYS } /// Inappropriate file type or format. public static var EFTYPE: POSIXErrorCode { return .EFTYPE } /// Authentication error. public static var EAUTH: POSIXErrorCode { return .EAUTH } /// Need authenticator. public static var ENEEDAUTH: POSIXErrorCode { return .ENEEDAUTH } /// Intelligent device errors. /// Device power is off. public static var EPWROFF: POSIXErrorCode { return .EPWROFF } /// Device error, e.g. paper out. public static var EDEVERR: POSIXErrorCode { return .EDEVERR } /// Value too large to be stored in data type. public static var EOVERFLOW: POSIXErrorCode { return .EOVERFLOW } /// Program loading errors. /// Bad executable. public static var EBADEXEC: POSIXErrorCode { return .EBADEXEC } /// Bad CPU type in executable. public static var EBADARCH: POSIXErrorCode { return .EBADARCH } /// Shared library version mismatch. public static var ESHLIBVERS: POSIXErrorCode { return .ESHLIBVERS } /// Malformed Macho file. public static var EBADMACHO: POSIXErrorCode { return .EBADMACHO } /// Operation canceled. public static var ECANCELED: POSIXErrorCode { return .ECANCELED } /// Identifier removed. public static var EIDRM: POSIXErrorCode { return .EIDRM } /// No message of desired type. public static var ENOMSG: POSIXErrorCode { return .ENOMSG } /// Illegal byte sequence. public static var EILSEQ: POSIXErrorCode { return .EILSEQ } /// Attribute not found. public static var ENOATTR: POSIXErrorCode { return .ENOATTR } /// Bad message. public static var EBADMSG: POSIXErrorCode { return .EBADMSG } /// Reserved. public static var EMULTIHOP: POSIXErrorCode { return .EMULTIHOP } /// No message available on STREAM. public static var ENODATA: POSIXErrorCode { return .ENODATA } /// Reserved. public static var ENOLINK: POSIXErrorCode { return .ENOLINK } /// No STREAM resources. public static var ENOSR: POSIXErrorCode { return .ENOSR } /// Not a STREAM. public static var ENOSTR: POSIXErrorCode { return .ENOSTR } /// Protocol error. public static var EPROTO: POSIXErrorCode { return .EPROTO } /// STREAM ioctl timeout. public static var ETIME: POSIXErrorCode { return .ETIME } /// No such policy registered. public static var ENOPOLICY: POSIXErrorCode { return .ENOPOLICY } /// State not recoverable. public static var ENOTRECOVERABLE: POSIXErrorCode { return .ENOTRECOVERABLE } /// Previous owner died. public static var EOWNERDEAD: POSIXErrorCode { return .EOWNERDEAD } /// Interface output queue is full. public static var EQFULL: POSIXErrorCode { return .EQFULL } } /// Describes an error in the Mach error domain. public struct MachError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSMachErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSMachErrorDomain } public typealias Code = MachErrorCode } extension MachErrorCode : _ErrorCodeProtocol { public typealias _ErrorType = MachError } extension MachError { public static var success: MachError.Code { return .success } /// Specified address is not currently valid. public static var invalidAddress: MachError.Code { return .invalidAddress } /// Specified memory is valid, but does not permit the required /// forms of access. public static var protectionFailure: MachError.Code { return .protectionFailure } /// The address range specified is already in use, or no address /// range of the size specified could be found. public static var noSpace: MachError.Code { return .noSpace } /// The function requested was not applicable to this type of /// argument, or an argument is invalid. public static var invalidArgument: MachError.Code { return .invalidArgument } /// The function could not be performed. A catch-all. public static var failure: MachError.Code { return .failure } /// A system resource could not be allocated to fulfill this /// request. This failure may not be permanent. public static var resourceShortage: MachError.Code { return .resourceShortage } /// The task in question does not hold receive rights for the port /// argument. public static var notReceiver: MachError.Code { return .notReceiver } /// Bogus access restriction. public static var noAccess: MachError.Code { return .noAccess } /// During a page fault, the target address refers to a memory /// object that has been destroyed. This failure is permanent. public static var memoryFailure: MachError.Code { return .memoryFailure } /// During a page fault, the memory object indicated that the data /// could not be returned. This failure may be temporary; future /// attempts to access this same data may succeed, as defined by the /// memory object. public static var memoryError: MachError.Code { return .memoryError } /// The receive right is already a member of the portset. public static var alreadyInSet: MachError.Code { return .alreadyInSet } /// The receive right is not a member of a port set. public static var notInSet: MachError.Code { return .notInSet } /// The name already denotes a right in the task. public static var nameExists: MachError.Code { return .nameExists } /// The operation was aborted. Ipc code will catch this and reflect /// it as a message error. public static var aborted: MachError.Code { return .aborted } /// The name doesn't denote a right in the task. public static var invalidName: MachError.Code { return .invalidName } /// Target task isn't an active task. public static var invalidTask: MachError.Code { return .invalidTask } /// The name denotes a right, but not an appropriate right. public static var invalidRight: MachError.Code { return .invalidRight } /// A blatant range error. public static var invalidValue: MachError.Code { return .invalidValue } /// Operation would overflow limit on user-references. public static var userReferencesOverflow: MachError.Code { return .userReferencesOverflow } /// The supplied (port) capability is improper. public static var invalidCapability: MachError.Code { return .invalidCapability } /// The task already has send or receive rights for the port under /// another name. public static var rightExists: MachError.Code { return .rightExists } /// Target host isn't actually a host. public static var invalidHost: MachError.Code { return .invalidHost } /// An attempt was made to supply "precious" data for memory that is /// already present in a memory object. public static var memoryPresent: MachError.Code { return .memoryPresent } /// A page was requested of a memory manager via /// memory_object_data_request for an object using a /// MEMORY_OBJECT_COPY_CALL strategy, with the VM_PROT_WANTS_COPY /// flag being used to specify that the page desired is for a copy /// of the object, and the memory manager has detected the page was /// pushed into a copy of the object while the kernel was walking /// the shadow chain from the copy to the object. This error code is /// delivered via memory_object_data_error and is handled by the /// kernel (it forces the kernel to restart the fault). It will not /// be seen by users. public static var memoryDataMoved: MachError.Code { return .memoryDataMoved } /// A strategic copy was attempted of an object upon which a quicker /// copy is now possible. The caller should retry the copy using /// vm_object_copy_quickly. This error code is seen only by the /// kernel. public static var memoryRestartCopy: MachError.Code { return .memoryRestartCopy } /// An argument applied to assert processor set privilege was not a /// processor set control port. public static var invalidProcessorSet: MachError.Code { return .invalidProcessorSet } /// The specified scheduling attributes exceed the thread's limits. public static var policyLimit: MachError.Code { return .policyLimit } /// The specified scheduling policy is not currently enabled for the /// processor set. public static var invalidPolicy: MachError.Code { return .invalidPolicy } /// The external memory manager failed to initialize the memory object. public static var invalidObject: MachError.Code { return .invalidObject } /// A thread is attempting to wait for an event for which there is /// already a waiting thread. public static var alreadyWaiting: MachError.Code { return .alreadyWaiting } /// An attempt was made to destroy the default processor set. public static var defaultSet: MachError.Code { return .defaultSet } /// An attempt was made to fetch an exception port that is /// protected, or to abort a thread while processing a protected /// exception. public static var exceptionProtected: MachError.Code { return .exceptionProtected } /// A ledger was required but not supplied. public static var invalidLedger: MachError.Code { return .invalidLedger } /// The port was not a memory cache control port. public static var invalidMemoryControl: MachError.Code { return .invalidMemoryControl } /// An argument supplied to assert security privilege was not a host /// security port. public static var invalidSecurity: MachError.Code { return .invalidSecurity } /// thread_depress_abort was called on a thread which was not /// currently depressed. public static var notDepressed: MachError.Code { return .notDepressed } /// Object has been terminated and is no longer available. public static var terminated: MachError.Code { return .terminated } /// Lock set has been destroyed and is no longer available. public static var lockSetDestroyed: MachError.Code { return .lockSetDestroyed } /// The thread holding the lock terminated before releasing the lock. public static var lockUnstable: MachError.Code { return .lockUnstable } /// The lock is already owned by another thread. public static var lockOwned: MachError.Code { return .lockOwned } /// The lock is already owned by the calling thread. public static var lockOwnedSelf: MachError.Code { return .lockOwnedSelf } /// Semaphore has been destroyed and is no longer available. public static var semaphoreDestroyed: MachError.Code { return .semaphoreDestroyed } /// Return from RPC indicating the target server was terminated /// before it successfully replied. public static var rpcServerTerminated: MachError.Code { return .rpcServerTerminated } /// Terminate an orphaned activation. public static var rpcTerminateOrphan: MachError.Code { return .rpcTerminateOrphan } /// Allow an orphaned activation to continue executing. public static var rpcContinueOrphan: MachError.Code { return .rpcContinueOrphan } /// Empty thread activation (No thread linked to it). public static var notSupported: MachError.Code { return .notSupported } /// Remote node down or inaccessible. public static var nodeDown: MachError.Code { return .nodeDown } /// A signalled thread was not actually waiting. public static var notWaiting: MachError.Code { return .notWaiting } /// Some thread-oriented operation (semaphore_wait) timed out. public static var operationTimedOut: MachError.Code { return .operationTimedOut } /// During a page fault, indicates that the page was rejected as a /// result of a signature check. public static var codesignError: MachError.Code { return .codesignError } /// The requested property cannot be changed at this time. public static var policyStatic: MachError.Code { return .policyStatic } } public struct ErrorUserInfoKey : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable, _ObjectiveCBridgeable { public init(rawValue: String) { self.rawValue = rawValue } public var rawValue: String } public extension ErrorUserInfoKey { @available(*, deprecated, renamed: "NSUnderlyingErrorKey") static let underlyingErrorKey = ErrorUserInfoKey(rawValue: NSUnderlyingErrorKey) @available(*, deprecated, renamed: "NSLocalizedDescriptionKey") static let localizedDescriptionKey = ErrorUserInfoKey(rawValue: NSLocalizedDescriptionKey) @available(*, deprecated, renamed: "NSLocalizedFailureReasonErrorKey") static let localizedFailureReasonErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedFailureReasonErrorKey) @available(*, deprecated, renamed: "NSLocalizedRecoverySuggestionErrorKey") static let localizedRecoverySuggestionErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoverySuggestionErrorKey) @available(*, deprecated, renamed: "NSLocalizedRecoveryOptionsErrorKey") static let localizedRecoveryOptionsErrorKey = ErrorUserInfoKey(rawValue: NSLocalizedRecoveryOptionsErrorKey) @available(*, deprecated, renamed: "NSRecoveryAttempterErrorKey") static let recoveryAttempterErrorKey = ErrorUserInfoKey(rawValue: NSRecoveryAttempterErrorKey) @available(*, deprecated, renamed: "NSHelpAnchorErrorKey") static let helpAnchorErrorKey = ErrorUserInfoKey(rawValue: NSHelpAnchorErrorKey) @available(*, deprecated, renamed: "NSStringEncodingErrorKey") static let stringEncodingErrorKey = ErrorUserInfoKey(rawValue: NSStringEncodingErrorKey) @available(*, deprecated, renamed: "NSURLErrorKey") static let NSURLErrorKey = ErrorUserInfoKey(rawValue: Foundation.NSURLErrorKey) @available(*, deprecated, renamed: "NSFilePathErrorKey") static let filePathErrorKey = ErrorUserInfoKey(rawValue: NSFilePathErrorKey) }
32.793301
119
0.732961
462fd6318a2100efab80e4cc6219c35cb5971007
5,947
// RUN: echo -n "%S/Inputs/" > %t.rsp // RUN: cat "%S/Inputs/unicode.txt" >> %t.rsp // RUN: %swiftc_driver_plain -emit-executable @%t.rsp -o %t.out -emit-module -emit-module-path %t.swiftmodule -emit-objc-header-path %t.h -serialize-diagnostics -emit-dependencies -parseable-output -driver-skip-execution 2>&1 | %FileCheck %s // XFAIL: OS=freebsd, OS=openbsd, OS=linux-gnu // CHECK: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "began", // CHECK-NEXT: "name": "compile", // CHECK-NEXT: "command": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}} -frontend -c -primary-file {{.*[\\/]}}你好.swift{{(\\")? .*}} -o {{.*[\\/]}}你好-[[OUTPUT:.*]].o{{(\\")?}}", // CHECK-NEXT: "command_executable": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}}", // CHECK-NEXT: "command_arguments": [ // CHECK-NEXT: "-frontend", // CHECK-NEXT: "-c", // CHECK-NEXT: "-primary-file", // CHECK-NEXT: "{{.*[\\/]}}你好.swift", // CHECK: "-o", // CHECK-NEXT: "{{.*[\\/]}}你好-[[OUTPUT:.*]].o" // CHECK-NEXT: ], // CHECK-NEXT: "inputs": [ // CHECK-NEXT: "{{.*[\\/]}}你好.swift" // CHECK-NEXT: ], // CHECK-NEXT: "outputs": [ // CHECK-NEXT: { // CHECK-NEXT: "type": "object", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].o" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "dependencies", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].d" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftmodule", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].swiftmodule" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftdoc", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].swiftdoc" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftsourceinfo", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].swiftsourceinfo" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "diagnostics", // CHECK-NEXT: "path": "{{.*[\\/]}}你好-[[OUTPUT]].dia" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "pid": 1, // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 1 // CHECK-NEXT: } // CHECK-NEXT: } // CHECK-NEXT: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "finished", // CHECK-NEXT: "name": "compile", // CHECK-NEXT: "pid": 1, // CHECK-NEXT: "output": "Output placeholder\n", // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 1 // CHECK-NEXT: }, // CHECK-NEXT: "exit-status": 0 // CHECK-NEXT: } // CHECK-NEXT: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "began", // CHECK-NEXT: "name": "merge-module", // CHECK-NEXT: "command": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}} -frontend -merge-modules -emit-module {{.*[\\/]}}你好-[[OUTPUT]].swiftmodule{{(\\")?}} {{.*}} -o {{.*[\\/]}}parseable_output_unicode.swift.tmp.swiftmodule{{(\\")?}}", // CHECK-NEXT: "command_executable": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}}", // CHECK-NEXT: "command_arguments": [ // CHECK-NEXT: "-frontend", // CHECK-NEXT: "-merge-modules", // CHECK-NEXT: "-emit-module", // CHECK-NEXT: "{{.*[\\/]}}你好-[[OUTPUT]].swiftmodule", // CHECK: "-o", // CHECK-NEXT: "{{.*[\\/]}}parseable_output_unicode.swift.tmp.swiftmodule" // CHECK-NEXT: ], // CHECK-NEXT: "inputs": [ // CHECK-NEXT: "{{.*[\\/]}}你好-[[OUTPUT]].o" // CHECK-NEXT: ], // CHECK-NEXT: "outputs": [ // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftmodule", // CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output_unicode.swift.tmp.swiftmodule" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftdoc", // CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output_unicode.swift.tmp.swiftdoc" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "swiftsourceinfo", // CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output_unicode.swift.tmp.swiftsourceinfo" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "type": "clang-header", // CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output_unicode.swift.tmp.h" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "pid": 2, // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 2 // CHECK-NEXT: } // CHECK-NEXT: } // CHECK-NEXT: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "finished", // CHECK-NEXT: "name": "merge-module", // CHECK-NEXT: "pid": 2, // CHECK-NEXT: "output": "Output placeholder\n", // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 2 // CHECK-NEXT: }, // CHECK-NEXT: "exit-status": 0 // CHECK-NEXT: } // CHECK-NEXT: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "began", // CHECK-NEXT: "name": "link", // CHECK-NEXT: "command": "{{.*[\\/](ld|clang.exe)(\\")?}} {{.*[\\/]}}你好-[[OUTPUT]].o{{(\\")?}}{{.*}}-o {{.*[\\/]}}parseable_output_unicode.swift.tmp.out{{(\\")?}}", // CHECK-NEXT: "command_executable": "{{.*[\\/](ld|clang.exe)(\\")?}}", // CHECK-NEXT: "command_arguments": [ // CHECK: "{{.*[\\/]}}你好-[[OUTPUT]].o", // CHECK: "-o", // CHECK-NEXT: "{{.*[\\/]}}parseable_output_unicode.swift.tmp.out" // CHECK-NEXT: ], // CHECK-NEXT: "inputs": [ // CHECK-NEXT: "{{.*[\\/]}}你好-[[OUTPUT]].o" // CHECK-NEXT: ], // CHECK-NEXT: "outputs": [ // CHECK-NEXT: { // CHECK-NEXT: "type": "image", // CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output_unicode.swift.tmp.out" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "pid": 3, // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 3 // CHECK-NEXT: } // CHECK-NEXT: } // CHECK-NEXT: {{[1-9][0-9]*}} // CHECK-NEXT: { // CHECK-NEXT: "kind": "finished", // CHECK-NEXT: "name": "link", // CHECK-NEXT: "pid": 3, // CHECK-NEXT: "output": "Output placeholder\n", // CHECK-NEXT: "process": { // CHECK-NEXT: "real_pid": 3 // CHECK-NEXT: }, // CHECK-NEXT: "exit-status": 0 // CHECK-NEXT: }
37.639241
242
0.512864
1c29d8b62b293f6659ff7bd1aae9f9b4e87a1e5d
24,317
// // PieChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class PieChartRenderer: ChartDataRendererBase { public weak var chart: PieChartView? public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } public override func drawData(context context: CGContext) { guard let chart = chart else { return } let pieData = chart.data if (pieData != nil) { for set in pieData!.dataSets as! [IPieChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } } public func calculateMinimumRadiusForSpacedSlice( center center: CGPoint, radius: CGFloat, angle: CGFloat, arcStartPointX: CGFloat, arcStartPointY: CGFloat, startAngle: CGFloat, sweepAngle: CGFloat) -> CGFloat { let angleMiddle = startAngle + sweepAngle / 2.0 // Other point of the arc let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) // Middle point on the arc let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) // Middle point on straight line between the two point. // This is the base of the contained triangle let basePointsDistance = sqrt( pow(arcEndPointX - arcStartPointX, 2) + pow(arcEndPointY - arcStartPointY, 2)) // After reducing space from both sides of the "slice", // the angle of the contained triangle should stay the same. // So let's find out the height of that triangle. let containedTriangleHeight = (basePointsDistance / 2.0 * tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD)) // Now we subtract that from the radius var spacedRadius = radius - containedTriangleHeight // And now subtract the height of the arc that's between the triangle and the outer circle spacedRadius -= sqrt( pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) + pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2)) return spacedRadius } public func drawDataSet(context context: CGContext, dataSet: IPieChartDataSet) { guard let chart = chart, data = chart.data, animator = animator else {return } var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle let phaseX = animator.phaseX let phaseY = animator.phaseY let entryCount = dataSet.entryCount var drawAngles = chart.drawAngles let sliceSpace = dataSet.sliceSpace let center = chart.centerCircleBox let radius = chart.radius let userInnerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? radius * chart.holeRadiusPercent : 0.0 var visibleAngleCount = 0 for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount++; } } CGContextSaveGState(context) for (var j = 0; j < entryCount; j++) { let sliceAngle = drawAngles[j] var innerRadius = userInnerRadius guard let e = dataSet.entryForIndex(j) else { continue } // draw only if the value is greater than zero if ((abs(e.value) > 0.000001)) { if (!chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: data.indexOfDataSet(dataSet))) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let sliceSpaceOuterAngle = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let startAngleOuter = rotationAngle + (angle + sliceSpaceOuterAngle / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceOuterAngle) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD) let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD) let path = CGPathCreateMutable() CGPathMoveToPoint( path, nil, arcStartPointX, arcStartPointY) CGPathAddRelativeArc( path, nil, center.x, center.y, radius, startAngleOuter * ChartUtils.Math.FDEG2RAD, sweepAngleOuter * ChartUtils.Math.FDEG2RAD) if sliceSpace > 0.0 { innerRadius = max(innerRadius, calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter)) } if (innerRadius > 0.0) { let sliceSpaceInnerAngle = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceInnerAngle / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceInnerAngle) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner CGPathAddLineToPoint( path, nil, center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, innerRadius, endAngleInner * ChartUtils.Math.FDEG2RAD, -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { CGPathAddLineToPoint( path, nil, center.x, center.y) } CGPathCloseSubpath(path) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextEOFillPath(context) } } angle += sliceAngle * phaseX } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let chart = chart, data = chart.data, animator = animator else { return } let center = chart.centerCircleBox // get whole the radius var r = chart.radius let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let phaseX = animator.phaseX let phaseY = animator.phaseY var off = r / 10.0 * 3.0 if chart.drawHoleEnabled { off = (r - (r * chart.holeRadiusPercent)) / 2.0 } r -= off; // offset to keep things inside the chart var dataSets = data.dataSets let yValueSum = (data as! PieChartData).yValueSum let drawXVals = chart.isDrawSliceTextEnabled let usePercentValuesEnabled = chart.usePercentValuesEnabled var angle: CGFloat = 0.0 var xIndex = 0 for (var i = 0; i < dataSets.count; i++) { guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue } let drawYVals = dataSet.isDrawValuesEnabled if (!drawYVals && !drawXVals) { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } for (var j = 0, entryCount = dataSet.entryCount; j < entryCount; j++) { if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil)) { continue } guard let e = dataSet.entryForIndex(j) else { continue } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceAngle = drawAngles[xIndex] let sliceSpace = dataSet.sliceSpace let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * r) // offset needed to center the drawn text in the slice let offset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0 angle = angle + offset // calculate the text position let x = r * cos((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD) + center.x var y = r * sin((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD) + center.y let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value let val = formatter.stringFromNumber(value)! let lineHeight = valueFont.lineHeight y -= lineHeight // draw everything, depending on settings if (drawXVals && drawYVals) { ChartUtils.drawText( context: context, text: val, point: CGPoint(x: x, y: y), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) if (j < data.xValCount && data.xVals[j] != nil) { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } else if (drawXVals) { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } else if (drawYVals) { ChartUtils.drawText( context: context, text: val, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } xIndex++ } } } public override func drawExtras(context context: CGContext) { drawHole(context: context) drawCenterText(context: context) } /// draws the hole in the center of the chart and the transparent circle / hole private func drawHole(context context: CGContext) { guard let chart = chart, animator = animator else { return } if (chart.drawHoleEnabled) { CGContextSaveGState(context) let radius = chart.radius let holeRadius = radius * chart.holeRadiusPercent let center = chart.centerCircleBox if let holeColor = chart.holeColor { if holeColor != NSUIColor.clearColor() { // draw the hole-circle CGContextSetFillColorWithColor(context, chart.holeColor!.CGColor) CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) } } // only draw the circle if it can be seen (not covered by the hole) if let transparentCircleColor = chart.transparentCircleColor { if transparentCircleColor != NSUIColor.clearColor() && chart.transparentCircleRadiusPercent > chart.holeRadiusPercent { let alpha = animator.phaseX * animator.phaseY let secondHoleRadius = radius * chart.transparentCircleRadiusPercent // make transparent CGContextSetAlpha(context, alpha); CGContextSetFillColorWithColor(context, transparentCircleColor.CGColor) // draw the transparent-circle CGContextBeginPath(context) CGContextAddEllipseInRect(context, CGRect( x: center.x - secondHoleRadius, y: center.y - secondHoleRadius, width: secondHoleRadius * 2.0, height: secondHoleRadius * 2.0)) CGContextAddEllipseInRect(context, CGRect( x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) CGContextEOFillPath(context) } } CGContextRestoreGState(context) } } /// draws the description text in the center of the pie chart makes most sense when center-hole is enabled private func drawCenterText(context context: CGContext) { guard let chart = chart, centerAttributedText = chart.centerAttributedText else { return } if chart.drawCenterTextEnabled && centerAttributedText.length > 0 { let center = chart.centerCircleBox let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0) var boundingRect = holeRect if (chart.centerTextRadiusPercent > 0.0) { boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0) } let textBounds = centerAttributedText.boundingRectWithSize(boundingRect.size, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil) var drawingRect = boundingRect drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0 drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0 drawingRect.size = textBounds.size CGContextSaveGState(context) let clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil) CGContextBeginPath(context) CGContextAddPath(context, clippingPath) CGContextClip(context) centerAttributedText.drawWithRect(drawingRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil) CGContextRestoreGState(context) } } public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let chart = chart, data = chart.data, animator = animator else { return } CGContextSaveGState(context) let phaseX = animator.phaseX let phaseY = animator.phaseY var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let center = chart.centerCircleBox let radius = chart.radius let userInnerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? radius * chart.holeRadiusPercent : 0.0 for (var i = 0; i < indices.count; i++) { // get the index to highlight let xIndex = indices[i].xIndex if (xIndex >= drawAngles.count) { continue } guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue } if !set.isHighlightEnabled { continue } let entryCount = set.entryCount var visibleAngleCount = 0 for (var j = 0; j < entryCount; j++) { guard let e = set.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount++; } } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceSpace = set.sliceSpace let sliceAngle = drawAngles[xIndex] let sliceSpaceOuterAngle = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) var innerRadius = userInnerRadius let shift = set.selectionShift let highlightedRadius = radius + shift CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor) let startAngleOuter = rotationAngle + (angle + sliceSpaceOuterAngle / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceOuterAngle) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let path = CGPathCreateMutable() CGPathMoveToPoint( path, nil, center.x + highlightedRadius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD), center.y + highlightedRadius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, highlightedRadius, startAngleOuter * ChartUtils.Math.FDEG2RAD, sweepAngleOuter * ChartUtils.Math.FDEG2RAD) if sliceSpace > 0.0 { innerRadius = max(innerRadius, calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD), arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD), startAngle: startAngleOuter, sweepAngle: sweepAngleOuter)) } if (innerRadius > 0.0) { let sliceSpaceInnerAngle = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceInnerAngle / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceInnerAngle) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner CGPathAddLineToPoint( path, nil, center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD)) CGPathAddRelativeArc( path, nil, center.x, center.y, innerRadius, endAngleInner * ChartUtils.Math.FDEG2RAD, -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { CGPathAddLineToPoint( path, nil, center.x, center.y) } CGPathCloseSubpath(path) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextEOFillPath(context) } CGContextRestoreGState(context) } }
38.35489
220
0.493359
398487107f108394e3bef7c2a6ad2fbac0913b2e
32,976
// // MMUtils.swift // MobileMessaging // // Created by Andrey K. on 17/02/16. // // import Foundation import CoreData import CoreLocation import SystemConfiguration import UserNotifications public typealias DictionaryRepresentation = [String: Any] func arrayToSet<T>(arr: [T]?) -> Set<T>? { return arr != nil ? Set<T>(arr!) : nil } func deltaDict(_ current: [String: Any], _ dirty: [String: Any]) -> [String: Any]? { var ret:[String: Any] = [:] dirty.keys.forEach { (k) in let currentV = current[k] as Any let dirtyV = dirty[k] as Any if checkIfAnyIsNil(dirtyV) { if checkIfAnyIsNil(currentV) { } else { ret[k] = NSNull() } } else { if (currentV is [String : Any] && dirtyV is [String : Any]) { let currentDict = currentV as! [String : Any] let dirtyDict = dirtyV as! [String : Any] if currentDict.isEmpty && dirtyDict.isEmpty { ret[k] = nil } else { ret[k] = deltaDict(currentDict, dirtyDict) } } else { if currentV is AnyHashable && dirtyV is AnyHashable { if (currentV as! AnyHashable) != (dirtyV as! AnyHashable){ ret[k] = dirtyV } } else { if (checkIfAnyIsNil(currentV)) { ret[k] = dirtyV } else { ret[k] = NSNull() } } } } } return ret.isEmpty ? (!current.isEmpty && !dirty.isEmpty ? nil : ret) : ret } func isOptional(_ instance: Any) -> Bool { let mirror = Mirror(reflecting: instance) let style = mirror.displayStyle return style == .optional } func checkIfAnyIsNil(_ v: Any) -> Bool { if (isOptional(v)) { switch v { case Optional<Any>.none: return true case Optional<Any>.some(let v): return checkIfAnyIsNil(v) default: return false } } else { return false } } extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any { var noNulls: [Key: Value] { return self.filter { let val = $0.1 as Any if case Optional<Any>.none = val { return false } else { return true } } } } extension MobileMessaging { class var currentInstallation: MMInstallation? { return MobileMessaging.getInstallation() } class var currentUser: MMUser? { return MobileMessaging.getUser() } } func contactsServiceDateEqual(_ l: Date?, _ r: Date?) -> Bool { switch (l, r) { case (.none, .none): return true case (.some, .none): return false case (.none, .some): return false case (.some(let left), .some(let right)): return DateStaticFormatters.ContactsServiceDateFormatter.string(from: left) == DateStaticFormatters.ContactsServiceDateFormatter.string(from: right) } } struct DateStaticFormatters { /** Desired format is GMT+03:00 and a special case for Greenwich Mean Time: GMT+00:00 */ static var CurrentJavaCompatibleTimeZoneOffset: String { var gmt = DateStaticFormatters.TimeZoneOffsetFormatter.string(from: MobileMessaging.date.now) if gmt == "GMT" { gmt = gmt + "+00:00" } return gmt } /** Desired format is GMT+03:00, not GMT+3 */ static var TimeZoneOffsetFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "ZZZZ" dateFormatter.timeZone = MobileMessaging.timeZone return dateFormatter }() static var LoggerDateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:SSS" return dateFormatter }() static var ContactsServiceDateFormatter: DateFormatter = { let result = DateFormatter() result.locale = Locale(identifier: "en_US_POSIX") result.dateFormat = "yyyy-MM-dd" result.timeZone = TimeZone(secondsFromGMT: 0) return result }() static var ISO8601SecondsFormatter: DateFormatter = { let result = DateFormatter() result.locale = Locale(identifier: "en_US_POSIX") result.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" result.timeZone = TimeZone(secondsFromGMT: 0) return result }() static var CoreDataDateFormatter: DateFormatter = { let result = DateFormatter() result.locale = Locale(identifier: "en_US_POSIX") result.dateFormat = "yyyy-MM-dd HH:mm:ss Z" return result }() static var timeFormatter: DateFormatter = { let result = DateFormatter() result.dateStyle = DateFormatter.Style.none result.timeStyle = DateFormatter.Style.short return result }() } extension Dictionary where Key: ExpressibleByStringLiteral, Value: Hashable { var valuesStableHash: Int { return self.sorted { (kv1, kv2) -> Bool in if let key1 = kv1.key as? String, let key2 = kv2.key as? String { return key1.compare(key2) == .orderedAscending } else { return false } }.reduce("", {"\($0),\($1.1)"}).stableHash } } extension String { var stableHash: Int { let unicodeScalars = self.unicodeScalars.map { $0.value } return unicodeScalars.reduce(5381) { ($0 << 5) &+ $0 &+ Int($1) } } } extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any { var nilIfEmpty: [Key: Value]? { return self.isEmpty ? nil : self } } extension Collection { var nilIfEmpty: Self? { return self.isEmpty ? nil : self } } extension Data { var mm_toHexString: String { return reduce("") {$0 + String(format: "%02x", $1)} } } extension String { var safeUrl: URL? { return URL(string: self) } func mm_matches(toRegexPattern: String, options: NSRegularExpression.Options = []) -> Bool { if let regex = try? NSRegularExpression(pattern: toRegexPattern, options: options), let _ = regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSRange(0..<self.count)) { return true } else { return false } } var mm_isSdkGeneratedMessageId: Bool { return mm_isUUID } var mm_isUUID: Bool { return mm_matches(toRegexPattern: Consts.UUIDRegexPattern, options: .caseInsensitive) } func mm_breakWithMaxLength(maxLenght: Int) -> String { var result: String = self let currentLen = self.count let doPutDots = maxLenght > 3 if currentLen > maxLenght { if let index = self.index(self.startIndex, offsetBy: maxLenght - (doPutDots ? 3 : 0), limitedBy: self.endIndex) { result = self[..<index] + (doPutDots ? "..." : "") } } return result } var mm_toHexademicalString: String? { if let data: Data = self.data(using: String.Encoding.utf16) { return data.mm_toHexString } else { return nil } } var mm_fromHexademicalString: String? { if let data = self.mm_dataFromHexadecimalString { return String.init(data: data, encoding: String.Encoding.utf16) } else { return nil } } var mm_dataFromHexadecimalString: Data? { let trimmedString = self.trimmingCharacters(in: CharacterSet.init(charactersIn:"<> ")).replacingOccurrences(of: " ", with: "") // make sure the cleaned up string consists solely of hex digits, and that we have even number of them let regex = try! NSRegularExpression(pattern: "^[0-9a-f]*$", options: .caseInsensitive) let found = regex.firstMatch(in: trimmedString, options: [], range: NSMakeRange(0, trimmedString.count)) if found == nil || found?.range.location == NSNotFound || trimmedString.count % 2 != 0 { return nil } // everything ok, so now let's build NSData var data = Data() var index = trimmedString.startIndex while index < trimmedString.endIndex { let range:Range<Index> = index..<trimmedString.index(index, offsetBy: 2) let byteString = trimmedString[range] let num = UInt8(byteString.withCString { strtoul($0, nil, 16) }) data.append([num] as [UInt8], count: 1) index = trimmedString.index(index, offsetBy: 2) } return data } var mm_urlSafeString: String { let raw: String = self var urlFragmentAllowed = CharacterSet.urlFragmentAllowed urlFragmentAllowed.remove(charactersIn: "!*'();:@&=+$,/?%#[]") var result = String() if let str = raw.addingPercentEncoding(withAllowedCharacters: urlFragmentAllowed) { result = str } return result } } func += <Key, Value> (left: inout Dictionary<Key, Value>, right: Dictionary<Key, Value>?) { guard let right = right else { return } for (k, v) in right { left.updateValue(v, forKey: k) } } func + <Key, Value> (l: Dictionary<Key, Value>?, r: Dictionary<Key, Value>?) -> Dictionary<Key, Value>? { switch (l, r) { case (.none, .none): return nil case (.some(let left), .none): return left case (.none, .some(let right)): return right case (.some(let left), .some(let right)): var lMutable = left for (k, v) in right { lMutable[k] = v } return lMutable } } func + <Key, Value> (l: Dictionary<Key, Value>?, r: Dictionary<Key, Value>) -> Dictionary<Key, Value> { switch (l, r) { case (.none, _): return r case (.some(let left), _): var lMutable = left for (k, v) in r { lMutable[k] = v } return lMutable } } func + <Key, Value> (l: Dictionary<Key, Value>, r: Dictionary<Key, Value>) -> Dictionary<Key, Value> { var lMutable = l for (k, v) in r { lMutable[k] = v } return lMutable } func + <Element: Any>(l: Set<Element>?, r: Set<Element>?) -> Set<Element>? { switch (l, r) { case (.none, .none): return nil case (.some(let left), .none): return left case (.none, .some(let right)): return right case (.some(let left), .some(let right)): return left.union(right) } } func + <Element: Any>(l: [Element]?, r: [Element]?) -> [Element] { switch (l, r) { case (.none, .none): return [Element]() case (.some(let left), .none): return left case (.none, .some(let right)): return right case (.some(let left), .some(let right)): return left + right } } func ==(lhs : [AnyHashable : MMAttributeType], rhs: [AnyHashable : MMAttributeType]) -> Bool { return NSDictionary(dictionary: lhs).isEqual(to: rhs) } func ==(l : [String : MMAttributeType]?, r: [String : MMAttributeType]?) -> Bool { switch (l, r) { case (.none, .none): return true case (.some, .none): return false case (.none, .some): return false case (.some(let left), .some(let right)): return NSDictionary(dictionary: left).isEqual(to: right) } } func !=(lhs : [AnyHashable : MMAttributeType], rhs: [AnyHashable : MMAttributeType]) -> Bool { return !NSDictionary(dictionary: lhs).isEqual(to: rhs) } protocol DictionaryRepresentable { init?(dictRepresentation dict: DictionaryRepresentation) var dictionaryRepresentation: DictionaryRepresentation {get} } extension Date { var timestampDelta: UInt { return UInt(max(0, MobileMessaging.date.now.timeIntervalSinceReferenceDate - self.timeIntervalSinceReferenceDate)) } } var isTestingProcessRunning: Bool { return ProcessInfo.processInfo.arguments.contains("-IsStartedToRunTests") } extension Optional where Wrapped: Any { func ifSome<T>(_ block: (Wrapped) -> T?) -> T? { switch self { case .none: return nil case .some(let wr): return block(wr) } } } public class MobileMessagingService: NSObject, NamedLogger { let mmContext: MobileMessaging let uniqueIdentifier: String var isRunning: Bool init(mmContext: MobileMessaging, uniqueIdentifier: String) { self.isRunning = false self.mmContext = mmContext self.uniqueIdentifier = uniqueIdentifier super.init() self.mmContext.registerSubservice(self) } deinit { stopObserving() } func start(_ completion: @escaping (Bool) -> Void) { logDebug("starting") isRunning = true setupObservers() completion(isRunning) } func stop(_ completion: @escaping (Bool) -> Void) { logDebug("stopping") stopObserving() isRunning = false completion(isRunning) } /// A system data that is related to a particular subservice. For example for Geofencing service it is a key-value pair "geofencing: <bool>" that indicates whether the service is enabled or not var systemData: [String: AnyHashable]? { return nil } /// Called by message handling operation in order to fill the MessageManagedObject data by MobileMessaging subservices. Subservice must be in charge of fulfilling the message data to be stored on disk. You return `true` if message was changed by the method. func populateNewPersistedMessage(_ message: inout MessageManagedObject, originalMessage: MM_MTMessage) -> Bool { return false } func handleNewMessage(_ message: MM_MTMessage, completion: @escaping (MessageHandlingResult) -> Void) { completion(.noData) } func handleAnyMessage(_ message: MM_MTMessage, completion: @escaping (MessageHandlingResult) -> Void) { completion(.noData) } func mobileMessagingWillStart(_ mmContext: MobileMessaging) {} func mobileMessagingDidStart(_ mmContext: MobileMessaging) {} func mobileMessagingWillStop(_ mmContext: MobileMessaging) {} func mobileMessagingDidStop(_ mmContext: MobileMessaging) {} var dispatchQueue: DispatchQueue { return DispatchQueue.global() } func appWillEnterForeground() {} func appDidFinishLaunching(_ notification: Notification) {} func appDidBecomeActive() {} func appWillResignActive() {} func appWillTerminate() {} func appDidEnterBackground() {} @objc func geoServiceDidStart(_ notification: Notification) {} @objc private func appWillEnterForegroundMainThread(_ notification: Notification) { dispatchQueue.async {self.appWillEnterForeground()} } @objc private func appDidBecomeActiveMainThread(_ notification: Notification) { dispatchQueue.async {self.appDidBecomeActive()} } @objc private func appWillResignActiveMainThread(_ notification: Notification) { dispatchQueue.async {self.appWillResignActive()} } @objc private func appWillTerminateMainThread(_ notification: Notification) { dispatchQueue.async {self.appWillTerminate()} } @objc private func appDidEnterBackgroundMainThread(_ notification: Notification) { dispatchQueue.async {self.appDidEnterBackground()} } @objc private func handleAppDidFinishLaunchingNotification(_ n: Notification) { guard n.userInfo?[UIApplication.LaunchOptionsKey.remoteNotification] == nil else { // we don't want to work on launching when push received. return } dispatchQueue.async { self.appDidFinishLaunching(n) } } func syncWithServer(_ completion: @escaping (NSError?) -> Void) {} func pushRegistrationStatusDidChange(_ mmContext: MobileMessaging) {} func depersonalizationStatusDidChange(_ mmContext: MobileMessaging) {} func depersonalizeService(_ mmContext: MobileMessaging, completion: @escaping () -> Void) { completion() } func handlesInAppNotification(forMessage message: MM_MTMessage?) -> Bool { return false } func showBannerNotificationIfNeeded(forMessage message: MM_MTMessage?, showBannerWithOptions: @escaping (UNNotificationPresentationOptions) -> Void) { showBannerWithOptions([]) } private func stopObserving() { NotificationCenter.default.removeObserver(self) } private func setupObservers() { guard !isTestingProcessRunning else { return } NotificationCenter.default.addObserver( self, selector: #selector(appWillResignActiveMainThread(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(appDidBecomeActiveMainThread(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(appWillTerminateMainThread(_:)), name: UIApplication.willTerminateNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(appDidEnterBackgroundMainThread(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(appWillEnterForegroundMainThread(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(handleAppDidFinishLaunchingNotification(_:)), name: UIApplication.didFinishLaunchingNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(geoServiceDidStart(_:)), name: NSNotification.Name(rawValue: MMNotificationGeoServiceDidStart), object: nil) } } public extension UIDevice { func SYSTEM_VERSION_LESS_THAN(_ version: String) -> Bool { return self.systemVersion.compare(version, options: .numeric) == .orderedAscending } @objc var IS_IOS_BEFORE_10: Bool { return SYSTEM_VERSION_LESS_THAN("10.0") } } class MMDate { var now: Date { return Date() } func timeInterval(sinceNow timeInterval: TimeInterval) -> Date { return Date(timeIntervalSinceNow: timeInterval) } func timeInterval(since1970 timeInterval: TimeInterval) -> Date { return Date(timeIntervalSince1970: timeInterval) } func timeInterval(sinceReferenceDate timeInterval: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate: timeInterval) } func timeInterval(_ timeInterval: TimeInterval, since date: Date) -> Date { return Date(timeInterval: timeInterval, since: date) } } protocol UserNotificationCenterStorage { func getDeliveredMessages(completionHandler: @escaping ([MM_MTMessage]) -> Swift.Void) } class DefaultUserNotificationCenterStorage : UserNotificationCenterStorage { func getDeliveredMessages(completionHandler: @escaping ([MM_MTMessage]) -> Swift.Void) { UNUserNotificationCenter.current().getDeliveredNotifications { notifications in let messages = notifications .compactMap({ MM_MTMessage(payload: $0.request.content.userInfo, deliveryMethod: .local, seenDate: nil, deliveryReportDate: nil, seenStatus: .NotSeen, isDeliveryReportSent: false) }) completionHandler(messages) } } } protocol MMApplication { var applicationIconBadgeNumber: Int { get set } var applicationState: UIApplication.State { get } var isRegisteredForRemoteNotifications: Bool { get } func unregisterForRemoteNotifications() func registerForRemoteNotifications() var notificationEnabled: Bool? { get } var visibleViewController: UIViewController? { get } } extension UIApplication: MMApplication { var visibleViewController: UIViewController? { return self.keyWindow?.visibleViewController } } extension MMApplication { var isInForegroundState: Bool { return applicationState == .active } var notificationEnabled: Bool? { var notificationSettings: UNNotificationSettings? let semaphore = DispatchSemaphore(value: 0) DispatchQueue.global().async { UNUserNotificationCenter.current().getNotificationSettings { settings in notificationSettings = settings semaphore.signal() } } return semaphore.wait(timeout: DispatchTime.now() + .seconds(2)) == DispatchTimeoutResult.timedOut ? nil : notificationSettings?.alertSetting == UNNotificationSetting.enabled || notificationSettings?.badgeSetting == UNNotificationSetting.enabled || notificationSettings?.soundSetting == UNNotificationSetting.enabled } } class MainThreadedUIApplication: MMApplication { init() { } var app: UIApplication = UIApplication.shared var applicationIconBadgeNumber: Int { get { return getFromMain(getter: { app.applicationIconBadgeNumber }) } set { inMainWait(block: { app.applicationIconBadgeNumber = newValue }) } } var visibleViewController: UIViewController? { return getFromMain(getter: { app.keyWindow?.visibleViewController }) } var applicationState: UIApplication.State { return getFromMain(getter: { app.applicationState }) } var isRegisteredForRemoteNotifications: Bool { return getFromMain(getter: { app.isRegisteredForRemoteNotifications }) } func unregisterForRemoteNotifications() { inMainWait { app.unregisterForRemoteNotifications() } } func registerForRemoteNotifications() { inMainWait { app.registerForRemoteNotifications() } } } func getDocumentsDirectory(filename: String) -> String { let applicationSupportPaths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true) let basePath = applicationSupportPaths.first ?? NSTemporaryDirectory() return URL(fileURLWithPath: basePath).appendingPathComponent("com.mobile-messaging.\(filename)", isDirectory: false).path } func applicationCodeChanged(newApplicationCode: String) -> Bool { let ci = InternalData.unarchive(from: InternalData.currentPath) if let currentApplicationCode = ci?.applicationCode { return newApplicationCode != currentApplicationCode } else if let currentApplicationCodeHash = ci?.applicationCodeHash { let newApplicationCodeHash = calculateAppCodeHash(newApplicationCode) return newApplicationCodeHash != currentApplicationCodeHash } else { return false } } extension String { static func localizedUserNotificationStringOrFallback(key: String?, args: [String]?, fallback: String?) -> String? { let ret: String? if let key = key { if let args = args { ret = NSString.localizedUserNotificationString(forKey: key, arguments: args) } else { ret = NSLocalizedString(key, comment: "") as String } } else { ret = fallback } return ret } } enum MessageStorageKind: String { case messages = "messages", chat = "chat" } extension UIImage { convenience init?(mm_named: String) { self.init(named: mm_named, in: MobileMessaging.bundle, compatibleWith: nil) } } let isDebug: Bool = { var isDebug = false // function with a side effect and Bool return value that we can pass into assert() func set(debug: Bool) -> Bool { isDebug = debug return isDebug } // assert: // "Condition is only evaluated in playgrounds and -Onone builds." // so isDebug is never changed to false in Release builds assert(set(debug: true)) return isDebug }() func calculateAppCodeHash(_ appCode: String) -> String { return String(appCode.sha1().prefix(10)) } extension Sequence { func forEachAsync(_ work: @escaping (Self.Iterator.Element, @escaping () -> Void) -> Void, completion: @escaping () -> Void) { let loopGroup = DispatchGroup() self.forEach { (el) in loopGroup.enter() work(el, { loopGroup.leave() }) } loopGroup.notify(queue: DispatchQueue.global(qos: .default), execute: { completion() }) } } extension UIColor { class func enabledCellColor() -> UIColor { return UIColor.white } class func disabledCellColor() -> UIColor { return UIColor.TABLEVIEW_GRAY().lighter(2) } func darker(_ percents: CGFloat) -> UIColor { var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) func reduce(_ value: CGFloat) -> CGFloat { let result: CGFloat = max(0, value - value * (percents/100.0)) return result } return UIColor(red: reduce(r) , green: reduce(g), blue: reduce(b), alpha: a) } func lighter(_ percents: CGFloat) -> UIColor { var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) func reduce(_ value: CGFloat) -> CGFloat { let result: CGFloat = min(1, value + value * (percents/100.0)) return result } return UIColor(red: reduce(r) , green: reduce(g), blue: reduce(b), alpha: a) } class func colorMod255(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } class func TEXT_BLACK() -> UIColor { return UIColor.colorMod255(65, 65, 65) } class func TEXT_GRAY() -> UIColor { return UIColor.colorMod255(165, 165, 165) } class func TABBAR_TITLE_BLACK() -> UIColor { return UIColor.colorMod255(90, 90, 90) } class func ACTIVE_TINT() -> UIColor { return UIColor.MAIN() } class func TABLEVIEW_GRAY() -> UIColor { return UIColor.colorMod255(239, 239, 244) } class func MAIN() -> UIColor { #if IO return UIColor.colorMod255(234, 55, 203) #else return UIColor.colorMod255(239, 135, 51) #endif } class func MAIN_MED_DARK() -> UIColor { return UIColor.MAIN().darker(25) } class func MAIN_DARK() -> UIColor { return UIColor.MAIN().darker(50) } class func CHAT_MESSAGE_COLOR(_ isYours: Bool) -> UIColor { if (isYours == true) { return UIColor.colorMod255(253, 242, 229) } else { return UIColor.white } } class func CHAT_MESSAGE_FONT_COLOR(_ isYours: Bool) -> UIColor { if (isYours == true) { return UIColor.colorMod255(73, 158, 90) } else { return UIColor.darkGray } } class func TABLE_SEPARATOR_COLOR() -> UIColor { return UIColor.colorMod255(210, 209, 213) } class func GREEN() -> UIColor { return UIColor.colorMod255(127, 211, 33) } class func RED() -> UIColor { return UIColor.colorMod255(243, 27, 0) } convenience init(hexString: String, alpha: CGFloat = 1.0) { let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) if (hexString.hasPrefix("#")) { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) let mask = 0x000000FF let r = Int(color >> 16) & mask let g = Int(color >> 8) & mask let b = Int(color) & mask let red = CGFloat(r) / 255.0 let green = CGFloat(g) / 255.0 let blue = CGFloat(b) / 255.0 self.init(red:red, green:green, blue:blue, alpha:alpha) } } extension Optional { var orNil : String { if self == nil { return "nil" } if "\(Wrapped.self)" == "String" { return "\"\(self!)\"" } return "\(self!)" } } extension URL { static func attachmentDownloadDestinationFolderUrl(appGroupId: String?) -> URL { let fileManager = FileManager.default let tempFolderUrl: URL if let appGroupId = appGroupId, let appGroupContainerUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: appGroupId) { tempFolderUrl = appGroupContainerUrl.appendingPathComponent("Library/Caches") } else { tempFolderUrl = URL.init(fileURLWithPath: NSTemporaryDirectory()) } var destinationFolderURL = tempFolderUrl.appendingPathComponent("com.mobile-messaging.rich-notifications-attachments", isDirectory: true) var isDir: ObjCBool = true if !fileManager.fileExists(atPath: destinationFolderURL.path, isDirectory: &isDir) { do { try fileManager.createDirectory(at: destinationFolderURL, withIntermediateDirectories: true, attributes: nil) } catch _ { destinationFolderURL = tempFolderUrl } } return destinationFolderURL } static func attachmentDownloadDestinatioUrl(sourceUrl: URL, appGroupId: String?) -> URL { return URL.attachmentDownloadDestinationFolderUrl(appGroupId:appGroupId).appendingPathComponent(sourceUrl.absoluteString.sha1() + "." + sourceUrl.pathExtension) } } extension Bundle { static var mainAppBundle: Bundle { var bundle = Bundle.main if bundle.bundleURL.pathExtension == "appex" { // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex let url = bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent() if let otherBundle = Bundle(url: url) { bundle = otherBundle } } return bundle } var appGroupId: String? { return self.object(forInfoDictionaryKey: "com.mobilemessaging.app_group") as? String } } extension Array where Element: Hashable { var asSet: Set<Element> { return Set(self) } } extension Set { var asArray: Array<Element> { return Array(self) } } class ThreadSafeDict<T> { private var dict: [String: T] = [:] private var queue: DispatchQueue = DispatchQueue.init(label: "", qos: .default, attributes: DispatchQueue.Attributes.concurrent) func set(value: T?, forKey key: String) { queue.async(group: nil, qos: .default, flags: .barrier) { self.dict[key] = value } } func getValue(forKey key: String) -> T? { var ret: T? queue.sync { ret = dict[key] } return ret } func reset() { queue.async { self.dict.removeAll() } } } extension UIWindow { var visibleViewController: UIViewController? { return UIWindow.getVisibleViewControllerFrom(self.rootViewController) } static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? { if let nc = vc as? UINavigationController { return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController) } else if let tc = vc as? UITabBarController { let moreNavigationController = tc.moreNavigationController if let visible = moreNavigationController.visibleViewController , visible.view.window != nil { return UIWindow.getVisibleViewControllerFrom(moreNavigationController) } else { return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController) } } else { if let pvc = vc?.presentedViewController { return UIWindow.getVisibleViewControllerFrom(pvc) } else { return vc } } } }
34.172021
261
0.619936
3a5731974003aa61858a0fb465f3e2c6cdbc7050
13,116
// // Copyright © 2021 Apparata AB. All rights reserved. // import Foundation import libsqlite3 internal typealias SQLStatementID = OpaquePointer @SQLActor public class SQLStatement { private enum StepResult { case done case row(SQLRow) } internal struct Iteration: Equatable { private var iteration: Int = 0 mutating func markNew() { iteration += 1 } } private let id: SQLStatementID private let db: SQLDatabaseID /// Changes when statement is reset. internal private(set) var iteration = Iteration() internal init(id: SQLStatementID, db: SQLDatabaseID) { self.id = id self.db = db } // MARK: - Execute internal func execute() throws { try reset() try step() } internal func execute(values: [SQLValue]) throws { try reset() try bind(values: values) try step() } internal func execute(values: [SQLColumnCompatibleType?]) throws { try reset() try bind(values: values) try step() } internal func execute(namesAndValues: [String: SQLColumnCompatibleType?]) throws { try reset() try bind(namesAndValues: namesAndValues) try step() } internal func execute<T: SQLRowRepresentable>(object: T) throws { try reset() try bind(object: object) try step() } // MARK: - Fetch Row internal func fetchRow() throws -> SQLRow? { try reset() return try nextRow() } internal func fetchRow(values: [SQLValue]) throws -> SQLRow? { try reset() try bind(values: values) return try nextRow() } internal func fetchRow(values: [SQLColumnCompatibleType?]) throws -> SQLRow? { try reset() try bind(values: values) return try nextRow() } internal func fetchRow(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> SQLRow? { try reset() try bind(namesAndValues: namesAndValues) return try nextRow() } // MARK: - Fetch Row Object internal func fetchObject<T: SQLRowRepresentable>() throws -> T? { try reset() return try nextRow().map(T.init) } internal func fetchObject<T: SQLRowRepresentable>(values: [SQLValue]) throws -> T? { try reset() try bind(values: values) return try nextRow().map(T.init) } internal func fetchObject<T: SQLRowRepresentable>(values: [SQLColumnCompatibleType?]) throws -> T? { try reset() try bind(values: values) return try nextRow().map(T.init) } internal func fetchObject<T: SQLRowRepresentable>(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> T? { try reset() try bind(namesAndValues: namesAndValues) return try nextRow().map(T.init) } // MARK: - Fetch All Rows internal func fetchAllRows() throws -> [SQLRow] { try reset() return try allRows() } internal func fetchAllRows(values: [SQLValue]) throws -> [SQLRow] { try reset() try bind(values: values) return try allRows() } internal func fetchAllRows(values: [SQLColumnCompatibleType?]) throws -> [SQLRow] { try reset() try bind(values: values) return try allRows() } internal func fetchAllRows(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> [SQLRow] { try reset() try bind(namesAndValues: namesAndValues) return try allRows() } // MARK: - Fetch All Row Objects internal func fetchAllObjects<T: SQLRowRepresentable>() throws -> [T] { try reset() return try allRowObjects() } internal func fetchAllObjects<T: SQLRowRepresentable>(values: [SQLValue]) throws -> [T] { try reset() try bind(values: values) return try allRowObjects() } internal func fetchAllObjects<T: SQLRowRepresentable>(values: [SQLColumnCompatibleType?]) throws -> [T] { try reset() try bind(values: values) return try allRowObjects() } internal func fetchAllObjects<T: SQLRowRepresentable>(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> [T] { try reset() try bind(namesAndValues: namesAndValues) return try allRowObjects() } // MARK: - Fetch Rows Sequence internal func fetchRowSequence() throws -> SQLRowSequence { try reset() return try rows() } internal func fetchRowSequence(values: [SQLValue]) throws -> SQLRowSequence { try reset() try bind(values: values) return try rows() } internal func fetchRowSequence(values: [SQLColumnCompatibleType?]) throws -> SQLRowSequence { try reset() try bind(values: values) return try rows() } internal func fetchRowSequence(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> SQLRowSequence { try reset() try bind(namesAndValues: namesAndValues) return try rows() } // MARK: - Fetch Objects Sequence internal func fetchObjectSequence<T: SQLRowRepresentable>() throws -> SQLObjectSequence<T> { try reset() return try rowObjects() } internal func fetchObjectSequence<T: SQLRowRepresentable>(values: [SQLValue]) throws -> SQLObjectSequence<T> { try reset() try bind(values: values) return try rowObjects() } internal func fetchObjectSequence<T: SQLRowRepresentable>(values: [SQLColumnCompatibleType?]) throws -> SQLObjectSequence<T> { try reset() try bind(values: values) return try rowObjects() } internal func fetchObjectSequence<T: SQLRowRepresentable>(namesAndValues: [String: SQLColumnCompatibleType?]) throws -> SQLObjectSequence<T> { try reset() try bind(namesAndValues: namesAndValues) return try rowObjects() } // MARK: - Next Row internal func nextRow() throws -> SQLRow? { switch try step() { case .done: return nil case .row(let row): return row } } internal func nextRowForIteration(_ iteration: Iteration) throws -> SQLRow? { guard self.iteration == iteration else { return nil } switch try step() { case .done: return nil case .row(let row): return row } } // MARK: - Next Object internal func nextObject<T: SQLRowRepresentable>() throws -> T? { switch try step() { case .done: return nil case .row(let row): return try T(sqlRow: row) } } internal func nextObjectForIteration<T: SQLRowRepresentable>(_ iteration: Iteration) throws -> T? { guard self.iteration == iteration else { return nil } switch try step() { case .done: return nil case .row(let row): return try T(sqlRow: row) } } // MARK: - All Rows private func allRows() throws -> [SQLRow] { return try stepAllRows() } // MARK: - All Row Objects private func allRowObjects<T: SQLRowRepresentable>() throws -> [T] { return try stepAllRows().compactMap(T.init) } // MARK: - Rows as Sequence private func rows() throws -> SQLRowSequence { SQLRowSequence(for: self, validForIteration: iteration) } // MARK: - Rows as Object Sequence private func rowObjects<T: SQLRowRepresentable>() throws -> SQLObjectSequence<T> { SQLObjectSequence(for: self, validForIteration: iteration) } // MARK: - Reset private func reset() throws { iteration.markNew() try sqlite3_reset(id) .throwIfNotOK(.failedToResetStatement, db) } // MARK: - Bind private func bind(values: [SQLValue]) throws { let binder = Binder(id: id, db: db) for index in 0..<values.count { switch values[index] { case .text(let text): try binder.bindText(text, at: index) case .int(let value): try binder.bindInt(value, at: index) case .double(let value): try binder.bindDouble(value, at: index) case .blob(let data): try binder.bindBlob(data, at: index) case .null: try binder.bindNull(at: index) } } } private func bind(values: [SQLColumnCompatibleType?]) throws { let binder = Binder(id: id, db: db) for index in 0..<values.count { switch values[index]?.asSQLValue { case .text(let text): try binder.bindText(text, at: index) case .int(let value): try binder.bindInt(value, at: index) case .double(let value): try binder.bindDouble(value, at: index) case .blob(let data): try binder.bindBlob(data, at: index) case .null: try binder.bindNull(at: index) default: try binder.bindNull(at: index) } } } private func bind(namesAndValues: [String: SQLColumnCompatibleType?], optionalParameters: Bool = false) throws { let binder = Binder(id: id, db: db) for (name, value) in namesAndValues { do { let sqlValue = value?.asSQLValue switch sqlValue { case .text(let string): try binder.bindText(string, to: name, isOptional: optionalParameters) case .int(let number): try binder.bindInt(number, to: name, isOptional: optionalParameters) case .double(let number): try binder.bindDouble(number, to: name, isOptional: optionalParameters) case .blob(let data): try binder.bindBlob(data, to: name, isOptional: optionalParameters) case .null: try binder.bindNull(to: name, isOptional: optionalParameters) default: try binder.bindNull(to: name, isOptional: optionalParameters) } } catch { print("Failed to bind value '\(String(describing: value))' to '\(name)'") dump(error) throw error } } } private func bind<T: SQLRowRepresentable>(object: T) throws { try bind(namesAndValues: object.makeSQLNamesAndValues(), optionalParameters: true) } // MARK: - Step @discardableResult private func step() throws -> StepResult { let result = sqlite3_step(id) switch result { case SQLITE_DONE: return .done case SQLITE_ROW: return .row(try fetchCurrentRow()) default: throw SQLError.failedToStepStatement(db) } } // MARK: - Step All Rows public func stepAllRows() throws -> [SQLRow] { var rows = [SQLRow]() loop: while true { switch try step() { case .done: break loop case .row(let row): rows.append(row) } } return rows } // MARK: - Fetch Current Row private func fetchCurrentRow() throws -> SQLRow { let columnCount = sqlite3_column_count(id) guard columnCount > 0 else { return SQLRow() } var row = SQLRow() for columnIndex in 0..<columnCount { let columnType = sqlite3_column_type(id, columnIndex) let value: SQLValue switch columnType { case SQLITE_INTEGER: value = .int(Int(sqlite3_column_int64(id, columnIndex))) case SQLITE_FLOAT: value = .double(sqlite3_column_double(id, columnIndex)) case SQLITE_TEXT: if let text = sqlite3_column_text(id, columnIndex) { value = .text(String(cString: text)) } else { value = .null } case SQLITE_BLOB: if let blob = sqlite3_column_blob(id, columnIndex) { let byteCount = sqlite3_column_bytes(id, columnIndex) if byteCount > 0 { value = .blob(Data(bytes: blob, count: Int(byteCount))) } else { value = .null } } else { value = .null } case SQLITE_NULL: value = .null default: value = .null } let columnName: SQLColumnName if let rawColumnName = sqlite3_column_name(id, columnIndex) { columnName = String(cString: rawColumnName) } else { columnName = "Column \(columnIndex)" } row.addColumn(name: columnName, index: columnIndex, value: value) } return row } }
30.221198
146
0.571058
e96095ff80e76388f003d2503e672fa8532899cc
3,496
// // CustomPresentationController.swift // CustomTransitionsExample // // Created by Yee Peng Chia on 12/28/14. // Copyright (c) 2014 Keen Code Interactive. All rights reserved. // import UIKit class CustomPresentationController: UIPresentationController { override func presentationTransitionWillBegin() { // let firstViewController = self.presentingViewController as FirstViewController // let image = firstViewController.titleViewAsImage() // // let secondViewController = self.presentedViewController as SecondViewController // secondViewController.titleImageView = UIImageView(image: image) // secondViewController.titleImageView?.backgroundColor = UIColor.clearColor() // secondViewController.view.insertSubview(secondViewController.titleImageView!, // belowSubview: secondViewController.closeButton) // // let centerXConstraint = NSLayoutConstraint(item: secondViewController.titleImageView!, // attribute: NSLayoutAttribute.CenterX, // relatedBy: NSLayoutRelation.Equal, // toItem: secondViewController.view, // attribute: NSLayoutAttribute.CenterX, // multiplier: 1.0, // constant: 0.0) // // let centerYConstraint = NSLayoutConstraint(item: secondViewController.titleImageView!, // attribute: NSLayoutAttribute.CenterY, // relatedBy: NSLayoutRelation.Equal, // toItem: secondViewController.view, // attribute: NSLayoutAttribute.CenterY, // multiplier: 1.0, // constant: 0.0) // // secondViewController.view .addConstraints([centerXConstraint, centerYConstraint]) self.containerView.addSubview(self.presentedView()) if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition( {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in }, completion:nil) } } override func presentationTransitionDidEnd(completed: Bool) { if !completed { } } override func dismissalTransitionWillBegin() { if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition( {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in }, completion:nil) } } override func dismissalTransitionDidEnd(completed: Bool) { if completed { } } override func frameOfPresentedViewInContainerView() -> CGRect { var frame = self.containerView.bounds; return frame } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator) transitionCoordinator.animateAlongsideTransition( {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in // var firstViewController = self.presentingViewController as FirstViewController // firstViewController.button.frame = self.containerView.bounds }, completion:nil) } }
39.727273
97
0.66476
9095af7ff75e1192e50690814da81232aef358d5
448
// 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: "ARCoreLocation", platforms: [ .iOS(.v11) ], products: [ .library(name: "ARCoreLocation", targets: ["ARCoreLocation"]) ], dependencies: [], targets: [ .target(name: "ARCoreLocation", path: "ARCoreLocation") ] )
24.888889
96
0.638393
f7563c83f7aacaf9cfe5f59d8c84eacdafef03ec
1,055
// // Testable_SwiftTests.swift // Testable SwiftTests // // Created by Jim Puls on 10/29/14. // Licensed to Square, Inc. under one or more contributor license agreements. // See the LICENSE file distributed with this work for the terms under // which Square, Inc. licenses this file to you. import UIKit import XCTest class Testable_SwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
27.763158
111
0.640758
9138027509c5af430d92f7fe911ca0b3a4b4a432
1,805
// // Purchase.swift // mas-cli // // Created by Jakob Rieck on 24/10/2017. // Copyright (c) 2017 Jakob Rieck. All rights reserved. // import Commandant import CommerceKit public struct PurchaseCommand: CommandProtocol { public typealias Options = PurchaseOptions public let verb = "purchase" public let function = "Purchase and download free apps from the Mac App Store" private let appLibrary: AppLibrary /// Public initializer. public init() { self.init(appLibrary: MasAppLibrary()) } /// Internal initializer. /// - Parameter appLibrary: AppLibrary manager. init(appLibrary: AppLibrary = MasAppLibrary()) { self.appLibrary = appLibrary } /// Runs the command. public func run(_ options: Options) -> Result<Void, MASError> { // Try to download applications with given identifiers and collect results let appIds = options.appIds.filter { appId in if let product = appLibrary.installedApp(forId: appId) { printWarning("\(product.appName) has already been purchased.") return false } return true } do { try downloadAll(appIds, purchase: true).wait() } catch { return .failure(error as? MASError ?? .downloadFailed(error: error as NSError)) } return .success(()) } } public struct PurchaseOptions: OptionsProtocol { let appIds: [UInt64] public static func create(_ appIds: [Int]) -> PurchaseOptions { PurchaseOptions(appIds: appIds.map { UInt64($0) }) } public static func evaluate(_ mode: CommandMode) -> Result<PurchaseOptions, CommandantError<MASError>> { create <*> mode <| Argument(usage: "app ID(s) to install") } }
28.203125
108
0.631025
69809f8f0b4dedb179a76bcca96da394f7be2680
601
// // ItemComparison.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // import Foundation func <(lhs: UDItem, rhs: UDItem) -> Bool { if lhs.rarity != rhs.rarity { return lhs.rarity.rawValue < rhs.rarity.rawValue } else { return lhs.baseValue < rhs.baseValue } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 5"
33.388889
235
0.697171
6aae756f4caa9a207f1568b14ddd40bfc447e32d
380
// // SimpleColor.swift // Created by Julian Schiavo on 13/5/2020. // Copyright © 2020 Julian Schiavo. All rights reserved. // import UIKit public struct SimpleColor: Equatable, Hashable { var red: CGFloat var green: CGFloat var blue: CGFloat var uiColor: UIColor { UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1) } }
21.111111
79
0.647368
eb65a1f37eb39333efcfa4cb4e1b9f12f5247aaf
2,578
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b=l let:b}struct B{class a=l func a<I func a}}}struct X<T:T.a var f=(" class d<T enum S<h{ typealias F>(" class A{{d enum B{ enum S<T where g: d = [ 1 ) class c{{ protocol A{class d{ {class A{d{ class c<T where g:{}typealias d<I func b{ class A{{class A{ typealias d class A{{{ var _=b{}}}struct S{class S< enum a}b func b {}typealias F>(b=1 var f{class a}}}b}}}struct S<B<H.h=F=b{enum a}struct B{ {class b{let f{ enum S if true{class B{class b<T where h.g=a{ }}typealias F=F>(b< var f=1 let f=1 { }}}struct S{{ func b<I func a<H.h{{class b<T where h.g=a{ class c{{enum a{class b=c{class b{ let a enum b=(" typealias d<I func a{class a{class S<I func b<T where h.g=a{ class B{ func g:d< class func g:e{class c<T where g:e{class c,case struct g mb:d<h{class d<a}}class b<T{ import a{class a enum b{class A{class d} Int] g mb:b:e{class A{class d:d<T where g: AnyObject func a}struct g : AnyObject typealias d<T where g{{{class a {class A{class A{{{ { var f{ class B{class a = d:{func b<let a = [ 1 ) func g:{b { if true{var b {class A{< }}enum a<T where g:Int a let:{{{ }struct X<T:T.a enum S<I func a<I : d = [ 1 ) }struct Q<T{{ {{< }}enum a<T where g:Int a var f{ }struct B<T enum b{{class A{class d func g{{class d{< }}enum a<T where g:Int a class S<T where g:e{}struct B{{}}}struct Q<T where H{ var _=(b{class A{let f=(b{class b<T where h.g=a{ class d:{{ func g: AnyObject class a}class a}}}struct B<T{let a {class a=c,case func a{{ class d<T where g:e{ }struct S<B{class b=(" let f{class b typealias d<T where g:d:d} Int] g : d = d} Int] g : f {class a{ class S<I : d = d<T where g:d func b{class a{b {struct Q< class b{} class c{class d} Int] g mb:{class A{ func p{func p{ class A{class b<T where h.g=a{ }}class a enum S case c{class A{ enum b{struct g : d = [ 1 ) func a<T where g: d where g: d where g: d = d:{ func a}protocol A{func a{var f{ protocol A{ class a{struct S{ class A{d } protocol A{ let : AnyObject class b=c,case if true{ func a{{func a{ { func b let:b struct B{ if true{class c{ { func a}struct S class var f{struct S struct Q<T{ class A{func a<T enum S<T where g:d struct X<T:T.a class A{ protocol a<T where g:{class d:d} Int] g mb:{func g:e{ enum S<T{func b<T where h.g=a{ let f{class d:e{}struct S<T where g: f {class b{class d< let f{class d func a{class d class a{ enum S<I func a{class a}struct B{class A{{{class b<T where h.g=a{
23.436364
93
0.657099
1e6630efca0ac3e2287cbc00b999f8683980d584
3,212
import Foundation public enum PMKError: Error { /** The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`. This is invalid as per Cocoa/Apple calling conventions. */ case invalidCallingConvention /** A handler returned its own promise. 99% of the time, this is likely a programming error. It is also invalid per Promises/A+. */ case returnedSelf /** `when()`, `race()` etc. were called with invalid parameters, eg. an empty array. */ case badInput /// The operation was cancelled case cancelled /// `nil` was returned from `flatMap` @available(*, deprecated, message: "See: `compactMap`") case flatMap(Any, Any.Type) /// `nil` was returned from `compactMap` case compactMap(Any, Any.Type) /** The lastValue or firstValue of a sequence was requested but the sequence was empty. Also used if all values of this collection failed the test passed to `firstValue(where:)`. */ case emptySequence } extension PMKError: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .flatMap(obj, type): return "Could not `flatMap<\(type)>`: \(obj)" case let .compactMap(obj, type): return "Could not `compactMap<\(type)>`: \(obj)" case .invalidCallingConvention: return "A closure was called with an invalid calling convention, probably (nil, nil)" case .returnedSelf: return "A promise handler returned itself" case .badInput: return "Bad input was provided to a PromiseKit function" case .cancelled: return "The asynchronous sequence was cancelled" case .emptySequence: return "The first or last element was requested for an empty sequence" } } } extension PMKError: LocalizedError { public var errorDescription: String? { return debugDescription } } //////////////////////////////////////////////////////////// Cancellation /// An error that may represent the cancelled condition public protocol CancellableError: Error { /// returns true if this Error represents a cancelled condition var isCancelled: Bool { get } } extension Error { public var isCancelled: Bool { do { throw self } catch PMKError.cancelled { return true } catch let error as CancellableError { return error.isCancelled } catch URLError.cancelled { return true } catch CocoaError.userCancelled { return true } catch { #if os(macOS) || os(iOS) || os(tvOS) let pair = { ($0.domain, $0.code) }(error as NSError) return pair == ("SKErrorDomain", 2) #else return false #endif } } } /// Used by `catch` and `recover` public enum CatchPolicy { /// Indicates that `catch` or `recover` handle all error types including cancellable-errors. case allErrors /// Indicates that `catch` or `recover` handle all error except cancellable-errors. case allErrorsExceptCancellation }
31.184466
97
0.61457
8794fea049f2254e72d34c69d074d25346bb79a8
4,707
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import Amplify import AWSRekognition import AWSTextract import AWSPolly import AWSTranslate import AWSComprehend import AWSTranscribeStreaming class PredictionsErrorHelper { static func mapHttpResponseCode(statusCode: Int, serviceKey: String) -> PredictionsError? { switch statusCode { case 200 ..< 300: return nil case 404: return PredictionsError.httpStatus(statusCode, "Please check your request and try again") case 400: return PredictionsError.httpStatus(statusCode, """ There are number of reasons for receiving a 400 status code. Please check the service documentation for the specific service you are hitting. """) case 500: return PredictionsError.httpStatus(statusCode, """ The request processing has failed because of an unknown error, exception or failure. Please check aws-amplify github for known issues. """) case 503: return PredictionsError.httpStatus(statusCode, "The request has failed due to a temporary failure of the server.") default: return PredictionsError.httpStatus( statusCode, """ Status code unrecognized, please refer to the AWS Service error documentation. https://docs.aws.amazon.com/directoryservice/latest/devguide/CommonErrors.html """ ) } } // swiftlint:disable cyclomatic_complexity static func mapPredictionsServiceError(_ error: NSError) -> PredictionsError { let defaultError = PredictionsErrorHelper.getDefaultError(error) switch error.domain { case AWSServiceErrorDomain: let errorTypeOptional = AWSServiceErrorType.init(rawValue: error.code) guard let errorType = errorTypeOptional else { return defaultError } return AWSServiceErrorMessage.map(errorType) ?? defaultError case AWSRekognitionErrorDomain: guard let errorType = AWSRekognitionErrorType.init(rawValue: error.code) else { return defaultError } return AWSRekognitionErrorMessage.map(errorType) ?? defaultError case AWSPollyErrorDomain: guard let errorType = AWSPollyErrorType.init(rawValue: error.code) else { return defaultError } return AWSPollyErrorMessage.map(errorType) ?? defaultError case AWSTextractErrorDomain: guard let errorType = AWSTextractErrorType.init(rawValue: error.code) else { return defaultError } return AWSTextractErrorMessage.map(errorType) ?? defaultError case AWSComprehendErrorDomain: guard let errorType = AWSComprehendErrorType.init(rawValue: error.code) else { return defaultError } return AWSComprehendErrorMessage.map(errorType) ?? defaultError case AWSTranslateErrorDomain: guard let errorType = AWSTranslateErrorType.init(rawValue: error.code) else { return defaultError } return AWSTranslateErrorMessage.map(errorType) ?? defaultError case AWSTranscribeStreamingErrorDomain: guard let errorType = AWSTranscribeStreamingErrorType.init(rawValue: error.code) else { return defaultError } return AWSTranscribeStreamingErrorMessage.map(errorType) ?? defaultError default: return defaultError } } static func getDefaultError(_ error: NSError) -> PredictionsError { let errorMessage = """ Domain: [\(error.domain) Code: [\(error.code) LocalizedDescription: [\(error.localizedDescription) LocalizedFailureReason: [\(error.localizedFailureReason ?? "") LocalizedRecoverySuggestion: [\(error.localizedRecoverySuggestion ?? "") """ return PredictionsError.unknown(errorMessage, "") } }
42.026786
114
0.583174
bb97ae4e981d0cac4453db02fdd78c8a85d3fe1b
185
import Foundation public protocol FbSimCtlEventCommonFields { var type: FbSimCtlEventType { get } var name: FbSimCtlEventName { get } var timestamp: TimeInterval { get } }
23.125
43
0.735135
0966818d2b4faa4a60cd11deaef1ae4a741969a0
2,864
// // HomeViewController.swift // CodeReader // // Created by Alberto Lourenço on 23/03/18. // Copyright © 2018 Alberto Lourenço. All rights reserved. // import UIKit import Contacts import EventKit import CoreLocation class HomeViewController: UIViewController, CodeReaderDelegate { @IBOutlet private weak var lblCode: UILabel? //----------------------------------------------------------------------- // MARK: - UIViewController //----------------------------------------------------------------------- override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.lblCode?.text = "" } //----------------------------------------------------------------------- // MARK: - CodeReader Delegate //----------------------------------------------------------------------- func codeReaderDidCancel() { // when user close CodeReader } func codeReaderDidFail(controller: CodeReaderViewController) { // when camera doesn't detect a QRCode or Barcode } func codeReaderDidGetQRCode(controller: CodeReaderViewController, type: CodeReaderType, value: Any?) { if !CodeReaderConfig.handleAutomatically { controller.dismiss(animated: true, completion: nil) } switch type { case .undefined: if let string = value as? String { self.lblCode?.text = string } break case .url: if let url = value as? URL { self.lblCode?.text = url.absoluteString } break case .sms: if let sms = value as? CodeReaderSMS { self.lblCode?.text = String(describing: sms) } break case .mail: if let mail = value as? CodeReaderMail { self.lblCode?.text = String(describing: mail) } break case .vcard: if let contact = value as? CNContact { self.lblCode?.text = String(describing: contact) } break case .event: if let event = value as? EKEvent { self.lblCode?.text = String(describing: event) } break case .geolocation: if let location = value as? CLLocation { self.lblCode?.text = String(describing: location) } break } } func codeReaderDidGetBarcode(controller: CodeReaderViewController, code: String) { controller.dismiss(animated: true, completion: nil) self.lblCode?.text = code } //----------------------------------------------------------------------- // MARK: - Custom methods //----------------------------------------------------------------------- @IBAction func handleAutomatically() { CodeReaderConfig.handleAutomatically = true self.showCodeReader() } @IBAction func handleManually() { CodeReaderConfig.handleAutomatically = false self.showCodeReader() } private func showCodeReader() { let codeReaderVC = CodeReaderViewController().instantiate(delegate: self) self.present(codeReaderVC, animated: true, completion: nil) } }
26.036364
103
0.585545
14251bc98a40300312c3516097adb6f701506860
255
import Vapor public extension Future where T: Response { public func flash(_ type: Flash.Kind, _ message: String) -> Future<Response> { return self.map(to: Response.self) { res in return res.flash(type, message) } } }
25.5
82
0.627451
0ab03a87f35025e574291189d3361a6e74dfc3dc
1,862
// // The MIT License // // Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.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. // // // HMLocalDeviceError.swift // HMKit // // Created by Mikk Rätsep on 13/11/2017. // import CoreBluetooth import Foundation /// The values representing an error encountered by the `HMLocalDevice`. public enum HMLocalDeviceError: Error { /// The `HMLocalDevice` is already connected to a Link case alreadyConnected /// Bluetooth has a problem case bluetooth(HMBluetoothError) /// `HMLocalDevice` had an internal error (usually releated to invalid data) case internalError /// An input was invalid or the size was wrong case invalidInput /// `HMLocalDevice` is uninitalised with certificate and keys case uninitialised }
35.132075
81
0.737379
1693607e4aef2e8966d91dd39f2995df887c2626
1,404
// // AppDelegate.swift // BetterRest // // Created by DR_Kun on 2020/3/2. // Copyright © 2020 kun. 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 } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.947368
179
0.746439
7aa14a0f28d42e52174c2eb1ade4e9d93bc2a91c
1,203
// // DynamicFormContainer.swift // UIComponent_Example // // Created by labs01 on 6/15/18. // Copyright © 2018 CocoaPods. All rights reserved. // import Foundation import UIComponent struct DynamicFormState{ var names:[String:[String]] } protocol DynamicFormContainerDelegate:class { func onLoadMoreClick() func onRefresh() } class DynamicFormContainer: BaseComponentRenderable<DynamicFormState>{ weak var viewController: DynamicFormViewController? weak var delegate:DynamicFormContainerDelegate? public init(controller: DynamicFormViewController, state: DynamicFormState){ self.viewController = controller super.init(state: state) } override func render(_ state: DynamicFormState) -> ComponentContainer { return EmptyViewComponent(){ $0.backgroundColor = Color.green $0.layout = {v in constrain(v){ view in view.left == view.superview!.left view.right == view.superview!.right view.top == view.superview!.top + 64 view.bottom == view.superview!.bottom } } } } }
26.733333
80
0.630923
1ac49cf83eb05e569a81e23c376a1e162c760ed9
4,941
// // STPlayerManage.swift // STScrolPlay // // Created by xiudou on 2017/8/1. // Copyright © 2017年 CoderST. All rights reserved. // import UIKit import SVProgressHUD class STPlayerManage: NSObject { /// 单粒管理者 static let shareManage : STPlayerManage = STPlayerManage() /// STPlayer数组 fileprivate lazy var playerArray : [STPlayer] = [STPlayer]() fileprivate var time : Timer? fileprivate var timeInterval : TimeInterval = 1 /// 正在播放的player weak var currentPlayer : STPlayer? /// 当前播放的图层 weak var currentPlayerView : UIView? /// 当前播放器的状态 var status : PlayerState?{ return currentPlayer?.state } override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(removeActionPlayer(_:)), name: NSNotification.Name(rawValue: RemoveActionPlayer), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } } // MARK:- 对外接口 extension STPlayerManage{ /// 按钮点击操作 func playWithURL(_ playUrl : URL, _ configuration : STConfiguration){ // 1 是不是活跃状态 if currentPlayer?.isAction == true && currentPlayerView?.hash == configuration.palyView?.hash{ // 1.1 是 resume currentPlayer?.resume() }else{ // 1.2 不是 // 1.21 停止上个播放 stopUpStPlayer() // 1.22 播放新的视频 addStPlayer(playUrl, configuration) } } /// 退出界面删除全部 func removeAll(){ removeTime() for player in playerArray{ player.stop() } SVProgressHUD.dismiss() playerArray.removeAll() } // MARK:- 私有方法 /// 停止上个播放器 func stopUpStPlayer(){ guard let currentPlayer = currentPlayer else { return } if let index = playerArray.index(of: currentPlayer){ currentPlayer.isAction = false currentPlayer.stop() resetVideoView(currentPlayerView) playerArray.remove(at: index) } } /// 添加新的播放器 fileprivate func addStPlayer(_ playUrl : URL, _ configuration : STConfiguration){ let player = STPlayer() print(player) player.isAction = true player.playWithURL(playUrl, configuration) // 添加新的player addPlayer(player) currentPlayer = player currentPlayerView = configuration.palyView as! STVideoView? startTimeAction() } /// 移除活跃的player @objc fileprivate func removeActionPlayer(_ notification : Notification){ guard let willRemoveCell = notification.object as? STCell else { return } // guard let currentPlayCell = currentPlayerView?.superview as? STCell else { return } if willRemoveCell.videlView.hash == currentPlayerView?.hash { currentPlayer?.stop() resetVideoView(currentPlayerView) deletePlayer(currentPlayer) removeTime() print("可以移除") }else{ print("不需要移除") } } /// videoView复位 fileprivate func resetVideoView(_ videoView : UIView?){ if let viedoView = videoView as? STVideoView{ viedoView.reset() } } @objc fileprivate func startTimeAction(){ if time == nil { time = Timer(timeInterval: timeInterval, target: self, selector: #selector(videoViewUpUI), userInfo: nil, repeats: true) RunLoop.main.add(time!, forMode: .commonModes) } } @objc fileprivate func videoViewUpUI() { if currentPlayer?.isAction == true { guard let currentPlayer = currentPlayer else { return } if currentPlayer.state == .Stopped { stopUpStPlayer() } // currentPlayerView?.upData(currentPlayer) } } fileprivate func removeTime() { time?.invalidate() time = nil } } // MARK:- 私有方法 extension STPlayerManage { /// 添加player fileprivate func addPlayer(_ player : STPlayer){ if playerArray.contains(player){ print("已经存在player - ",player) }else{ playerArray.append(player) } } /// 删除player fileprivate func deletePlayer(_ player : STPlayer?){ if player == nil { return } if playerArray.contains(player!) { guard let index = playerArray.index(of: player!) else { return } player?.stop() playerArray.remove(at: index) }else{ print("player - 不存在",player!) } } }
25.209184
167
0.549686
725df6976f409e3d4c69f3f7890c4991ad09b207
2,073
/* * Copyright (C) 2016 nohana, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an &quot;AS IS&quot; 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 Photos public class PhotoKitAsset: Asset { public var durationString: String? { guard self.asset.mediaType == .video else { return nil } let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional formatter.allowedUnits = [ .minute, .second ] formatter.zeroFormattingBehavior = [ .pad ] let formattedDuration = formatter.string(from: self.duration) return formattedDuration } let asset: PHAsset public init(asset: PHAsset) { self.asset = asset } public var originalAsset: PHAsset { return asset as PHAsset } public var duration: TimeInterval { return self.asset.duration } // MARK: - Asset public var identifier: Int { return asset.localIdentifier.hash } public func image(targetSize: CGSize, handler: @escaping (ImageData?) -> Void) { let option = PHImageRequestOptions() option.isNetworkAccessAllowed = true _ = PHImageManager.default().requestImage( for: self.asset, targetSize: targetSize, contentMode: .aspectFit, options: option ) { (image, info) -> Void in guard let image = image else { handler(nil) return } handler(ImageData(image: image, info: info as Dictionary<NSObject, AnyObject>?)) } } }
30.940299
96
0.632899
3982a30698795a30040d856bc6dd9ee6f16f6717
669
// // MetaHeader.swift // LucidCodeGenCore // // Created by Théophane Rupin on 3/20/19. // import Meta public struct MetaHeader { public let filename: String public let organizationName: String public init(filename: String, organizationName: String) { self.filename = filename self.organizationName = organizationName } public var meta: [Comment] { return [ .empty, .comment(filename), .empty, .comment("Generated automatically."), .comment("Copyright © \(organizationName). All rights reserved."), .empty ] } }
20.272727
78
0.572496
1c1bc153fe3ad38d037cebfafd501c5bd66dd080
4,479
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore // MARK: Paginators extension ELBV2 { /// Describes the specified listeners or the listeners for the specified Application Load Balancer or Network Load Balancer. You must specify either a load balancer or one or more listeners. For an HTTPS or TLS listener, the output includes the default certificate for the listener. To describe the certificate list for the listener, use DescribeListenerCertificates. public func describeListenersPaginator( _ input: DescribeListenersInput, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (DescribeListenersOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeListeners, tokenKey: \DescribeListenersOutput.nextMarker, on: eventLoop, onPage: onPage ) } /// Describes the specified load balancers or all of your load balancers. To describe the listeners for a load balancer, use DescribeListeners. To describe the attributes for a load balancer, use DescribeLoadBalancerAttributes. public func describeLoadBalancersPaginator( _ input: DescribeLoadBalancersInput, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (DescribeLoadBalancersOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeLoadBalancers, tokenKey: \DescribeLoadBalancersOutput.nextMarker, on: eventLoop, onPage: onPage ) } /// Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. To describe the targets for a target group, use DescribeTargetHealth. To describe the attributes of a target group, use DescribeTargetGroupAttributes. public func describeTargetGroupsPaginator( _ input: DescribeTargetGroupsInput, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (DescribeTargetGroupsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeTargetGroups, tokenKey: \DescribeTargetGroupsOutput.nextMarker, on: eventLoop, onPage: onPage ) } } extension ELBV2.DescribeListenersInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ELBV2.DescribeListenersInput { return .init( listenerArns: self.listenerArns, loadBalancerArn: self.loadBalancerArn, marker: token, pageSize: self.pageSize ) } } extension ELBV2.DescribeLoadBalancersInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ELBV2.DescribeLoadBalancersInput { return .init( loadBalancerArns: self.loadBalancerArns, marker: token, names: self.names, pageSize: self.pageSize ) } } extension ELBV2.DescribeTargetGroupsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> ELBV2.DescribeTargetGroupsInput { return .init( loadBalancerArn: self.loadBalancerArn, marker: token, names: self.names, pageSize: self.pageSize, targetGroupArns: self.targetGroupArns ) } }
40.718182
459
0.665997
6724ae8dbade76d894f2ab21261dd6a419166566
458
import BuildDsl import CheckDemoTask import Cocoapods import Bundler BuildDsl.travis.main( makeLocalTask: { di in try CheckDemoTask( bashExecutor: di.resolve(), iosProjectBuilder: di.resolve(), environmentProvider: di.resolve(), mixboxTestDestinationProvider: di.resolve(), bundlerBashCommandGenerator: di.resolve(), bashEscapedCommandMaker: di.resolve() ) } )
25.444444
56
0.639738
90fc494dc1e836728a8cf63f40fc6066804e0885
5,958
// // Date+Ex.swift // MLHelper_Example // // Created by Mario on 2020/8/31. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation public let AllComponent: Set<Calendar.Component> = [ .era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond, .calendar, .timeZone ] public let datetimeComponent: Set<Calendar.Component> = [ .year, .month, .day, .hour, .minute, .second ] public let dateComponent: Set<Calendar.Component> = [.year, .month, .day] public let timeComponent: Set<Calendar.Component> = [.hour, .minute, .second, .nanosecond] public extension Date { static func +( date: inout Date, timeInterVal: Int) { } } public extension Date { /// date adding years months days hours minutes seconds /// - Parameters: /// - y: year default 0, /// - mh: month default 0 /// - d: day default 0 /// - h: hour default 0 /// - me: minute default 0 /// - s: second default 0 /// - Returns: Date func adding(years y: Int = 0, months mh: Int = 0, days d: Int = 0, hours h: Int = 0, minutes me: Int = 0, seconds s: Int = 0) -> Date { let calendar = Calendar.current var date = self if y != 0 { date = calendar.date(byAdding: .year, value: y, to: date) ?? date } if mh != 0 { date = calendar.date(byAdding: .month, value: mh, to: date) ?? date } if d != 0 { date = calendar.date(byAdding: .day, value: d, to: date) ?? date } if h != 0 { date = calendar.date(byAdding: .hour, value: h, to: date) ?? date } if me != 0 { date = calendar.date(byAdding: .minute, value: me, to: date) ?? date } if s != 0 { date = calendar.date(byAdding: .second, value: s, to: date) ?? date } return date } /// add years /// - Parameter years: added years /// - Returns: Date by adding years func addYears(_ years: Int) -> Date { self.adding(years: years) } /// adding months /// - Parameter months: added month /// - Returns: Date by adding months func addMonths(_ months: Int) -> Date { self.adding(months: months) } /// adding days /// - Parameter days: added days /// - Returns: Date by adding days func addDays(_ days: Int) -> Date { adding(days: days) } /// adding hours /// - Parameter hours: added hours /// - Returns: Date by adding hours func addHours(_ hours: Int) -> Date { adding(hours: hours) } /// adding minutes /// - Parameter minutes: added minutes /// - Returns: Date by adding minutes func addMinutes(_ minutes: Int) -> Date { adding(minutes: minutes) } /// adding seconds /// - Parameter seconds: added seconds /// - Returns: Date by adding seconds func addSeconds(_ seconds: Int) -> Date { adding(seconds: seconds) } /// 获取日期当前所有部分 /// - Parameter components: 获取部分 默认 全部获取 /// - Returns: func getComponents(_ components: Set<Calendar.Component> = AllComponent) -> DateComponents { Calendar.current.dateComponents(components, from: self) } /// 获取日期部分 /// - Returns: (年,月,日) func dateCompoent() -> (year: Int, month: Int, day: Int) { let c = getComponents([.year, .month, .day]) return (c.year!, c.month!, c.day!) } /// 获取时间部分 /// - Returns: (时,分,秒,毫秒) func timeComponent() -> (hour: Int, minute: Int, second: Int, nano: Int) { let c = getComponents([.hour, .minute, .second, .nanosecond]) return (c.hour!, c.minute!, c.second!, c.nanosecond!) } /// 获取某一个值 /// - Parameter component: 获取值的部分 /// - Returns: 获取制定值的结果 func getComponent(component: Calendar.Component) -> Int { Calendar.current.component(component, from: self) } } public extension Date { var year: Int { get { getComponent(component: .year) } } var month: Int { get { getComponent(component: .month) } } var day: Int { get { getComponent(component: .day) } } var hour: Int { get { getComponent(component: .hour) } } var minute: Int { get { getComponent(component: .minute) } } var second: Int { get { getComponent(component: .second) } } var weekday: Int { get { getComponent(component: .weekday) } } var weekOfMonth: Int { get { getComponent(component: .weekOfMonth) } } var weekOfYear: Int { get { getComponent(component: .weekOfYear) } } var weekdayOrdinal: Int { get { getComponent(component: .weekdayOrdinal) } } var yearForWeekOfYear: Int { get { getComponent(component: .yearForWeekOfYear) } } } public extension NSDate { /// date adding years months days hours minutes seconds /// - Parameters: /// - y: year default 0 /// - mh: month default 0 /// - d: day default 0 /// - h: hour default 0 /// - me: minute default 0 /// - s: second default 0 /// - Returns: Date func adding(years y: Int = 0, months mh: Int = 0, days d: Int = 0, hours h: Int = 0, minutes me: Int = 0, seconds s: Int = 0) -> NSDate { return (self as Date).adding(years: y, months: mh, days: d, hours: h, minutes: me, seconds: s) as NSDate } }
23.927711
141
0.527526
ded3c157b80013f52460a7b8fdd3a843527acd66
377
// // PartnerEventIdResponse.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct PartnerEventIdResponse: Codable { public var name: String? public var value: String? public init(name: String? = nil, value: String? = nil) { self.name = name self.value = value } }
15.708333
60
0.660477
ed7c63a720157cd5521550b75a1a7bff894ec77a
292
// // SaveViewController.swift // utility-converter // // Created by Brion Silva on 26/03/2019. // Copyright © 2019 Brion Silva. All rights reserved. // import UIKit class SaveViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
17.176471
54
0.674658
3ab337a7cb7e16181902aac9279eaea22b988bbb
1,333
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation public final class FifoCache<Key: Hashable, Value> { public init(count: Int, queueQos: DispatchQoS) { self.count = count self.keyWriteIndex = 0 self.keys = Array(repeating: nil, count: count) self.storage = Dictionary(minimumCapacity: count) self.queue = DispatchQueue( label: "\(String(reflecting: FifoCache.self))-\(UUID().uuidString)", qos: queueQos, attributes: [.concurrent], target: .global(qos: queueQos.qosClass) ) } public func set(_ value: Value, forKey key: Key) { self.queue.async(flags: .barrier) { // We could remove value from the storage only when key != keyToDel, but the comparison is // much more expensive than unconditional removal from the storage. if let keyToDel = self.keys[self.keyWriteIndex] { self.storage.removeValue(forKey: keyToDel) } self.keys[self.keyWriteIndex] = key self.storage[key] = value self.keyWriteIndex = (self.keyWriteIndex + 1) % self.count } } public func valueForKey(_ key: Key) -> Value? { self.queue.sync { self.storage[key] } } private let count: Int private var keys: [Key?] private var keyWriteIndex: Int private var storage: [Key: Value] private let queue: DispatchQueue }
30.295455
100
0.672918