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
284e3089d3d462fcb14f90d8172c92cbfdad27db
659
// // YMStringRepresentable.swift // YMKit // // Created by Yakov Manshin on 6/12/19. // Copyright © 2019 Yakov Manshin. All rights reserved. // /// A protocol that enforces values of the conforming type to always have nice `String` representation. public protocol YMStringRepresentable { /// String representation of the value. var stringValue: String { get } } extension Int: YMStringRepresentable { public var stringValue: String { return String(describing: self) } } extension Double: YMStringRepresentable { public var stringValue: String { return String(describing: self) } }
20.59375
103
0.673748
7a1d56418a757487ee18f784c56877aa4b014f8e
5,734
// // MQTTDataReading.swift // Classic // // Created by Urayoan Miranda on 9/29/20. // Copyright © 2020 Urayoan Miranda. All rights reserved. // //{ // "BatTemperature":18.61, // "NetAmpHours":0, // "ChargeState":0, // "InfoFlagsBits":-1577046016, // "ReasonForResting":104, // "NegativeAmpHours":-1459, // "BatVoltage":13.71, // "PVVoltage":15.21, // "VbattRegSetPTmpComp":14.7, // "TotalAmpHours":63, // "WhizbangBatCurrent":0.41, // "BatCurrent":0.91, // "PVCurrent":0.71, // "ConnectionState":0, // "EnergyToday":0.41, // "EqualizeTime":7200, // "SOC":100, // "Aux1":false, // "Aux2":false, // "Power":12.01, // "FETTemperature":31.31, // "PositiveAmpHours":2094, // "TotalEnergy":109.51, // "FloatTimeTodaySeconds":16842, // "RemainingAmpHours":63, // "AbsorbTime":7200, // "ShuntTemperature":23.01, // "PCBTemperature":39.41 //} struct MQTTDataReading: Codable { var BatTemperature: Float? var NetAmpHours: Int? var ChargeState: Int? var InfoFlagsBits: Int? var ReasonForResting: Int? var NegativeAmpHours: Int? var BatVoltage: Float? var PVVoltage: Float? var VbattRegSetPTmpComp: Float? var TotalAmpHours: Int? var WhizbangBatCurrent: Float? var BatCurrent: Float? var PVCurrent: Float? var ConnectionState: Int? var EnergyToday: Float? var EqualizeTime: Int? var SOC: Int? var Aux1: Bool? var Aux2: Bool? var Power: Float? var FETTemperature: Float? var PositiveAmpHours: Int? var TotalEnergy: Float? var FloatTimeTodaySeconds: Int? var RemainingAmpHours: Int? var AbsorbTime: Int? var ShuntTemperature: Float? var PCBTemperature: Float? init(BatTemperature: Float? = 0.0,NetAmpHours: Int? = 0, ChargeState: Int? = 0, InfoFlagsBits: Int? = 0, ReasonForResting: Int? = 0, NegativeAmpHours: Int?, BatVoltage: Float?, PVVoltage: Float?, VbattRegSetPTmpComp: Float?, TotalAmpHours: Int?, WhizbangBatCurrent: Float?, BatCurrent: Float?, PVCurrent: Float?, ConnectionState: Int?, EnergyToday: Float?, EqualizeTime: Int?, SOC: Int?, Aux1: Bool?, Aux2: Bool?, Power: Float?, FETTemperature: Float?, PositiveAmpHours: Int?, TotalEnergy: Float?, FloatTimeTodaySeconds: Int?, RemainingAmpHours: Int?, AbsorbTime: Int?, ShuntTemperature: Float?, PCBTemperature: Float?) { self.BatTemperature = BatTemperature self.NetAmpHours = NetAmpHours self.ChargeState = ChargeState self.InfoFlagsBits = InfoFlagsBits self.ReasonForResting = ReasonForResting self.NegativeAmpHours = NegativeAmpHours self.BatVoltage = BatVoltage self.PVVoltage = PVVoltage self.VbattRegSetPTmpComp = VbattRegSetPTmpComp self.TotalAmpHours = TotalAmpHours self.WhizbangBatCurrent = WhizbangBatCurrent self.BatCurrent = BatCurrent self.PVCurrent = PVCurrent self.ConnectionState = ConnectionState self.EnergyToday = EnergyToday self.EqualizeTime = EqualizeTime self.SOC = SOC self.Aux1 = Aux1 self.Aux2 = Aux2 self.Power = Power self.FETTemperature = FETTemperature self.PositiveAmpHours = PositiveAmpHours self.TotalEnergy = TotalEnergy self.FloatTimeTodaySeconds = FloatTimeTodaySeconds self.RemainingAmpHours = RemainingAmpHours self.AbsorbTime = AbsorbTime self.ShuntTemperature = ShuntTemperature self.PCBTemperature = PCBTemperature } } extension MQTTDataReading: Equatable { static func ==(lhs: MQTTDataReading, rhs: MQTTDataReading) -> Bool { return (lhs.BatTemperature == rhs.BatTemperature) && (lhs.NetAmpHours == rhs.NetAmpHours) && (lhs.ChargeState == rhs.ChargeState) && (lhs.InfoFlagsBits == rhs.InfoFlagsBits) && (lhs.ReasonForResting == rhs.ReasonForResting) && (lhs.NegativeAmpHours == rhs.NegativeAmpHours) && (lhs.BatVoltage == rhs.BatVoltage) && (lhs.VbattRegSetPTmpComp == rhs.VbattRegSetPTmpComp) && (lhs.TotalAmpHours == rhs.TotalAmpHours) && (lhs.WhizbangBatCurrent == rhs.WhizbangBatCurrent) && (lhs.BatCurrent == rhs.BatCurrent) && (lhs.PVCurrent == rhs.PVCurrent) && (lhs.ConnectionState == rhs.ConnectionState) && (lhs.EnergyToday == rhs.EnergyToday) && (lhs.EqualizeTime == rhs.EqualizeTime) && (lhs.SOC == rhs.SOC) && (lhs.Aux1 == rhs.Aux1) && (lhs.Aux2 == rhs.Aux2) && (lhs.Power == rhs.Power) && (lhs.FETTemperature == rhs.FETTemperature) && (lhs.PositiveAmpHours == rhs.PositiveAmpHours) && (lhs.TotalEnergy == rhs.TotalEnergy) && (lhs.FloatTimeTodaySeconds == rhs.FloatTimeTodaySeconds) && (lhs.RemainingAmpHours == rhs.RemainingAmpHours) && (lhs.AbsorbTime == rhs.AbsorbTime) && (lhs.ShuntTemperature == rhs.ShuntTemperature) && (lhs.PCBTemperature == rhs.PCBTemperature) } } //extended Structure struct MQTTReading : Codable { let records: [MQTTDataReading] } extension MQTTReading: Equatable { static func ==(lhs: MQTTReading, rhs: MQTTReading) -> Bool { return (lhs.records == rhs.records) } }
43.439394
205
0.601849
ed40f38d82314535619d6498781d5c0133e0db10
4,248
// // DetailCellViewModel.swift // FinalProject // // Created by hieungq on 8/11/20. // Copyright © 2020 Asiantech. All rights reserved. // import UIKit import Hero import RealmSwift protocol DetailCellViewModelDelegate: class { func viewModel(_ viewModel: DetailCellViewModel) } final class DetailCellViewModel { // MARK: - Properties private(set) var collectorImage: CollectorImage? private(set) var selectedIndexPath: IndexPath? private(set) var collectorImageSimilars: [CollectorImage] = [] private var notificationToken: NotificationToken? weak var delegate: DetailCellViewModelDelegate? var listImageLiked: [CollectorImage] = [] enum Action { case isLike case reaction } // MARK: - Function init(collectorImage: CollectorImage? = nil, selectedIndexPath: IndexPath? = nil) { self.collectorImage = collectorImage self.selectedIndexPath = selectedIndexPath } func getDataSimilar(completion: @escaping APICompletion) { Api.Detail.getAllImagesSimilar(albumID: (collectorImage?.albumID).content) { [weak self] result in guard let this = self else { return } switch result { case .failure(let error): completion( .failure(error)) case .success(var result): for i in 0..<result.count where this.collectorImage?.imageID == result[i].imageID { result.remove(at: i) break } this.collectorImageSimilars.append(contentsOf: result) completion( .success) } } } func cellForItemAt(indexPath: IndexPath) -> SimilarCellViewModel { guard indexPath.row < collectorImageSimilars.count else { return SimilarCellViewModel() } let collectorImage = collectorImageSimilars[indexPath.row] return SimilarCellViewModel(collectorImage: collectorImage) } func getDetailViewModel(forIndexPath indexPath: IndexPath) -> DetailViewModel { let detailVM = DetailViewModel() detailVM.collectorImages = collectorImageSimilars detailVM.selectedIndexPath = indexPath return detailVM } func setupObserve() { do { let realm = try Realm() notificationToken = realm.objects(CollectorImage.self).observe({ (_) in self.delegate?.viewModel(self) }) } catch { HUD.showError(withStatus: App.String.Error.errorSomeThingWrong) } } func isLike() -> Bool { guard let imageID = collectorImage?.imageID else { return false } do { let realm = try Realm() let image = realm.objects(CollectorImage.self).filter("imageID = '\(imageID)'") if image.count != 0 { return true } else { return false } } catch { HUD.showError(withStatus: App.String.Error.errorSomeThingWrong) return false } } func reaction() -> Bool { guard let imageID = collectorImage?.imageID else { return false } do { if !isLike() { let realm = try Realm() let image = CollectorImage() image.imageID = "\(collectorImage?.imageID ?? "")" image.imageUrl = "\(collectorImage?.imageUrl ?? "")" image.heigthImageForRealm = Double(collectorImage?.heigthImage ?? 0) image.widthImageForRealm = Double(collectorImage?.widthImage ?? 0) image.dateAppend = Date() image.albumID = "\(collectorImage?.albumID ?? "")" try realm.write { realm.add(image) } return true } else { let realm = try Realm() let image = realm.objects(CollectorImage.self).filter("imageID = '\(imageID)'") try realm.write { realm.delete(image) } return false } } catch { HUD.showError(withStatus: App.String.Error.errorSomeThingWrong) return false } } }
34.258065
106
0.582392
f7d5aebdb41fc401b641f6b9afc653ac82990620
414
// // ArticleStoreUseCase.swift // // // Created by Arturo Gamarra on 3/28/21. // import Foundation import Combine public struct ArticleStoreUseCase { private let repo: ArticleRepository public init(repo: ArticleRepository) { self.repo = repo } public func execute(article: Article) -> AnyPublisher<Article, Error> { return repo.store(article: article) } }
18
75
0.654589
39c12383bb3411b166bcaf103e7eb965511138b4
633
// // ObservableOperators.swift // ObservableKit-iOS // // Created by Florian Rath on 20.07.15. // Copyright © 2015 Codepool GmbH. All rights reserved. // import Foundation infix operator <- { associativity right precedence 90 } public func <-<T>(left: OptionalObservable<T>, right: T?) { left.value = right } public func +=<T>(left: OptionalObservable<T>, right: OptionalListener<T>) { left.valueChangedEvent.addListener(right) } public func <-<T>(left: Observable<T>, right: T) { left.value = right } public func +=<T>(left: Observable<T>, right: Listener<T>) { left.valueChangedEvent.addListener(right) }
23.444444
76
0.693523
e627abe8a1e31c0979eb8856662a8a9378f81dbe
3,523
// // RealtimeUITests // // Created by Germán Stábile on 2/13/20. // Copyright © 2020 TopTier labs. All rights reserved. // import XCTest @testable import swift_ui_base class ios_baseUITests: XCTestCase { var app: XCUIApplication! let networkMocker = NetworkMocker() override func setUp() { super.setUp() app = XCUIApplication() app.launchArguments = ["Automation Test"] networkMocker.setUp() } override func tearDown() { super.tearDown() networkMocker.tearDown() } func testCreateAccountValidations() { app.launch() app.buttons["GoToSignUpLink"].tap() let signUpButton = app.buttons["SignUpButton"] waitFor(element: signUpButton, timeOut: 2) XCTAssertFalse(signUpButton.isEnabled) app.type(text: "automation@test", on: "EmailTextField") app.dismissKeyboard() app.type( text: "holahola", on: "PasswordTextField", isSecure: true ) app.dismissKeyboard() XCTAssertFalse(signUpButton.isEnabled) app.type( text: "holahola", on: "ConfirmPasswordTextField", isSecure: true ) XCTAssertFalse(signUpButton.isEnabled) app.type(text: ".com", on: "EmailTextField") XCTAssert(signUpButton.isEnabled) app.dismissKeyboard() app.type( text: "holahol", on: "ConfirmPasswordTextField", isSecure: true ) XCTAssertFalse(signUpButton.isEnabled) } func testAccountCreation() { app.launch() networkMocker.stubSignUp() app.attemptSignUp( in: self, with: "[email protected]", password: "holahola" ) let logOutButton = app.buttons["LogOutButton"] waitFor(element: logOutButton, timeOut: 15) networkMocker.stubLogOut() logOutButton.tap() networkMocker.stubLogIn() app.attemptSignIn( in: self, with: "[email protected]", password: "holahola" ) networkMocker.stubGetProfile() let getMyProfile = app.buttons["GetMyProfileButton"] waitFor(element: getMyProfile, timeOut: 10) getMyProfile.tap() sleep(10) if let alert = app.alerts.allElementsBoundByIndex.first { waitFor(element: alert, timeOut: 10) alert.buttons.allElementsBoundByIndex.first?.tap() networkMocker.stubDeleteAccount() app.deleteAccountIfNeeded(in: self) } } func testSignInFailure() { app.launch() networkMocker.stubLogIn(shouldSucceed: false) app.attemptSignIn( in: self, with: "[email protected]", password: "incorrect password" ) if let alert = app.alerts.allElementsBoundByIndex.first { waitFor(element: alert, timeOut: 2) alert.buttons.allElementsBoundByIndex.first?.tap() } let signInButton = app.buttons["SignInButton"] waitFor(element: signInButton, timeOut: 2) } func testSignInValidations() { app.launch() app.buttons["GoToLoginLink"].tap() let signInButton = app.buttons["SignInButton"] waitFor(element: signInButton, timeOut: 2) XCTAssertFalse(signInButton.isEnabled) app.type(text: "automation@test", on: "EmailTextField") app.type( text: "holahola", on: "PasswordTextField", isSecure: true ) XCTAssertFalse(signInButton.isEnabled) app.type(text: ".com", on: "EmailTextField") XCTAssert(signInButton.isEnabled) } }
21.881988
61
0.635254
4abfff9da7bce36c75dd8c1644238e2c40483dd2
890
import TSCBasic import struct TSCUtility.Version import TuistAutomation import TuistGraph public final class MockTargetRunner: TargetRunning { public init() {} public var runTargetStub: ((GraphTarget, AbsolutePath, String, String?, Version?, Version?, String?, [String]) throws -> Void)? public func runTarget( _ target: GraphTarget, workspacePath: AbsolutePath, schemeName: String, configuration: String?, minVersion: Version?, version: Version?, deviceName: String?, arguments: [String] ) throws { try runTargetStub?(target, workspacePath, schemeName, configuration, minVersion, version, deviceName, arguments) } public var assertCanRunTargetStub: ((Target) throws -> Void)? public func assertCanRunTarget(_ target: Target) throws { try assertCanRunTargetStub?(target) } }
31.785714
131
0.68764
89f058b3df82130369d371614b16ecc2b25e39fa
1,737
// // DynamicAnimatorViewController.swift // animation // // Created by USER on 2018/10/31. // Copyright © 2018 USER. All rights reserved. // import UIKit class DynamicAnimatorViewController: BaseViewController { var animator: UIDynamicAnimator? override func viewDidLoad() { super.viewDidLoad() redView.frame = CGRect(x: 100, y: 100, width: 100, height: 100) animator = UIDynamicAnimator(referenceView: view) } } extension DynamicAnimatorViewController { override func operateTitleArray() -> [String]? { return ["重力", "弹力", "吸附力", "推力", "甩行力"] } override func clickBtn(btn: UIButton) { switch btn.tag { case 0: gravityAnimator() case 1: collisionAnimator() case 2: attachmentAnimator() // case 3: // case 4: default: break } } private func gravityAnimator() { let gravity = UIGravityBehavior(items: [redView]) gravity.setAngle(CGFloat.pi / 2, magnitude: 0.5) animator?.addBehavior(gravity) } private func collisionAnimator() { let collision = UICollisionBehavior(items: [redView]) // collision.addBoundary(withIdentifier: "123ß" as NSCopying, from: CGPoint(x: 0, y: 300), to: CGPoint(x: 300, y: 600)) collision.collisionMode = .everything collision.translatesReferenceBoundsIntoBoundary = true animator?.addBehavior(collision) } private func attachmentAnimator() { let attachment = UIAttachmentBehavior(item: view, attachedToAnchor: CGPoint(x: 100, y: 200)) attachment.length = 100 animator?.addBehavior(attachment) } }
27.140625
126
0.619459
89d920c822a0f46128d0add9096c88fabcd69c0c
9,280
// // PlayerViewController.swift // InsanityRadio // // Created by Dylan Maryk on 25/05/2015. // Copyright (c) 2015 Insanity Radio. All rights reserved. // import MediaPlayer import UIKit class PlayerViewController: UIViewController, RadioDelegate { @IBOutlet weak var navItem: UINavigationItem! @IBOutlet weak var shareBarButtonItem: UIBarButtonItem! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var currentShowLabel: UILabel! @IBOutlet weak var nowPlayingLabel: UILabel! @IBOutlet weak var albumArtImageView: UIImageView! private let radio = Radio() private let manager = AFHTTPRequestOperationManager() private var previousNowPlayingArtwork: UIImage? private var paused = true private var attemptingPlay = true override func viewDidLoad() { super.viewDidLoad() radio.connect("https://insanityradio.com/listen/get_current_stream.mp3?platform=iOS&version=" + API_VERSION, withDelegate: self, withGain: (1.0)) manager.requestSerializer.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateUI), name: "DataUpdated", object: nil) // Workaround for play/stop button image changing on rotate on iOS 9 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updatePlayPauseButton), name: UIDeviceOrientationDidChangeNotification, object: nil) UIApplication.sharedApplication().beginReceivingRemoteControlEvents() NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/London")!) // Test if timer retained in background until app terminated by system let components = NSCalendar.currentCalendar().components([.Minute, .Second], fromDate: NSDate()) let secondsUntilNextHour = NSTimeInterval(3600 - (components.minute * 60) - components.second) NSTimer.scheduledTimerWithTimeInterval(secondsUntilNextHour, target: self, selector: #selector(startCurrentShowTimer), userInfo: nil, repeats: false) let titleViewImageView = UIImageView(frame: CGRectMake(0, 0, 35, 35)) titleViewImageView.image = UIImage(named: "headphone") let titleViewLabel = UILabel() titleViewLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 17) titleViewLabel.textColor = UIColor.whiteColor() titleViewLabel.text = "Insanity Radio" let titleViewLabelSize = titleViewLabel.sizeThatFits(CGSizeMake(CGFloat.max, titleViewImageView.frame.size.height)) titleViewLabel.frame = CGRectMake(titleViewImageView.frame.size.width + 10, 0, titleViewLabelSize.width, titleViewImageView.frame.size.height) let titleView = UIView(frame: CGRectMake(0, 0, titleViewLabel.frame.origin.x + titleViewLabel.frame.size.width, titleViewLabel.frame.size.height)) titleView.addSubview(titleViewImageView) titleView.addSubview(titleViewLabel) navItem.titleView = titleView playPauseButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit updateCurrentShow() } func updateUI() { updateCurrentShow() let nowPlaying = DataModel.getNowPlaying() nowPlayingLabel.text = nowPlaying.song + "\n" + nowPlaying.artist if let art = nowPlaying.albumArt { updateImageWithURL(art) } else { self.displayCurrentShowImage() } radioPlayed() displayNowPlayingInfo(previousNowPlayingArtwork) } func updateCurrentShow() { let currentShow = DataModel.getCurrentShow() var currentShowLabelText = currentShow.name if currentShow.presenters != "" { currentShowLabelText += "\nwith " + currentShow.presenters } currentShowLabel.text = currentShowLabelText } private func updateImageWithURL(imageURL: String) { manager.responseSerializer = AFImageResponseSerializer() let requestOperation = manager.GET(imageURL, parameters: nil, success: { (operation: AFHTTPRequestOperation, responseObject: AnyObject) -> Void in self.displayFinalImage(responseObject as? UIImage) }, failure: { (operation: AFHTTPRequestOperation?, error: NSError) -> Void in self.displayCurrentShowImage() }) requestOperation!.start() } private func displayCurrentShowImage() { manager.responseSerializer = AFImageResponseSerializer() let requestOperation = manager.GET(DataModel.getCurrentShow().imageURL, parameters: nil, success: { (operation: AFHTTPRequestOperation, responseObject: AnyObject) -> Void in self.displayFinalImage(responseObject as? UIImage) }, failure: { (operation: AFHTTPRequestOperation?, error: NSError) -> Void in self.displayDefaultImage() }) requestOperation!.start() } private func displayFinalImage(image: UIImage?) { self.albumArtImageView.image = image displayNowPlayingInfo(image); } private func displayDefaultImage() { self.albumArtImageView.image = UIImage(named: "insanity-icon.png") displayNowPlayingInfo(nil); } private func displayNowPlayingInfo(image: UIImage?) { if NSClassFromString("MPNowPlayingInfoCenter") == nil { return } previousNowPlayingArtwork = image let nowPlaying = DataModel.getNowPlaying() let currentShow = DataModel.getCurrentShow() var nowPlayingSong: String var currentShowName: String if paused { nowPlayingSong = "Insanity Radio" } else { nowPlayingSong = nowPlaying.song } if currentShow.name == "" { currentShowName = "103.2FM" } else { currentShowName = currentShow.name } var songInfo: [String: AnyObject] = [ MPMediaItemPropertyTitle: nowPlayingSong, MPMediaItemPropertyArtist: currentShowName ] if let nowPlayingImage = image { songInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: nowPlayingImage) } MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo } @IBAction private func playPauseButtonTapped() { if paused { playRadio() } else { pauseRadio() } } private func playRadio() { attemptingPlay = true playPauseButton.enabled = false playPauseButton.alpha = 0.5 radio.updatePlay(true) } private func pauseRadio() { radioPaused() radio.updatePlay(false) } func updatePlayPauseButton() { if attemptingPlay { playPauseButton.enabled = false playPauseButton.alpha = 0.5 } else if paused { radioPaused() } else { radioPlayed() } } private func radioPlayed() { paused = false attemptingPlay = false playPauseButton.enabled = true playPauseButton.alpha = 1 playPauseButton.imageView?.image = UIImage(named: "stop.png") } private func radioPaused() { paused = true attemptingPlay = false playPauseButton.enabled = true playPauseButton.alpha = 1 playPauseButton.imageView?.image = UIImage(named: "play.png") nowPlayingLabel.text = "" displayDefaultImage() } @IBAction private func shareButtonTapped() { let activityViewController = UIActivityViewController(activityItems: [CustomActivityItem()], applicationActivities: nil) activityViewController.popoverPresentationController?.barButtonItem = shareBarButtonItem self.presentViewController(activityViewController, animated: true, completion: nil) } func startCurrentShowTimer() { NSTimer.scheduledTimerWithTimeInterval(3600, target: self, selector: #selector(updateCurrentShow), userInfo: nil, repeats: true) updateCurrentShow() } override func remoteControlReceivedWithEvent(event: UIEvent?) { guard let controlEvent = event else { return } if controlEvent.subtype == UIEventSubtype.RemoteControlPlay { playRadio() } else if controlEvent.subtype == UIEventSubtype.RemoteControlPause { pauseRadio() } } func metaTitleUpdated(title: String) { DataModel.updateData() } func interruptRadio() { pauseRadio() } func resumeInterruptedRadio() { playRadio() } func connectProblem() { radioPaused() dispatch_async(dispatch_get_main_queue()) { UIAlertView(title: "Cannot Stream Insanity", message: "There was a problem streaming Insanity Radio. Please check your Internet connection.", delegate: self, cancelButtonTitle: "OK").show() } } }
36.25
201
0.649677
d7502ad3a4d5f417e3d2cae7f2ad44509aad9eb1
3,347
// // AppDelegate.swift // MyFirstApp // // Created by Michael Bond on 3/28/15. // Copyright (c) 2015 Michael Bond. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
52.296875
285
0.75112
180521374ec837226e14123ffa08624128aaf68f
751
// // AppDelegate.swift // WeatherApp // // Created by Ange Luvari & Maxime Begarie on 06/05/2019. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) {} func applicationDidEnterBackground(_ application: UIApplication) {} func applicationWillEnterForeground(_ application: UIApplication) {} func applicationDidBecomeActive(_ application: UIApplication) {} func applicationWillTerminate(_ application: UIApplication) {} }
25.896552
145
0.758988
87ebba46cba83e11f4c75ab6bcd98726b1885954
3,268
// // NSAttributeString+Extension.swift // EZBasicKit // // Created by wangding on 2019/5/24. // import Foundation extension NSMutableAttributedString { public func setAttributes(_ attributes: [NSAttributedString.Key: Any]?, regexPattern: String, options: NSRegularExpression.Options = []) { guard let regex = try? NSRegularExpression(pattern: regexPattern, options: options) else { return } let str = self.string let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count)) for r in results { self.setAttributes(attributes, range: r.range) } } public func addAttribute(_ name: String, value: Any, regexPattern: String, options: NSRegularExpression.Options = []) { guard let regex = try? NSRegularExpression(pattern: regexPattern, options: options) else { return } let str = self.string let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count)) for r in results { self.addAttribute(NSAttributedString.Key(rawValue: name), value: value, range: r.range) } } } extension NSAttributedString { var mutableAttributedString: NSMutableAttributedString { return NSMutableAttributedString(attributedString: self) } @objc public func setFont(_ font: UIFont) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.addAttributes([NSAttributedString.Key.font: font], range: NSRange(location: 0, length: self.length)) return muAttr } public func setColor(_ color: UIColor) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.addAttributes([NSAttributedString.Key.foregroundColor: color], range: NSRange(location: 0, length: self.length)) return muAttr } public func setUnderLineColor(_ lineColor: UIColor) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue], range: NSRange(location: 0, length: self.length)) muAttr.addAttributes([NSAttributedString.Key.underlineColor: lineColor], range: NSRange(location: 0, length: self.length)) return muAttr } public func asALink(_ link: String) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.addAttributes([NSAttributedString.Key.link: link], range: NSRange(location: 0, length: self.length)) return muAttr } public func asALink(_ link: URL) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.addAttributes([NSAttributedString.Key.link: link], range: NSRange(location: 0, length: self.length)) return muAttr } public func insert(_ object: NSAttributedString, index: Int) -> NSAttributedString { let muAttr = self.mutableAttributedString muAttr.insert(object, at: index) return muAttr } public static func + (lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString { let result = lhs.mutableAttributedString result.append(rhs) return result } }
34.4
153
0.690942
61ade810455950f0701b863251af75ea0b67b5f2
13,822
// // DeviceGuru.swift // // Created by Inder Kumar Rathore on 06/02/15. // Copyright (c) 2015. All rights reserved. // // Hardware string can be found @http://www.everymac.com // import Foundation import UIKit open class DeviceGuru { /// Stores the list of the devices from the DeviceList.plist private let deviceListDict: [String: AnyObject] /// Initialises the DeviceGuru using DeviceList.plist if the plist is not found then it asserts public init() { // get the bundle of the DeviceUtil if it's main bundle then it returns main bundle // if it's DeviceUtil.framework then it returns the DeviceUtil.framework bundle let deviceUtilTopBundle = Bundle(for: DeviceGuru.self) if let url = deviceUtilTopBundle.url(forResource: "DeviceGuru", withExtension: "bundle") { let deviceUtilBundle = Bundle(url: url) if let path = deviceUtilBundle?.path(forResource: "DeviceList", ofType: "plist") { self.deviceListDict = NSDictionary(contentsOfFile: path) as! [String: AnyObject] } else { // Assert if the plist is not found assertionFailure("DevicePlist.plist not found in the bundle.") self.deviceListDict = [String: AnyObject]() } } else if let path = deviceUtilTopBundle.path(forResource: "DeviceList", ofType: "plist") { // falling back to main bundle self.deviceListDict = NSDictionary(contentsOfFile: path) as! [String: AnyObject] } else { // Assert if the plist is not found assertionFailure("DevicePlist.plist not found in the bundle.") self.deviceListDict = [String: AnyObject]() } } /// This method returns the hardware type /// /// /// - returns: raw `String` of device type /// public func hardwareString() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, nil, 0) var hw_machine = [CChar](repeating: 0, count: Int(size)) sysctl(&name, 2, &hw_machine, &size, nil, 0) let hardware: String = String(cString: hw_machine) return hardware } /// This method returns the Hardware enum depending upon harware string /// /// /// - returns: `Hardware` type of the device /// public func hardware() -> Hardware { let hardware = hardwareString() if (hardware == "iPhone1,1") { return Hardware.iphone2g } if (hardware == "iPhone1,2") { return Hardware.iphone3g } if (hardware == "iPhone2,1") { return Hardware.iphone3gs } if (hardware == "iPhone3,1") { return Hardware.iphone4 } if (hardware == "iPhone3,2") { return Hardware.iphone4 } if (hardware == "iPhone3,3") { return Hardware.iphone4_cdma } if (hardware == "iPhone4,1") { return Hardware.iphone4s } if (hardware == "iPhone5,1") { return Hardware.iphone5 } if (hardware == "iPhone5,2") { return Hardware.iphone5_cdma_gsm } if (hardware == "iPhone5,3") { return Hardware.iphone5c } if (hardware == "iPhone5,4") { return Hardware.iphone5c_cdma_gsm } if (hardware == "iPhone6,1") { return Hardware.iphone5s } if (hardware == "iPhone6,2") { return Hardware.iphone5s_cdma_gsm } if (hardware == "iPhone7,1") { return Hardware.iphone6Plus } if (hardware == "iPhone7,2") { return Hardware.iphone6 } if (hardware == "iPhone8,1") { return Hardware.iphone6s } if (hardware == "iPhone8,2") { return Hardware.iphone6sPlus } if (hardware == "iPhone8,4") { return Hardware.iphoneSE } if (hardware == "iPhone9,1") { return Hardware.iphone7 } if (hardware == "iPhone9,2") { return Hardware.iphone7Plus } if (hardware == "iPhone9,3") { return Hardware.iphone7 } if (hardware == "iPhone9,4") { return Hardware.iphone7Plus } if (hardware == "iPhone10,1") { return Hardware.iphone8 } if (hardware == "iPhone10,2") { return Hardware.iphone8Plus } if (hardware == "iPhone10,3") { return Hardware.iphoneX } if (hardware == "iPhone10,4") { return Hardware.iphone8 } if (hardware == "iPhone10,5") { return Hardware.iphone8Plus } if (hardware == "iPhone10,6") { return Hardware.iphoneX } if (hardware == "iPod1,1") { return Hardware.ipodTouch1g } if (hardware == "iPod2,1") { return Hardware.ipodTouch2g } if (hardware == "iPod3,1") { return Hardware.ipodTouch3g } if (hardware == "iPod4,1") { return Hardware.ipodTouch4g } if (hardware == "iPod5,1") { return Hardware.ipodTouch5g } if (hardware == "iPod7,1") { return Hardware.ipodTouch6g } if (hardware == "iPad1,1") { return Hardware.ipad } if (hardware == "iPad1,2") { return Hardware.ipad3g } if (hardware == "iPad2,1") { return Hardware.ipad2_wifi } if (hardware == "iPad2,2") { return Hardware.ipad2 } if (hardware == "iPad2,3") { return Hardware.ipad2_cdma } if (hardware == "iPad2,4") { return Hardware.ipad2 } if (hardware == "iPad2,5") { return Hardware.ipadMini_wifi } if (hardware == "iPad2,6") { return Hardware.ipadMini } if (hardware == "iPad2,7") { return Hardware.ipadMini_wifi_cdma } if (hardware == "iPad3,1") { return Hardware.ipad3_wifi } if (hardware == "iPad3,2") { return Hardware.ipad3_wifi_cdma } if (hardware == "iPad3,3") { return Hardware.ipad3 } if (hardware == "iPad3,4") { return Hardware.ipad4_wifi } if (hardware == "iPad3,5") { return Hardware.ipad4 } if (hardware == "iPad3,6") { return Hardware.ipad4_gsm_cdma } if (hardware == "iPad4,1") { return Hardware.ipadAir_wifi } if (hardware == "iPad4,2") { return Hardware.ipadAir_wifi_gsm } if (hardware == "iPad4,3") { return Hardware.ipadAir_wifi_cdma } if (hardware == "iPad4,4") { return Hardware.ipadMiniRetina_wifi } if (hardware == "iPad4,5") { return Hardware.ipadMiniRetina_wifi_cdma } if (hardware == "iPad4,6") { return Hardware.ipadMiniRetina_wifi_cellular_cn } if (hardware == "iPad4,7") { return Hardware.ipadMini3_wifi } if (hardware == "iPad4,8") { return Hardware.ipadMini3_wifi_cellular } if (hardware == "iPad4,9") { return Hardware.ipadMini3_wifi_cellular_cn } if (hardware == "iPad5,1") { return Hardware.ipadMini4_wifi } if (hardware == "iPad5,2") { return Hardware.ipadMini4_wifi_cellular } if (hardware == "iPad5,3") { return Hardware.ipadAir2_wifi } if (hardware == "iPad5,4") { return Hardware.ipadAir2_wifi_cellular } if (hardware == "iPad6,3") { return Hardware.ipadPro_97_wifi } if (hardware == "iPad6,4") { return Hardware.ipadPro_97_wifi_cellular } if (hardware == "iPad6,7") { return Hardware.ipadPro_wifi } if (hardware == "iPad6,8") { return Hardware.ipadPro_wifi_cellular } if (hardware == "iPad6,11") { return Hardware.ipad5_wifi } if (hardware == "iPad6,12") { return Hardware.ipad5_wifi_cellular } if (hardware == "iPad7,1") { return Hardware.ipadPro2g_wifi } if (hardware == "iPad7,2") { return Hardware.ipadPro2g_wifi_cellular } if (hardware == "iPad7,3") { return Hardware.ipadPro_105_wifi } if (hardware == "iPad7,4") { return Hardware.ipadPro_105_wifi_cellular } if (hardware == "iPad7,5") { return Hardware.ipad6_wifi } if (hardware == "iPad7,6") { return Hardware.ipad6_wifi_cellular } if (hardware == "AppleTV1,1") { return Hardware.appleTv1g } if (hardware == "AppleTV2,1") { return Hardware.appleTv2g } if (hardware == "AppleTV3,1") { return Hardware.appleTv3g_2012 } if (hardware == "AppleTV3,2") { return Hardware.appleTv3g_2013 } if (hardware == "AppleTV5,3") { return Hardware.appleTv4g } if (hardware == "Watch1,1") { return Hardware.appleWatch_38 } if (hardware == "Watch1,2") { return Hardware.appleWatch_42 } if (hardware == "Watch2,3") { return Hardware.appleWatch_series_2_38 } if (hardware == "Watch2,4") { return Hardware.appleWatch_series_2_42 } if (hardware == "Watch2,6") { return Hardware.appleWatch_series_1_38 } if (hardware == "Watch2,7") { return Hardware.appleWatch_series_1_42 } if (hardware == "i386") { return Hardware.simulator } if (hardware == "x86_64") { return Hardware.simulator } //log message that your device is not present in the list logMessage(hardware) if (hardware.hasPrefix("iPhone")) { return Hardware.unknownIphone } if (hardware.hasPrefix("iPod")) { return Hardware.unknownIpod } if (hardware.hasPrefix("iPad")) { return Hardware.unknownIpad } if (hardware.hasPrefix("Watch")) { return Hardware.unknownAppleWatch } if (hardware.hasPrefix("AppleTV")) { return Hardware.unknownAppleTV } return Hardware.unknownDevice } /// This method returns the Platform enum depending upon harware string /// /// /// - returns: `Platform` type of the device /// public func platform() -> Platform { let hardware = hardwareString() if (hardware.hasPrefix("iPhone")) { return Platform.iPhone } if (hardware.hasPrefix("iPod")) { return Platform.iPodTouch } if (hardware.hasPrefix("iPad")) { return Platform.iPad } if (hardware.hasPrefix("Watch")) { return Platform.appleWatch } if (hardware.hasPrefix("AppleTV")) { return Platform.appleTV } return Platform.unknown } /// This method returns the readable description of hardware string /// /// - returns: readable description `String` of the device /// public func hardwareDescription() -> String? { let hardware = hardwareString() let hardwareDetail = self.deviceListDict[hardware] as? [String: AnyObject] if let hardwareDescription = hardwareDetail?["name"] { return hardwareDescription as? String } //log message that your device is not present in the list logMessage(hardware) return nil } /// This method returns the hardware number not actual but logically. /// e.g. if the hardware string is 5,1 then hardware number would be 5.1 /// public func hardwareNumber() -> Float? { let hardware = hardwareString() let hardwareDetail = self.deviceListDict[hardware] as? [String: AnyObject] if let hardwareNumber = hardwareDetail?["version"] as? Float { return hardwareNumber } //log message that your device is not present in the list logMessage(hardware) return nil //device might be new or one of missing device so returning nil } /// This method returns the resolution for still image that can be received /// from back camera of the current device. Resolution returned for image oriented landscape right. /// /// - parameters: /// - hardware: `Hardware` type of the device /// /// - returns: `CGSize` of the image captured by the device /// public func backCameraStillImageResolutionInPixels(_ hardware: Hardware) -> CGSize { switch (hardware) { case .iphone2g, .iphone3g: return CGSize(width: 1600, height: 1200) case .iphone3gs: return CGSize(width: 2048, height: 1536) case .iphone4, .iphone4_cdma, .ipad3_wifi, .ipad3_wifi_cdma, .ipad3, .ipad4_wifi, .ipad4, .ipad4_gsm_cdma: return CGSize(width: 2592, height: 1936) case .iphone4s, .iphone5, .iphone5_cdma_gsm, .iphone5c, .iphone5c_cdma_gsm, .iphone6, .iphone6Plus: return CGSize(width: 3264, height: 2448) case .ipodTouch4g: return CGSize(width: 960, height: 720) case .ipodTouch5g: return CGSize(width: 2440, height: 1605) case .ipad2_wifi, .ipad2, .ipad2_cdma: return CGSize(width: 872, height: 720) case .ipadMini_wifi, .ipadMini, .ipadMini_wifi_cdma: return CGSize(width: 1820, height: 1304) case .ipadMini4_wifi, .ipadMini4_wifi_cellular: return CGSize(width: 3264, height: 2448) case .ipadAir2_wifi, .ipadAir2_wifi_cellular: return CGSize(width: 2048, height: 1536) case .iphone6s, .iphone6sPlus, .iphoneSE, .iphone7, .iphone7Plus: return CGSize(width: 4032, height: 3024) case .ipadPro_97_wifi, .ipadPro_97_wifi_cellular: return CGSize(width: 4032, height: 3024) case .ipadPro_wifi, .ipadPro_wifi_cellular: return CGSize(width: 3264, height: 2448) case .ipadPro2g_wifi, .ipadPro2g_wifi_cellular, .ipadPro_105_wifi, .ipadPro_105_wifi_cellular: return CGSize(width: 4032, height: 3024) default: print("We have no resolution for your device's camera listed in this category. Please, take photo with back camera of your device, get its resolution in pixels (via Preview Cmd+I for example) and add a comment to this repository (https://github.com/InderKumarRathore/DeviceGuru) on GitHub.com in format Device = Wpx x Hpx.") } print("Your device is: \(hardwareDescription() ?? "unknown")") return CGSize.zero } /// Internal method for loggin, you don't need this method /// /// - parameters: /// - hardware: `String` hardware type of the device /// private func logMessage(_ hardware: String) { print("This is a device which is not listed in this category. Please visit https://github.com/InderKumarRathore/DeviceGuru and raise an issue there.") print("Your device hardware string is|" + hardware + "|") } }
44.587097
330
0.636015
262f3567f88e63f93978f19b8a67c9d5f01b1030
1,089
// 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: "HaishinKit", platforms: [ .iOS(.v9), .tvOS(.v10), .macOS(.v10_11) ], products: [ .library(name: "HaishinKit", targets: ["HaishinKit"]) ], dependencies: [ .package(url: "https://github.com/shogo4405/Logboard.git", from: "2.2.2") ], targets: [ .target(name: "SwiftPMSupport"), .target(name: "HaishinKit", dependencies: ["Logboard", "SwiftPMSupport"], path: "Sources", sources: [ "Codec", "Extension", "FLV", "HTTP", "ISO", "Media", "MP4", "Net", "PiP", "RTMP", "Util", "Platforms", "TS" ]) ] )
27.225
96
0.415978
dd844bb7f481c4ed786dd8f4c1777649fb9606c2
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing deinit { let f { for { for in { class case ,
17.833333
87
0.738318
ffbbe5e9a3c117c8e974fba7a2c13074a9f8484e
14,615
//: [Behavioral](Behavioral) | //: Creational | //: [Structural](Structural) /*: # Creational > In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation. > >**Source:** [wikipedia.org](https://en.wikipedia.org/wiki/Creational_pattern) */ import Swift import Foundation import UIKit /*: ## Abstract Factory The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time. ### Implementation */ protocol Sedan { func drive() } class CompactSedan: Sedan { func drive() { print("drive a compact sedan") } } class FullSizeSedan: Sedan { func drive() { print("drive a full-size sedan") } } protocol Hatchback { func drive() } class CompactHatchback: Hatchback { func drive() { print("drive a compact SUV") } } class FullSizeHatchback: Hatchback { func drive() { print("drive a full-size SUV") } } protocol Factory { func produceSedan() -> Sedan func produceHatchback() -> Hatchback } class CompactCarsFactory: Factory { func produceSedan() -> Sedan { return CompactSedan() } func produceHatchback() -> Hatchback { return CompactHatchback() } } class FullSizeCarsFactory: Factory { func produceSedan() -> Sedan { return FullSizeSedan() } func produceHatchback() -> Hatchback { return FullSizeHatchback() } } /*: ### Usage */ let compactCarsFactory = CompactCarsFactory() let compactSedan = compactCarsFactory.produceSedan() let compactHatchback = compactCarsFactory.produceHatchback() compactSedan.drive() compactHatchback.drive() let fullSizeCarsFactory = FullSizeCarsFactory() let fullsizeSedan = fullSizeCarsFactory.produceSedan() let fullsizeHatchback = fullSizeCarsFactory.produceHatchback() fullsizeSedan.drive() fullsizeHatchback.drive() /*: ## Builder The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm. ### Implementation */ class Shop { func build(builder: VehicleBuilder) -> Vehicle { return builder.build() } } protocol VehicleBuilder { var frame: String? { get } var engine: String? { get } var wheels: Int? { get } var doors: Int? { get } func setFrame(_ frame: String) -> VehicleBuilder func setEngine(_ engine: String) -> VehicleBuilder func setWheels(_ frame: Int) -> VehicleBuilder func setDoors(_ frame: Int) -> VehicleBuilder func build() -> Vehicle } class CarBuilder: VehicleBuilder { var frame: String? var engine: String? var wheels: Int? var doors: Int? func setFrame(_ frame: String) -> VehicleBuilder { self.frame = frame return self } func setEngine(_ engine: String) -> VehicleBuilder { self.engine = engine return self } func setWheels(_ wheels: Int) -> VehicleBuilder { self.wheels = wheels return self } func setDoors(_ doors: Int) -> VehicleBuilder { self.doors = doors return self } func build() -> Vehicle { return Vehicle(frame: self.frame ?? "", engine: self.engine ?? "", wheels: self.wheels ?? 0, doors: self.doors ?? 0) } } class MotorcycleBuilder: VehicleBuilder { var frame: String? var engine: String? var wheels: Int? var doors: Int? func setFrame(_ frame: String) -> VehicleBuilder { self.frame = "Motorcycle - " + frame return self } func setEngine(_ engine: String) -> VehicleBuilder { self.engine = "Motorcycle - " + engine return self } func setWheels(_ wheels: Int) -> VehicleBuilder { self.wheels = wheels return self } func setDoors(_ doors: Int) -> VehicleBuilder { self.doors = doors return self } func build() -> Vehicle { return Vehicle(frame: self.frame ?? "", engine: self.engine ?? "", wheels: self.wheels ?? 0, doors: self.doors ?? 0) } } struct Vehicle { var frame: String var engine: String var wheels: Int var doors: Int } /*: ### Usage Chained builder */ let car = CarBuilder() .setFrame("Frame") .setEngine("Engine") .setWheels(4) .setDoors(4) .build() print(car) /*: ### Usage Using a director */ let motorcycleBuilder = MotorcycleBuilder() .setFrame("Frame") .setEngine("Engine") .setWheels(4) .setDoors(4) let motorcycle = Shop().build(builder: motorcycleBuilder) print(motorcycle) /*: ## Factory Method The factory method pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time. ### Implementation */ protocol Shoe { var price: Double { get set } var weight: Float { get set } var type: String { get set } } protocol Ball { var price: Double { get set } } struct RunningShoe: Shoe { var price: Double var weight: Float var type: String } struct SoccerBall: Ball { var price: Double } struct BasketballBall: Ball { var price: Double } protocol SportsFactory { func makeShoe() -> Shoe func makeSoccerBall() -> Ball func makeBasketballBall() -> Ball } class NikeFactory: SportsFactory { func makeShoe() -> Shoe { return RunningShoe(price: 100.0, weight: 11.4, type: "Neutral") } func makeSoccerBall() -> Ball { return SoccerBall(price: 80) } func makeBasketballBall() -> Ball { return BasketballBall(price: 50) } } class AdidasFactory: SportsFactory { func makeShoe() -> Shoe { return RunningShoe(price: 200.0, weight: 11.0, type: "Neutral") } func makeSoccerBall() -> Ball { return SoccerBall(price: 100) } func makeBasketballBall() -> Ball { return BasketballBall(price: 60) } } /*: ### Usage */ let creators: [SportsFactory] = [NikeFactory(), AdidasFactory()] for creator in creators { let soccerBall = creator.makeSoccerBall() let basketballBall = creator.makeBasketballBall() print(soccerBall.price) print(basketballBall.price) } /*: ## Object Pool The object pool pattern can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low. ### Implementation */ struct MagicObject { let name: String let serialNumber: Int var occupier: [String] = [] var borrowedCount: Int = 0 } class Pool<T> { var magicObjects = [T]() private let arrayQ = DispatchQueue(label: "array") private let semaphore: DispatchSemaphore init(items: [T]) { magicObjects.reserveCapacity(magicObjects.count) for item in items { magicObjects.append(item) } // create a counter semaphore for the available items in the pool semaphore = DispatchSemaphore(value: items.count) } func getFromPool() -> T? { var result: T? // the semaphore count is decreased each time when the wait is called. If the count is 0, the function will block if semaphore.wait(timeout: .distantFuture) == DispatchTimeoutResult.success { if magicObjects.count > 0 { arrayQ.sync { result = self.magicObjects.remove(at: 0) } } } return result } func returnToPool(item: T) { arrayQ.sync { self.magicObjects.append(item) // increase the counter by 1 self.semaphore.signal() // DispatchSemaphore.signal(self.semaphore)() } } } extension Int { func times(action: (Int)->()) { for i in 0..<self { action(i) } } } class MagicHouse { private let pool: Pool<MagicObject> static var sharedInstance = MagicHouse() static var magicDebtInfo: [(String, Int, String)] = [] private init() { var magicObjects:[MagicObject] = [] 2.times { magicObjects.append(MagicObject(name: "Red Diamond", serialNumber: $0, occupier: [], borrowedCount: 0)) } 3.times { magicObjects.append(MagicObject(name: "Blue Heart", serialNumber: $0, occupier: [], borrowedCount: 0)) } self.pool = Pool(items: magicObjects) } static func lendMagicObject(occupier: String) -> MagicObject? { var magicObject = sharedInstance.pool.getFromPool() if magicObject != nil { magicObject!.occupier.append(occupier) magicObject!.borrowedCount += 1 magicDebtInfo.append((magicObject!.name, magicObject!.serialNumber, occupier)) print("\(occupier) is borrowing \(magicObject!.name) #\(magicObject!.serialNumber)") } return magicObject } static func receiveMagicObject(obj: MagicObject) { magicDebtInfo = magicDebtInfo.filter { $0.0 != obj.name && $0.1 != obj.serialNumber } sharedInstance.pool.returnToPool(item: obj) print("\(obj.occupier.last!) returning \(obj.name) #\(obj.serialNumber)") } static func printReport() { print("\nShow Report: Magic House currently has \(sharedInstance.pool.magicObjects.count) magic object(s) in stock") sharedInstance.pool.magicObjects.forEach { print("\($0.name) #\($0.serialNumber) \nBorrowed \($0.borrowedCount) time(s) by \($0.occupier)") } if magicDebtInfo.count > 0 { print("\nMagic Objects currently lent out:") magicDebtInfo.forEach { print("\($0.0) #\($0.1) by \($0.2)") } } } } /*: ### Usage */ let queue = DispatchQueue(label: "workQ", attributes: .concurrent) let group = DispatchGroup() print("\n------Starting test...") for i in 1...7 { queue.async(group: group, execute: DispatchWorkItem(block: { if let obj = MagicHouse.lendMagicObject(occupier: "person #\(i)") { Thread.sleep(forTimeInterval: Double(arc4random_uniform(10))) MagicHouse.receiveMagicObject(obj: obj) } })) } _ = group.wait(timeout: .distantFuture) _ = MagicHouse.lendMagicObject(occupier: "William") _ = MagicHouse.lendMagicObject(occupier: "Tato") MagicHouse.printReport() /*: ## Prototype The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient. ### Implementation */ protocol TextScheme { var font: UIFont { get set } var color: UIColor { get set } var text: String { get set} func clone() -> Paragraph } class Paragraph: TextScheme { var font: UIFont var color: UIColor var text: String init(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = .darkText, text: String = "") { self.font = font self.color = color self.text = text } func clone() -> Paragraph { return Paragraph(font: self.font, color: self.color, text: self.text) } } /*: ### Usage */ let base = Paragraph() let title = base.clone() title.font = UIFont.systemFont(ofSize: 18) title.text = "This is the title" let first = base.clone() first.text = "This is the first paragraph" let second = base.clone() second.text = "This is the second paragraph" print(first) print(second) /*: ## Simple Factory The simple factory pattern allows interfaces for creating objects without exposing the object creation logic to the client. ### Implementation */ enum VideoGameType { case adventure, combat } protocol VideoGame { func play() } class SuperMario : VideoGame { func play() { } } class StreetFighter: VideoGame { func play() { } } class SimpleFactory { static func createVideoGame(type: VideoGameType) -> VideoGame { switch type { case .adventure: return SuperMario() case .combat: return StreetFighter() } } } /*: ### Usage */ let superMario = SimpleFactory.createVideoGame(type: .adventure) superMario.play() let streetFighter = SimpleFactory.createVideoGame(type: .combat) streetFighter.play() /*: ## Singleton The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance. There are very few applications, do not overuse this pattern! ### Implementation */ enum LogLevel: Int { case verbose = 0 case debug = 1 case info = 2 case warning = 3 case error = 4 } enum LogTag: String { case observable case model case viewModel case view } protocol Loggable { static func v(tag: LogTag, message: String) static func d(tag: LogTag, message: String) static func i(tag: LogTag, message: String) static func w(tag: LogTag, message: String) static func e(tag: LogTag, message: String) } extension Loggable { static func v(tag: LogTag, message: String) { Logger.default.log(level: .verbose, tag: tag, message: message) } static func d(tag: LogTag, message: String) { Logger.default.log(level: .debug, tag: tag, message: message) } static func i(tag: LogTag, message: String) { Logger.default.log(level: .info, tag: tag, message: message) } static func w(tag: LogTag, message: String) { Logger.default.log(level: .warning, tag: tag, message: message) } static func e(tag: LogTag, message: String) { Logger.default.log(level: .error, tag: tag, message: message) } } class Log: Loggable {} class Logger { static let `default` = Logger() private init() { // Private initialization to ensure just one instance is created. } func log(level: LogLevel, tag: LogTag, message: String) { print("\(level.rawValue)/\(tag.rawValue): ", message) } } /*: ### Usage */ Log.i(tag: .model, message: "info")
25.867257
376
0.646664
09e2a5851761a64430bcfdf828bcb17f31c10ef7
716
class Str { var value: Str } // rdar://problem/58663066 // Test a environment where stdlib is not found. // Completion should return zero result. // RUN: %empty-directory(%t/rsrc) // RUN: %empty-directory(%t/sdk) // RUN: not %sourcekitd-test \ // RUN: -req=global-config -req-opts=completion_max_astcontext_reuse_count=0 \ // RUN: -req=complete -pos=4:1 %s -- %s -resource-dir %t/rsrc -sdk %t/sdk 2>&1 | %FileCheck %s // RUN: not %sourcekitd-test \ // RUN: -req=complete -pos=4:1 %s -- %s -resource-dir %t/rsrc -sdk %t/sdk == \ // RUN: -req=complete -pos=4:1 %s -- %s -resource-dir %t/rsrc -sdk %t/sdk 2>&1 | %FileCheck %s // CHECK: error response (Request Failed): failed to load the standard library
35.8
96
0.656425
de75a52a2cfc336064b1c79ad364afaa1ca31f61
723
// // SwipeReturnable.swift // HackathonStarter // // Created by 田中 達也 on 2016/07/21. // Copyright © 2016年 tattn. All rights reserved. // import UIKit protocol SwipeReturnable: class { func addSwipeReturnGesture() } extension SwipeReturnable where Self: UIViewController { func addSwipeReturnGesture() { let gestureToRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeBack)) gestureToRight.direction = UISwipeGestureRecognizerDirection.right view.addGestureRecognizer(gestureToRight) } } extension UIViewController: SwipeReturnable {} extension UIViewController { func swipeBack() { navigationController?.popViewController(animated: true) } }
24.1
97
0.737206
dedef696d14df447b73da5993441d866f28141f3
2,831
// // AscCollection+Op.swift // OrderedCollection // // Created by Vitali Kurlovich on 1/19/19. // public extension AscCollection { static func + <Other>(lhs: AscCollection, rhs: Other) throws -> AscArray<Element> where Other: Sequence, Element == Other.Element { var iterator = rhs.makeIterator() guard let right = iterator.next() else { return AscArray<Element>(buffer: Array(lhs.buffer)) } guard let left = lhs.last else { guard isAscOrdered(rhs) else { throw OrderedCollectionError.IncorrectValueError } return AscArray<Element>(buffer: Array(rhs)) } guard left <= right, isAscOrdered(rhs) else { throw OrderedCollectionError.IncorrectValueError } var buffer = Array(lhs.buffer) buffer.append(contentsOf: rhs) return AscArray<Element>(buffer: buffer) } static func + <Other>(lhs: AscCollection, rhs: Other) throws -> AscArray<Element> where Other: BidirectionalCollection, Element == Other.Element { guard let right = rhs.first else { return AscArray<Element>(buffer: Array(lhs.buffer)) } guard let left = lhs.last else { guard isAscOrdered(rhs) else { throw OrderedCollectionError.IncorrectValueError } return AscArray<Element>(buffer: Array(rhs)) } guard left <= right, isAscOrdered(rhs) else { throw OrderedCollectionError.IncorrectValueError } var buffer = Array(lhs.buffer) buffer.append(contentsOf: rhs) return AscArray<Element>(buffer: buffer) } static func + (lhs: AscCollection, rhs: AscCollection) throws -> AscArray<Element> { guard let right = rhs.first else { return AscArray<Element>(buffer: Array(lhs.buffer)) } guard let left = lhs.last else { return AscArray<Element>(buffer: Array(rhs.buffer)) } guard left <= right else { throw OrderedCollectionError.IncorrectValueError } var buffer = Array(lhs.buffer) buffer.append(contentsOf: rhs.buffer) return AscArray<Element>(buffer: buffer) } } public extension AscCollection where Buffer: MutationCollectionAppend, Buffer: Equatable { static func += <Other>(lhs: inout AscCollection, rhs: Other) throws where Other: Sequence, Element == Other.Element { try lhs.append(contentsOf: rhs) } static func += <Other>(lhs: inout AscCollection, rhs: Other) throws where Other: BidirectionalCollection, Element == Other.Element { try lhs.append(contentsOf: rhs) } static func += (lhs: inout AscCollection, rhs: AscCollection) throws { try lhs.append(contentsOf: rhs) } }
32.170455
150
0.62946
1dbcd5bbcd25db82587232686d5cf9b6f5977d48
1,283
// // MemoComposeViewModel.swift // RxMemo // // Created by RadCns_KIM_TAEWON on 2021/07/06. // import Foundation import RxSwift import RxCocoa import Action class MemoComposeViewModel: CommonViewModel { private let content: String? var initialText: Driver<String?> { return Observable.just(content).asDriver(onErrorJustReturn: nil) } let saveAction: Action<String, Void> let cancelAction: CocoaAction init(title: String, content: String? = nil, sceneCoordinator: SceneCoordinatorType, storage: MemoStorageType, saveAction: Action<String,Void>? = nil, cancelAction: CocoaAction? = nil) { self.content = content self.saveAction = Action<String, Void> { input in if let action = saveAction { action.execute(input) } return sceneCoordinator.close(animated: true).asObservable().map { _ in } } self.cancelAction = CocoaAction { if let action = cancelAction { action.execute(()) } return sceneCoordinator.close(animated: true).asObservable().map { _ in } } super.init(title: title, sceneCoordinator: sceneCoordinator, storage: storage) } }
29.159091
189
0.623539
d7c2a6566a988e82b33c3fba2597365aa3b8f6f4
253
// // AppLovinViewController.swift // TeadsSampleApp // // Created by Vincent Saluzzo on 15/03/2022. // Copyright © 2022 Teads. All rights reserved. // import Foundation class AppLovinViewController: TeadsViewController { var isMREC = false }
18.071429
51
0.731225
3a0adc3b274db0d3d40ae6a3d663c6c348ef618e
1,262
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache 2.0 */ import Foundation import FireMock enum UpdateCustomerMock: FireMockProtocol { case success case resourceNotFound var afterTime: TimeInterval { return 1.0 } var statusCode: Int { switch self { case .success: return 200 case .resourceNotFound: return 404 } } func mockFile() -> String { switch self { case .success: return R.file.successResultJson.fullName case .resourceNotFound: return R.file.emptyResponseJson.fullName } } } extension UpdateCustomerMock { static func register(mock: UpdateCustomerMock, projectUnit: ServiceUnit) { guard let service = projectUnit.service(for: ProjectServiceType.customerUpdate.rawValue) else { Logger.shared.warning("Can't find customer update service endpoint to mock") return } guard let url = URL(string: service.serviceEndpoint) else { Logger.shared.warning("Can't create customer update regex") return } FireMock.register(mock: mock, forURL: url, httpMethod: .put) } }
24.745098
103
0.625198
03d45afb3df00f774a878046627510415e118f32
2,741
// // ContentView.swift // Touchdown // // Created by Renato Rocha on 07/06/21. // import SwiftUI struct ContentView: View { // MARK: - PROPERTIES @EnvironmentObject var shop: Shop // MARK: - BODY var body: some View { ZStack { if shop.showingProduct == false && shop.selectedProduct == nil { VStack(spacing: 0) { NavigationBarView() .padding(.horizontal, 15) .padding(.bottom) .padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top) .background(Color.white) .shadow(color: Color.black.opacity(0.05), radius: 5, x: 0, y: 5) ScrollView(.vertical, showsIndicators: false, content: { VStack(spacing: 0) { FeaturedTabView() .frame(minHeight: 250) .padding(.vertical, 20) CategoryGridView() TitleView(title: "Helmets") LazyVGrid(columns: gridLayout, spacing: 15, content: { ForEach(products) { product in ProductItemView(product: product) .onTapGesture { feedback.impactOccurred() withAnimation(.easeOut) { shop.selectedProduct = product shop.showingProduct = true } } } //: ForEach }) //: LazyVGrid .padding(15) TitleView(title: "Brands") BrandGridView() FooterView() .padding(.horizontal) } //: VStack }) //: ScrollView } //: VStack .background(colorBackground.ignoresSafeArea(.all, edges: .all)) } else { ProductDetailView() } } //: ZStack .ignoresSafeArea(.all, edges: .top) } } // MARK: - PREVIEW struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(Shop()) } }
37.547945
94
0.383072
645dd1da0d868049b7efe9b5c6ef5784e28aebd6
1,722
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation extension Process { enum TibsProcessError: Error { case nonZeroExit(TerminationReason, Int32) case invalidUTF8Output(Data) } /// Runs a subprocess and returns its output as a String if it has a zero exit. static func tibs_checkNonZeroExit( arguments: [String], environment: [String: String]? = nil ) throws -> String { let p = Process() let out = Pipe() if #available(macOS 10.13, *) { p.executableURL = URL(fileURLWithPath: arguments[0], isDirectory: false) } else { p.launchPath = arguments[0] } p.arguments = Array(arguments[1...]) if let environment = environment { p.environment = environment } p.standardOutput = out if #available(macOS 10.13, *) { try p.run() } else { p.launch() } let data = out.fileHandleForReading.readDataToEndOfFile() p.waitUntilExit() if p.terminationReason != .exit || p.terminationStatus != 0 { throw TibsProcessError.nonZeroExit(p.terminationReason, p.terminationStatus) } guard let str = String(data: data, encoding: .utf8) else { throw TibsProcessError.invalidUTF8Output(data) } return str } }
28.229508
82
0.609175
6a0625ebc6ed1f074565d86a49a9a87c256c8fe2
2,133
// // DetailViewModel.swift // iOSEngineerCodeCheck // // Created by 肥沼英里 on 2022/01/23. // Copyright © 2022 YUMEMI Inc. All rights reserved. // import Foundation import RxOptional import RxRelay import RxSwift protocol DetailViewModelInput { func configureWith(repository: RepositoryCodable) } protocol DetailViewModelOutput { var titleText: BehaviorRelay<String> { get } var languageText: BehaviorRelay<String> { get } var stargazersCountText: BehaviorRelay<String> { get } var watchersCountText: BehaviorRelay<String> { get } var forksCountText: BehaviorRelay<String> { get } var issuesCountText: BehaviorRelay<String> { get } var avatarImageURL: BehaviorRelay<URL?> { get } var htmlURL: BehaviorRelay<URL?> { get } } final class DetailViewModel: DetailViewModelInput, DetailViewModelOutput { var input: DetailViewModelInput { return self } var output: DetailViewModelOutput { return self } private let disposeBag = DisposeBag() // Input func configureWith(repository: RepositoryCodable) { titleText.accept(repository.fullName) languageText.accept("Written in \(repository.language ?? "--")") stargazersCountText.accept("\(repository.stargazersCount) stars") watchersCountText.accept("\(repository.watchersCount) watchers") forksCountText.accept("\(repository.forksCount) forks") issuesCountText.accept("\(repository.openIssuesCount) open issues") avatarImageURL.accept(URL(string: repository.owner.avatarUrl)) htmlURL.accept(URL(string: repository.htmlURL)) } // Output lazy var titleText = BehaviorRelay<String>(value: "") lazy var languageText = BehaviorRelay<String>(value: "") lazy var stargazersCountText = BehaviorRelay<String>(value: "") lazy var watchersCountText = BehaviorRelay<String>(value: "") lazy var forksCountText = BehaviorRelay<String>(value: "") lazy var issuesCountText = BehaviorRelay<String>(value: "") lazy var avatarImageURL = BehaviorRelay<URL?>(value: nil) lazy var htmlURL = BehaviorRelay<URL?>(value: nil) }
36.775862
75
0.715424
8f491fe2454a9b5bcc272a2c8de4d30a40d2d7ff
1,453
import XCTest @testable import CountriesQL final class ContinentListCoordinatorTests: XCTestCase { private var router = AppRouterMock() private var countryCoordinator = BaseCoordinatorMock() private var viewModel: ContinentListViewModelMock! private var sut: ContinentListCoordinator! override func setUpWithError() throws { viewModel = ContinentListViewModelMock() sut = ContinentListCoordinator(router: router, viewModel: viewModel, countryCoordinator: countryCoordinator) } func testStart() { sut.start(onFinish: {}) XCTAssertTrue(viewModel.coordinatorDelegate === sut) XCTAssertTrue(router.viewController is ContinentListViewController) XCTAssertTrue(router.isAnimated!) XCTAssertTrue(router.onNavigateBack != nil) } func testCountryCoordinator() { sut.start(onFinish: {}) viewModel.rowSelected(IndexPath(row: 0, section: 0)) XCTAssertEqual(countryCoordinator.startCounter, 1) } } private final class ContinentListViewModelMock: ContinentListViewModelProtocol { var delegate: ContinentListViewModelDelegate? var coordinatorDelegate: ContinentListCoordinatorDelegate? var continents: [Continent] = [] func requestData() {} func rowSelected(_ indexPath: IndexPath) { coordinatorDelegate?.startCountryListScene(continent: .dummy) } }
30.270833
116
0.705437
892ff37aff27fae6de34f972b48a3dc9aa481fcb
1,131
import Foundation public protocol NetworkEngine { func load<A: Decodable>(_ request: URLRequest, as type: A.Type, completion: @escaping (Result<A, NetworkingError>) -> Void) } public enum NetworkingError: Error { case badRequest case resourceParsing case decoding case badResponse(String) } extension URLSession { public func load<A: Decodable>(_ resourse: Resource<A>, as type: A.Type = A.self, completion: @escaping (Result<A, NetworkingError>) -> Void) { dataTask(with: resourse.request) { (data, response, error) in if let error = error { completion(.failure(.badResponse(error.localizedDescription))) return } guard let _ = response, let data = data else { completion(.failure(.badResponse("data is nil"))) return } guard let value = try? JSONDecoder().decode(A.self, from: data) else { completion(.failure(.decoding)) return } completion(.success(value)) }.resume() } }
30.567568
147
0.579134
fe6326c55258da3ea3fe10354b04e1dd21d0e2c0
414
import SwiftWLR import Foundation import Logging LoggingSystem.bootstrap(WLRLogHandler.init) let logger = Logger(label: "tinywl") let server = WaylandServer() let state = TinyWLState(for: server) logger.info("Running Wayland compositor on WAYLAND_DISPLAY=\(server.socket)") let _ = try! Process.run( URL(fileURLWithPath: "/bin/sh", isDirectory: false), arguments: ["-c", "alacritty"] ) server.run()
19.714286
77
0.736715
4aa770421cd800f29237c6e9ff6f5d4c4c28760a
414
// // Login.swift // TheMovieManager // // Created by Owen LaRosa on 8/13/18. // Copyright © 2018 Udacity. All rights reserved. // import Foundation struct LoginRequest: Codable { let username : String let password: String let requestToken : String enum CodingKeys: String, CodingKey { case username case password case requestToken = "request_token" } }
18
50
0.642512
6990666fd683aa751f52bb43ae35a912ccca24fd
498
// // CashbackBalanceRequest.swift // Hugo // // Created by Jose Francisco Rosales Hernandez on 02/02/21. // Copyright © 2021 Clever Mobile Apps. All rights reserved. // import Foundation struct CashbackBalanceRequest: APIRequest { public typealias Response = CashbackBalanceResponse public var resourceName: String { return "api/v2/cashback/global?client_id=\(client_id)&country=\(country_name)" } public let client_id: String public let country_name: String }
23.714286
86
0.728916
e29bda93df58f6a5d5bddd545dc4b1402d955979
1,321
// // SampleConverter.swift // SwiftOpusPlayer // // Created by Kartik Venugopal on 8/4/21. // import AVFoundation class OpusSampleConverter { /// /// Converts from the format of samples produced by Opusfile (i.e. interleaved) to the canonical audio format /// required by AVAudioEngine for playback (non-interleaved aka planar). /// /// Returns an AVAudioPCMBuffer suitable for playback, if the conversion succeeds. /// static func convertInterleavedToPlanar(forFile file: OpusFile, from srcBuffer: AVAudioPCMBuffer) -> AVAudioPCMBuffer? { let targetFormat = AVAudioFormat(standardFormatWithSampleRate: OpusFile.standardSampleRate, channelLayout: file.channelLayout) guard let converter = AVAudioConverter(from: srcBuffer.format, to: targetFormat), let targetBuffer = AVAudioPCMBuffer(pcmFormat: targetFormat, frameCapacity: srcBuffer.frameLength) else { NSLog("Couldn't create target buffer.") return nil } do { try converter.convert(to: targetBuffer, from: srcBuffer) return targetBuffer } catch { NSLog("\nConversion failed: \(error)") } return nil } }
31.452381
123
0.628312
337ea2a36029db55a7d79766d4eb3fa86d54746e
865
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Amplify import AWSComprehend extension AWSComprehendEntityType { func toAmplifyEntityType() -> EntityType { switch self { case .person: return .person case .location: return .location case .organization: return .organization case .commercialItem: return .commercialItem case .event: return .event case .date: return .date case .quantity: return .quantity case .title: return .title case .other: return .other case .unknown: return .unknown @unknown default: return .unknown } } }
21.625
47
0.545665
79f71b2ef1eabfa209ba92f9193134dc28a50487
1,667
// // OwnerAndVIPCommentHandlerTest.swift // DeuxCheVauxTests // // Created by Чайка on 2018/06/25. // Copyright © 2018 Чайка. All rights reserved. // import XCTest class OwnerCommandHandlerTest: XCTestCase { private var cookie: HTTPCookie! override func setUp() { super.setUp() cookie = HTTPCookie(properties: [HTTPCookiePropertyKey.name: "user_session", HTTPCookiePropertyKey.value: user_session_value, HTTPCookiePropertyKey.domain: "nicovideo.jp", HTTPCookiePropertyKey.path: "/"]) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test01_allocation() { let operatorCommentor: OwnerCommandHandler = OwnerCommandHandler(program: liveNumber, cookies: [cookie]) XCTAssertNotNil(operatorCommentor, "operatorCommentor can not initialized") } func test02_ownerComment() { let operatorCommentor: OwnerCommandHandler = OwnerCommandHandler(program: liveNumber, cookies: [cookie]) do { try operatorCommentor.postOwnerComment(comment: "test comment", name: "Чайка", color: "green", isPerm: false) Thread.sleep(forTimeInterval: 10) try operatorCommentor.postOwnerComment(comment: "/perm test comment", color: "red", isPerm: false) Thread.sleep(forTimeInterval: 20) operatorCommentor.clearOwnerComment() } catch { XCTAssertTrue(false, "JSON serialization throw error") } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
32.686275
207
0.718656
50aed7fdea63f0ff1124c4595ae85a8b823770f7
2,266
// // SearchViewController.swift // Tumblr // // Created by Kevin Wong on 10/10/15. // Copyright © 2015 Kevin Wong. All rights reserved. // import UIKit class SearchViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var searchFeedView: UIImageView! @IBOutlet weak var loader: UIImageView! var loading_1: UIImage! var loading_2: UIImage! var loading_3: UIImage! var images: [UIImage]! var animatedImage: UIImage! override func viewDidLoad() { super.viewDidLoad() scrollView.contentSize = searchFeedView.image!.size scrollView.alpha = 0 loader.alpha = 1 } override func viewDidAppear(animated: Bool) { delay(2) { self.loader.alpha = 0 UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView.alpha = 1 }) } } override func viewDidDisappear(animated: Bool) { scrollView.alpha = 0 } override func viewWillAppear(animated: Bool) { loading_1 = UIImage(named: "loading-1") loading_2 = UIImage(named: "loading-2") loading_3 = UIImage(named: "loading-3") images = [loading_1, loading_2, loading_3] animatedImage = UIImage.animatedImageWithImages(images, duration: 1.0) loader.alpha = 1 loader.image = animatedImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
26.97619
106
0.612533
69782ff08f80ef09babfdcfe1f0833b5a1551380
248
#if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public protocol AutoSizeCalculable { func setAutoSizingRect(_ rect: CGRect, margins: PEdgeInsets) func autoSizeThatFits(_ size: CGSize, layoutClosure: () -> Void) -> CGSize }
22.545455
78
0.729839
20085b4088e60e83e06a1e32b102962e78712852
5,125
/// A struct used to hold/manipulate permissions in a C-compatible way for the mode_t struct public struct FilePermissions: OptionSet, ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, Hashable { public typealias StringLiteralType = String public typealias IntegerLiteralType = OSUInt public private(set) var rawValue: IntegerLiteralType /// Read, write, and execute permissions public static let all: FilePermissions = 0o7 /// Read only permissions public static let read: FilePermissions = 0o4 /// Write only permissions public static let write: FilePermissions = 0o2 /// Execute only permissions public static let execute: FilePermissions = 0o1 /// No permissions public static let none: FilePermissions = 0 /// Read and write permissions public static let readWrite: FilePermissions = [.read, .write] /// Read and execute permissions public static let readExecute: FilePermissions = [.read, .execute] /// Write and execute permissions public static let writeExecute: FilePermissions = [.write, .execute] /// All permissions public static let readWriteExecute: FilePermissions = .all // If the permissions include read permissions public var isReadable: Bool { return contains(.read) } // If the permissions include write permissions public var isWritable: Bool { return contains(.write) } // If the permissions include execute permissions public var isExecutable: Bool { return contains(.execute) } /// If the permissions are empty public var hasNone: Bool { return !(isReadable || isWritable || isExecutable) } public init(rawValue: IntegerLiteralType) { self.rawValue = rawValue } public init(_ perms: FilePermissions...) { rawValue = perms.reduce(0) { $0 | $1.rawValue } } /** Initialize from a Unix permissions string (3 chars 'rwx' 'r--' '-w-' '--x') */ public init(_ value: String) { self.init(rawValue: 0) guard value.count == 3 else { return } for char in value { switch char { case "r": rawValue |= 0o4 case "w": rawValue |= 0o2 case "x", "S", "t": rawValue |= 0o1 default: continue } } } public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(integerLiteral value: IntegerLiteralType) { self.init(rawValue: value) } /// Returns the inverse FilePermissions with all bits flipped public static prefix func ~ (lhs: FilePermissions) -> FilePermissions { // NOTing flips too many bits and may cause rawValues of equivalent // FilePermissionss to no longer be equivalent return FilePermissions(rawValue: ~lhs.rawValue & FilePermissions.all.rawValue) } /// Returns a FilePermissions with the bits contained in either mode public static func | (lhs: FilePermissions, rhs: FilePermissions) -> FilePermissions { return FilePermissions(rawValue: lhs.rawValue | rhs.rawValue) } /// Returns a FilePermissions with the bits contained in either mode public static func | (lhs: FilePermissions, rhs: IntegerLiteralType) -> FilePermissions { return FilePermissions(rawValue: lhs.rawValue | rhs) } /// Sets the FilePermissions with the bits contained in either mode public static func |= (lhs: inout FilePermissions, rhs: FilePermissions) { lhs.rawValue = lhs.rawValue | rhs.rawValue } /// Sets the FilePermissions with the bits contained in either mode public static func |= (lhs: inout FilePermissions, rhs: IntegerLiteralType) { lhs.rawValue = lhs.rawValue | rhs } /// Returns a FilePermissions with only the bits contained in both modes public static func & (lhs: FilePermissions, rhs: FilePermissions) -> FilePermissions { return FilePermissions(rawValue: lhs.rawValue & rhs.rawValue) } /// Returns a FilePermissions with only the bits contained in both modes public static func & (lhs: FilePermissions, rhs: IntegerLiteralType) -> FilePermissions { return FilePermissions(rawValue: lhs.rawValue & rhs) } /// Sets the FilePermissions with only the bits contained in both modes public static func &= (lhs: inout FilePermissions, rhs: FilePermissions) { lhs.rawValue = lhs.rawValue & rhs.rawValue } /// Sets the FilePermissions with only the bits contained in both modes public static func &= (lhs: inout FilePermissions, rhs: IntegerLiteralType) { lhs.rawValue = lhs.rawValue & rhs } } extension FilePermissions: CustomStringConvertible { public var description: String { var perms: [String] = [] if isReadable { perms.append("read") } if isWritable { perms.append("write") } if isExecutable { perms.append("execute") } if perms.isEmpty { perms.append("none") } return "\(type(of: self))(\(perms.joined(separator: ", ")))" } }
36.870504
109
0.665171
1d18d2191994602ccf31b8c6f18cd37516144a04
316
// // Common.swift // douyuTV // // Created by free on 17/2/19. // Copyright © 2017年 free. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH : CGFloat = 44 let kScreenW = UIScreen.main.bounds.width let KscreenH = UIScreen.main.bounds.height
16.631579
48
0.705696
f4e145ca3948b544cb79400fb12e63f3bd993bb3
4,040
// // BusinessesViewController.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BusinessesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if businesses != nil{ return businesses.count }else{ return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = myTableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell cell.business = businesses[indexPath.row] return cell } /* func scrollViewDidScroll(_ scrollView: UIScrollView) { if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = myTableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - myTableView.bounds.size.height - 1000; // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && myTableView.dragging) { isMoreDataLoading = true reloadSearch(++offset); } } } */ /* func reloadTable() { loadingSpinner.stopAnimating(); myTableView.reloadData(); myTableView.alpha = 1; } func reloadSearch(offset: Int = 0) { self.offset = offset; var completion = { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses self.searchLoadComplete(); }; if(self.offset > 0) { completion = { (businesses: [Business]!, error: NSError!) -> Void in self.businesses.appendContentsOf(businesses); self.searchLoadComplete(); }; } else { myTableView.alpha = 0; loadingSpinner.startAnimating(); } if let query = searchBar.text { searchTerm = query; } appDelegate.search_term = searchTerm; Business.search(searchTerm, offset: offset, completion: completion); } */ @IBOutlet var myTableView: UITableView! var businesses: [Business]! override func viewDidLoad() { super.viewDidLoad() myTableView.dataSource = self myTableView.delegate = self myTableView.rowHeight = UITableViewAutomaticDimension myTableView.estimatedRowHeight = 120 myTableView.separatorInset = UIEdgeInsets.zero let searchBar = UISearchBar() searchBar.sizeToFit() navigationItem.titleView = searchBar Business.searchWithTerm(term: "Thai", completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.myTableView.reloadData() if let businesses = businesses { for business in businesses { print(business.name!) print(business.address!) } } } ) /* Example of Yelp search with more search options specified Business.searchWithTerm(term: "Restaurants", sort: .distance, categories: ["asianfusion", "burgers"]) { (businesses, error) in self.businesses = businesses for business in self.businesses { print(business.name!) print(business.address!) } } */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
33.666667
135
0.582178
1cd20966a55cce17fe3db097ea6d212a501d3e59
1,657
// // ViewController.swift // DPLogExample // // Created by 张鹏 on 2018/4/2. // Copyright © 2018年 [email protected]. All rights reserved. // import UIKit import DPLog enum MyError: Error { case ahahha case okokokok } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() Log.error("My Error") Log.debug("My Debug") Log.warning("My Warning") Log.info("My Info") Log.error(MyError.okokokok) let error = NSError(domain: "dp.log.demo", code: 100001, userInfo: [NSLocalizedFailureReasonErrorKey: "Error Demo", NSLocalizedDescriptionKey: "Just a Demo"]) Log.error(error) ViewController.demo() DispatchQueue.concurrentPerform(iterations: 10) { (index) in guard let l = [DPLog.Message.Level.debug, DPLog.Message.Level.info, DPLog.Message.Level.warning, DPLog.Message.Level.error].randomElement() else { return } switch l { case .debug: Log.debug("并发-DEBUG") case .info: Log.info("并发-INFO") case .warning: Log.warning("并发-WARNING") case .error: Log.error("并发-ERROR") } } } class func demo() { Log.debug("测试一下下") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
25.106061
158
0.530477
e0ad04f483f3b302bf4f941316c51919ab15d045
1,684
// // Copyright 2019, 2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// A protocol that can be used as a queue or a stack with a backing datastore. All items stored in a datastore queue stack must be of the same type. public protocol DataStoreQueueStack { var count: Int { get } /// save item of type T /// - Parameter item: item to save. It is both append and push. func save(item: T) /// getFirstItem - queue peek /// - Returns: value of the first item added or nil. func getFirstItems(count: Int) -> [T]? /// getLastItem - stack peek. /// - Returns: value of the last item added or nil. func getLastItems(count: Int) -> [T]? /// removeFirstItem - queue get. It removes and returns the first item in the queue if it exists. /// - Returns: value of the first item in the queue. func removeFirstItems(count: Int) -> [T]? /// removeLastItem - stack pop. It removes and returns the last item item added if it exists. /// - Returns: value of the last item pushed onto the stack. func removeLastItems(count: Int) -> [T]? associatedtype T }
42.1
150
0.694181
ac6dce4aadd5ac6ca84cf16c967676bbda1eae8d
7,087
// // AudioEngine.swift // SwiftAudioPlayer // // Created by Tanha Kabir on 2019-01-29. // Copyright © 2019 Tanha Kabir, Jon Mercer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import AVFoundation protocol AudioEngineProtocol { var engine: AVAudioEngine { get set } func play() func pause() func seek(toNeedle needle: Needle) func invalidate() } protocol AudioEngineDelegate: AnyObject { func didEndPlaying() //for auto play func didError() } class AudioEngine: AudioEngineProtocol { weak var delegate:AudioEngineDelegate? let key:Key var engine = AVAudioEngine() var playerNode = AVAudioPlayerNode() var timer: Timer? static let defaultEngineAudioFormat: AVAudioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 2, interleaved: false)! var state:TimerState = .suspended enum TimerState { case suspended case resumed } var needle: Needle = -1 { didSet { if needle >= 0 && oldValue != needle { AudioClockDirector.shared.needleTick(key, needle: needle) } } } var duration: Duration = -1 { didSet { if duration >= 0 && oldValue != duration { AudioClockDirector.shared.durationWasChanged(key, duration: duration) } } } var playing : Bool = false var playingStatus: SAPlayingStatus? = nil { didSet { guard playingStatus != oldValue, let status = playingStatus else { return } if status == .ended { delegate?.didEndPlaying() } AudioClockDirector.shared.audioPlayingStatusWasChanged(key, status: status) } } var bufferedSecondsDebouncer: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, predictedDurationToLoad: Double.greatestFiniteMagnitude, isPlayable: false) var bufferedSeconds: SAAudioAvailabilityRange = SAAudioAvailabilityRange(startingNeedle: 0.0, durationLoadedByNetwork: 0.0, predictedDurationToLoad: Double.greatestFiniteMagnitude, isPlayable: false) { didSet { if bufferedSeconds.startingNeedle == 0.0 && bufferedSeconds.durationLoadedByNetwork == 0.0 { bufferedSecondsDebouncer = bufferedSeconds AudioClockDirector.shared.changeInAudioBuffered(key, buffered: bufferedSeconds) return } if bufferedSeconds.startingNeedle == oldValue.startingNeedle && bufferedSeconds.durationLoadedByNetwork == oldValue.durationLoadedByNetwork { return } if bufferedSeconds.durationLoadedByNetwork - DEBOUNCING_BUFFER_TIME < bufferedSecondsDebouncer.durationLoadedByNetwork { Log.debug("skipping pushing buffer: \(bufferedSeconds)") return } bufferedSecondsDebouncer = bufferedSeconds AudioClockDirector.shared.changeInAudioBuffered(key, buffered: bufferedSeconds) } } init(url: AudioURL, delegate:AudioEngineDelegate?, engineAudioFormat: AVAudioFormat) { self.key = url.key self.delegate = delegate engine.attach(playerNode) for node in SAPlayer.shared.audioModifiers { engine.attach(node) } if SAPlayer.shared.audioModifiers.count > 0 { var i = 0 let node = SAPlayer.shared.audioModifiers[i] engine.connect(playerNode, to: node, format: engineAudioFormat) i += 1 while i < SAPlayer.shared.audioModifiers.count { let lastNode = SAPlayer.shared.audioModifiers[i - 1] let currNode = SAPlayer.shared.audioModifiers[i] engine.connect(lastNode, to: currNode, format: engineAudioFormat) i += 1 } let finalNode = SAPlayer.shared.audioModifiers[SAPlayer.shared.audioModifiers.count - 1] engine.connect(finalNode, to: engine.mainMixerNode, format: engineAudioFormat) } else { engine.connect(playerNode, to: engine.mainMixerNode, format: engineAudioFormat) } engine.prepare() } deinit { timer?.invalidate() if state == .resumed { engine.stop() } } func updateIsPlaying() { if !bufferedSeconds.isPlayable { if bufferedSeconds.bufferingProgress > 0.999 { playingStatus = .ended } else { playingStatus = .buffering } return } let isPlaying = engine.isRunning && playerNode.isPlaying playingStatus = isPlaying ? .playing : .paused } func play() { playing = true // https://stackoverflow.com/questions/36754934/update-mpremotecommandcenter-play-pause-button if !engine.isRunning { do { try engine.start() } catch let error { Log.monitor(error.localizedDescription) } } playerNode.play() if state == .suspended { state = .resumed } } func pause() { playing = false // https://stackoverflow.com/questions/36754934/update-mpremotecommandcenter-play-pause-button playerNode.pause() engine.pause() if state == .resumed { state = .suspended } } func seek(toNeedle needle: Needle) { fatalError("No implementation for seek inAudioEngine, should be using streaming or disk type") } func invalidate() { } }
33.587678
212
0.609708
dd1ae356da805821677b7a30d4d4460010e346aa
461
import has_alias @_exported import struct_with_operators public func numeric(x: MyInt64) {} public func conditional(x: AliasWrapper.Boolean) {} public func longInt(x: Int.EspeciallyMagicalInt) {} public func numericArray(x: IntSlice) {} public protocol ExtraIncrementable { prefix func +++(base: inout Self) } extension SpecialInt : ExtraIncrementable {} public protocol DefaultInitializable { init() } extension SpecialInt : DefaultInitializable {}
20.954545
51
0.776573
561c9bf3a59ac48f8c7befaf9b17e4ba87df66da
1,221
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // import XCTest @testable import ENA class ExposureSubmissionHotlineViewControllerTest: XCTestCase { func testSetupView() { let vc = AppStoryboard.exposureSubmission.initiate(viewControllerType: ExposureSubmissionHotlineViewController.self) { coder -> UIViewController? in ExposureSubmissionHotlineViewController(coder: coder, coordinator: MockExposureSubmissionCoordinator()) } _ = vc.view XCTAssertNotNil(vc.tableView) XCTAssertEqual(vc.tableView.numberOfSections, 2) XCTAssertEqual(vc.tableView(vc.tableView, numberOfRowsInSection: 1), 5) } }
33.916667
150
0.772318
11662b9395f3fa127d4f1861ab742ef6516077bb
1,279
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 1791. Find Center of Star Graph // There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. // You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. // Example 1: // Input: edges = [[1,2],[2,3],[4,2]] // Output: 2 // Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center. // Example 2: // Input: edges = [[1,2],[5,1],[1,3],[1,4]] // Output: 1 // Constraints: // 3 <= n <= 10^5 // edges.length == n - 1 // edges[i].length == 2 // 1 <= ui, vi <= n // ui != vi // The given edges represent a valid star graph. func findCenter(_ edges: [[Int]]) -> Int { let n = edges.count + 1 var degree = [Int](repeating: 0, count: n + 1) for e in edges { degree[e[0]] += 1 degree[e[1]] += 1 } return degree.firstIndex(of: n - 1) ?? -1 } }
34.567568
214
0.577013
2f9372146c60cc3123560d8b0c8ef9999310f16d
4,020
// // Copyright © 2017 Slalom. All rights reserved. // import UIKit import CoreML import Vision import ImageIO class ViewController: UIViewController { @IBOutlet var classificationLabel: UILabel! @IBOutlet var imageView: UIImageView! private var detectionOverlay: CALayer! var inputImage: CIImage? override func viewDidLoad() { super.viewDidLoad() guard let image = imageView.image else { return } guard let ciImage = CIImage(image: image) else { fatalError("can't create CIImage from UIImage") } let orientation = CGImagePropertyOrientation(image.imageOrientation) inputImage = ciImage.oriented(forExifOrientation: Int32(orientation.rawValue)) // Show the image in the UI. imageView.image = image // Run the rectangle detector let handler = VNImageRequestHandler(ciImage: ciImage, orientation: orientation) DispatchQueue.global(qos: .userInteractive).async { do { try handler.perform([self.detectionRequest]) } catch { print(error) } } } lazy var detectionRequest: VNCoreMLRequest = { // Load the ML model through its generated class and create a Vision request for it. do { let model = try VNCoreMLModel(for: SlalomLogoClassifier().model) return VNCoreMLRequest(model: model, completionHandler: self.handleDetection) } catch { fatalError("can't load Vision ML model: \(error)") } }() func handleDetection(request: VNRequest, error: Error?) { guard let results = request.results, !results.isEmpty else { return } var strings: [String] = [] for observation in results where observation is VNRecognizedObjectObservation { guard let observation = observation as? VNRecognizedObjectObservation else { continue } let bestLabel = observation.labels.first! // Label with highest confidence let objectBounds = observation.boundingBox let pct = Float(Int(observation.confidence * 10000)) / 100 strings.append("\(pct)%") drawRectangle(detectedRectangle: objectBounds, identifier: bestLabel.identifier, confidence: observation.confidence) print(bestLabel.identifier, observation.confidence, objectBounds) } DispatchQueue.main.async { self.classificationLabel.text = strings.joined(separator: ", ") } } public func drawRectangle(detectedRectangle: CGRect, identifier: String, confidence: VNConfidence) { DispatchQueue.main.async { [unowned self] in let boundingBox = VNImageRectForNormalizedRect(detectedRectangle, Int(self.imageView.frame.width), Int(self.imageView.frame.height)) let layer = self.layerWithBounds(boundingBox, identifier: identifier, confidence: confidence) self.imageView.layer.addSublayer(layer) } } func layerWithBounds(_ rect: CGRect, identifier: String, confidence: VNConfidence) -> CALayer { let layer = CAShapeLayer() layer.bounds = rect layer.path = UIBezierPath(roundedRect: rect, cornerRadius: 8).cgPath layer.lineWidth = 3 if confidence < 0.45 { layer.lineDashPattern = [8,12] } switch identifier { case Label.buildLogo.rawValue: layer.strokeColor = UIColor(named: "BuildCyan")!.cgColor case Label.buildSquare.rawValue: layer.strokeColor = UIColor(named: "BuildCyan")!.cgColor default: layer.strokeColor = UIColor.red.cgColor } layer.shadowOpacity = 0.7 layer.shadowOffset = CGSize.zero layer.fillColor = UIColor.clear.cgColor layer.position = CGPoint(x: imageView.frame.midX, y: imageView.frame.midY) return layer } }
36.880734
144
0.636567
4b0f06d9b6c1ed7be8ba6df5d1cc1cbcdbcf0ce8
17,277
// // CreditNoteRoutes.swift // Stripe // // Created by Andrew Edwards on 5/13/19. // import NIO import NIOHTTP1 public protocol CreditNoteRoutes { /// Issue a credit note to adjust the amount of a finalized invoice. For a `status=open` invoice, a credit note reduces its `amount_due`. For a `status=paid` invoice, a credit note does not affect its `amount_due`. Instead, it can result in any combination of the following: /n - Refund: create a new refund (using `refund_amount`) or link an existing refund (using `refund`). - Customer balance credit: credit the customer’s balance (using `credit_amount`) which will be automatically applied to their next invoice when it’s finalized. - Outside of Stripe credit: any positive value from the result of `amount - refund_amount - credit_amount` is represented as an “outside of Stripe” credit. /n You may issue multiple credit notes for an invoice. Each credit note will increment the invoice’s `pre_payment_credit_notes_amount` or `post_payment_credit_notes_amount` depending on its `status` at the time of credit note creation. /// /// - Parameters: /// - amount: The integer amount in cents representing the total amount of the credit note. /// - invoice: ID of the invoice. /// - lines: Line items that make up the credit note. /// - outOfBandAmount: The integer amount in `cents` representing the amount that is credited outside of Stripe. /// - creditAmount: The integer amount in cents representing the amount to credit the customer’s balance, which will be automatically applied to their next invoice. /// - memo: The credit note’s memo appears on the credit note PDF. This will be unset if you POST an empty value. /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. /// - reason: Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` /// - refund: ID of an existing refund to link this credit note to. /// - refundAmount: The integer amount in cents representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. /// - expand: An array of properties to expand. /// - Returns: A `StripeCreditNote`. func create(amount: Int, invoice: String, lines: [[String: Any]]?, outOfBandAmount: Int?, creditAmount: Int?, memo: String?, metadata: [String: String]?, reason: StripeCreditNoteReason?, refund: String?, refundAmount: Int?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> /// Get a preview of a credit note without creating it. /// - Parameters: /// - invoice: ID of the invoice. /// - lines: Line items that make up the credit note. /// - amount: The integer amount in cents representing the total amount of the credit note. /// - creditAmount: The integer amount in cents representing the amount to credit the customer’s balance, which will be automatically applie to their next invoice. /// - outOfBandAmount: The integer amount in `cents` representing the amount that is credited outside of Stripe. /// - memo: The credit note’s memo appears on the credit note PDF. This will be unset if you POST an empty value. /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. /// - reason: Reason for issuing this credit note, one of `duplicate`, `fraudulent`, `order_change`, or `product_unsatisfactory` /// - refund: ID of an existing refund to link this credit note to. /// - refundAmount: The integer amount in cents representing the amount to refund. If set, a refund will be created for the charge associated with the invoice. /// - expand: An array of properties to expand. func preview(invoice: String, lines: [[String: Any]]?, amount: Int?, creditAmount: Int?, outOfBandAmount: Int?, memo: String?, metadata: [String: String]?, reason: StripeCreditNoteReason?, refund: String?, refundAmount: Int?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> /// Retrieves the credit note object with the given identifier. /// /// - Parameters: /// - id: ID of the credit note object to retrieve. /// - expand: An array of properties to expand. /// - Returns: A `StripeCreditNote`. func retrieve(id: String, expand: [String]?) -> EventLoopFuture<StripeCreditNote> /// Updates an existing credit note. /// /// - Parameters: /// - id: ID of the credit note object to update. /// - memo: Credit note memo. This will be unset if you POST an empty value. /// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. /// - expand: An array of properties to expand. /// - Returns: A `StripeCreditNote`. func update(id: String, memo: String?, metadata: [String: String]?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> /// When retrieving a credit note, you’ll get a lines property containing the the first handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. /// - Parameters: /// - id: The id of the credit note. /// - filter: A dictionary that will be used for the [query parameters.](https://stripe.com/docs/api/credit_notes/lines?lang=curl) func retrieveLineItems(id: String, filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteLineItemList> /// When retrieving a credit note preview, you’ll get a lines property containing the first handful of those items. This URL you can retrieve the full (paginated) list of line items. /// - Parameters: /// - id: ID of the invoice. /// - filter: A dictionary that will be used for the [query parameters.](https://stripe.com/docs/api/credit_notes/preview_lines?lang=curl) func retrievePreviewLineItems(invoice: String, filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteLineItemList> /// Marks a credit note as void. Learn more about [voiding credit notes.](https://stripe.com/docs/billing/invoices/credit-notes#voiding) /// /// - Parameters: /// - id: ID of the credit note object to void. /// - expand: An array of properties to expand. func void(id: String, expand: [String]?) -> EventLoopFuture<StripeCreditNote> /// Returns a list of credit notes. /// /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/credit_notes/list) func listAll(filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteList> /// Headers to send with the request. var headers: HTTPHeaders { get set } } extension CreditNoteRoutes { public func create(amount: Int, invoice: String, lines: [[String: Any]]? = nil, outOfBandAmount: Int? = nil, creditAmount: Int? = nil, memo: String? = nil, metadata: [String: String]? = nil, reason: StripeCreditNoteReason? = nil, refund: String? = nil, refundAmount: Int? = nil, expand: [String]? = nil) -> EventLoopFuture<StripeCreditNote> { return create(amount: amount, invoice: invoice, lines: lines, outOfBandAmount: outOfBandAmount, creditAmount: creditAmount, memo: memo, metadata: metadata, reason: reason, refund: refund, refundAmount: refundAmount, expand: expand) } public func preview(invoice: String, lines: [[String: Any]]?, amount: Int? = nil, creditAmount: Int? = nil, outOfBandAmount: Int? = nil, memo: String? = nil, metadata: [String: String]? = nil, reason: StripeCreditNoteReason? = nil, refund: String? = nil, refundAmount: Int? = nil, expand: [String]? = nil) -> EventLoopFuture<StripeCreditNote> { return preview(invoice: invoice, lines: lines, amount: amount, creditAmount: creditAmount, outOfBandAmount: outOfBandAmount, memo: memo, metadata: metadata, reason: reason, refund: refund, refundAmount: refundAmount, expand: expand) } public func retrieve(id: String, expand: [String]? = nil) -> EventLoopFuture<StripeCreditNote> { return retrieve(id: id, expand: expand) } public func update(id: String, memo: String? = nil, metadata: [String: String]? = nil, expand: [String]? = nil) -> EventLoopFuture<StripeCreditNote> { return update(id: id, memo: memo, metadata: metadata, expand: expand) } public func retrieveLineItems(id: String, filter: [String: Any]? = nil) -> EventLoopFuture<StripeCreditNoteLineItemList> { retrieveLineItems(id: id, filter: filter) } public func retrievePreviewLineItems(invoice: String, filter: [String: Any]? = nil) -> EventLoopFuture<StripeCreditNoteLineItemList> { retrievePreviewLineItems(invoice: invoice, filter: filter) } public func void(id: String, expand: [String]? = nil) -> EventLoopFuture<StripeCreditNote> { return void(id: id, expand: expand) } public func listAll(filter: [String: Any]? = nil) -> EventLoopFuture<StripeCreditNoteList> { return listAll(filter: filter) } } public struct StripeCreditNoteRoutes: CreditNoteRoutes { public var headers: HTTPHeaders = [:] private let apiHandler: StripeAPIHandler private let creditnotes = APIBase + APIVersion + "credit_notes" init(apiHandler: StripeAPIHandler) { self.apiHandler = apiHandler } public func create(amount: Int, invoice: String, lines: [[String: Any]]?, outOfBandAmount: Int?, creditAmount: Int?, memo: String?, metadata: [String: String]?, reason: StripeCreditNoteReason?, refund: String?, refundAmount: Int?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> { var body: [String: Any] = ["amount": amount, "invoice": invoice] if let lines = lines { body["lines"] = lines } if let outOfBandAmount = outOfBandAmount { body["out_of_band_amount"] = outOfBandAmount } if let creditAmount = creditAmount { body["credit_amount"] = creditAmount } if let memo = memo { body["memo"] = memo } if let metadata = metadata { metadata.forEach { body["metadata[\($0)]"] = $1 } } if let reason = reason { body["reason"] = reason.rawValue } if let refund = refund { body["refund"] = refund } if let refundAmount = refundAmount { body["refund_amount"] = refundAmount } if let expand = expand { body["expand"] = expand } return apiHandler.send(method: .POST, path: creditnotes, body: .string(body.queryParameters), headers: headers) } public func preview(invoice: String, lines: [[String: Any]]?, amount: Int?, creditAmount: Int?, outOfBandAmount: Int?, memo: String?, metadata: [String: String]?, reason: StripeCreditNoteReason?, refund: String?, refundAmount: Int?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> { var body: [String: Any] = ["invoice": invoice] if let amount = amount { body["amount"] = amount } if let lines = lines { body["lines"] = lines } if let creditAmount = creditAmount { body["credit_amount"] = creditAmount } if let outOfBandAmount = outOfBandAmount { body["out_of_band_amount"] = outOfBandAmount } if let memo = memo { body["memo"] = memo } if let metadata = metadata { metadata.forEach { body["metadata[\($0)]"] = $1 } } if let reason = reason { body["reason"] = reason.rawValue } if let refund = refund { body["refund"] = refund } if let refundAmount = refundAmount { body["refund_amount"] = refundAmount } if let expand = expand { body["expand"] = expand } return apiHandler.send(method: .POST, path: "\(creditnotes)/preview", body: .string(body.queryParameters), headers: headers) } public func retrieve(id: String, expand: [String]?) -> EventLoopFuture<StripeCreditNote> { var queryParams = "" if let expand = expand { queryParams += ["expand": expand].queryParameters } return apiHandler.send(method: .GET, path: "\(creditnotes)/\(id)", query: queryParams, headers: headers) } public func update(id: String, memo: String?, metadata: [String: String]?, expand: [String]?) -> EventLoopFuture<StripeCreditNote> { var body: [String: Any] = [:] if let memo = memo { body["memo"] = memo } if let metadata = metadata { metadata.forEach { body["metadata[\($0)]"] = $1 } } if let expand = expand { body["expand"] = expand } return apiHandler.send(method: .POST, path: "\(creditnotes)/\(id)", body: .string(body.queryParameters), headers: headers) } public func retrieveLineItems(id: String, filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteLineItemList> { var queryParams = "" if let filter = filter { queryParams += filter.queryParameters } return apiHandler.send(method: .GET, path: "\(creditnotes)/\(id)/lines", query: queryParams, headers: headers) } public func retrievePreviewLineItems(invoice: String, filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteLineItemList> { var queryParams = "invoice=\(invoice)" if let filter = filter { queryParams += "&" + filter.queryParameters } return apiHandler.send(method: .GET, path: "\(creditnotes)/preview/lines", query: queryParams, headers: headers) } public func void(id: String, expand: [String]?) -> EventLoopFuture<StripeCreditNote> { var body: [String: Any] = [:] if let expand = expand { body["expand"] = expand } return apiHandler.send(method: .POST, path: "\(creditnotes)/\(id)/void", body: .string(body.queryParameters), headers: headers) } public func listAll(filter: [String: Any]?) -> EventLoopFuture<StripeCreditNoteList> { var queryParams = "" if let filter = filter { queryParams += filter.queryParameters } return apiHandler.send(method: .GET, path: creditnotes, query: queryParams, headers: headers) } }
46.195187
932
0.578341
cc1525e2955afa6c2a75875e35dfe70b4fcd1346
6,685
// // ClubAsmCompoCircleView.swift // demo // // Created by Johan Halin on 10/04/2019. // Copyright © 2019 Dekadence. All rights reserved. // import UIKit class ClubAsmCompoCircleView: UIView, ClubAsmActions { private var containers = [ContainerView]() private var position = 0 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white for i in 1...4 { let view = ContainerView(frame: self.bounds, index: i) view.isHidden = true addSubview(view) self.containers.append(view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func action1() { for view in self.containers { view.isHidden = true } self.containers[self.position].isHidden = false self.containers[self.position].action1() } func action2() { self.containers[self.position].action2() } func action3() { self.containers[self.position].action3() } func action4() { self.containers[self.position].action4() } func action5() { self.containers[self.position].action5() self.position += 1 if self.position >= 4 { self.position = 0 } } private class ContainerView: UIView, ClubAsmActions { let backgroundContainer = UIView() let text = UIImageView() let referenceWidth: CGFloat = 366 let movement: CGFloat = 100 var textOrigin = CGPoint(x: 0, y: 0) let index: Int init(frame: CGRect, index: Int) { self.index = index super.init(frame: frame) self.backgroundContainer.frame = frame addSubview(self.backgroundContainer) let image = UIImage(named: "clubasmcompo_2-\(index)")! let count = Int(ceil(self.bounds.size.height / image.size.height)) for i in 0..<count { let background = UIView(frame: frame) background.backgroundColor = UIColor(patternImage: image) background.frame.origin.y = CGFloat(i) * image.size.height background.frame.size.width = background.bounds.size.width + image.size.width background.frame.size.height = image.size.height self.backgroundContainer.addSubview(background) let circleMask = CircleView(frame: self.bounds) circleMask.bounds.size.width += self.movement circleMask.backgroundColor = .clear self.backgroundContainer.mask = circleMask self.text.image = image self.text.frame = CGRect(x: 0, y: (self.bounds.size.height / 2.0) - (image.size.height / 2.0), width: image.size.width, height: image.size.height) addSubview(self.text) self.textOrigin = CGPoint(x: (self.bounds.size.width / 2.0) - ((self.text.bounds.size.width - 5.0) / 2.0) - (self.movement / 2.0), y: self.text.frame.origin.y) let middle = Double(background.bounds.size.width / 2.0) let animation = CABasicAnimation(keyPath: "position.x") animation.fromValue = NSNumber(floatLiteral: middle) animation.toValue = NSNumber(floatLiteral: middle - Double(image.size.width)) animation.beginTime = CACurrentMediaTime() + (sin(Double(i) / Double(count)) * 0.4) animation.duration = Double(image.size.width / self.referenceWidth) * 1.5 animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) animation.repeatCount = Float.infinity background.layer.add(animation, forKey: "xposition") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func action1() { self.backgroundContainer.isHidden = true startAt(x: 0) } func action2() { startAt(x: self.textOrigin.x * (1.0 / 4.0)) } func action3() { startAt(x: self.textOrigin.x * (2.0 / 4.0)) } func action4() { startAt(x: self.textOrigin.x * (3.0 / 4.0)) } func action5() { self.backgroundContainer.isHidden = false self.backgroundContainer.mask!.frame.origin.x = -self.movement self.text.layer.removeAllAnimations() self.text.frame.origin = self.textOrigin UIView.animate(withDuration: 2.0, delay: 0, options: [.curveLinear], animations: { self.backgroundContainer.mask!.frame.origin.x += self.movement self.text.frame.origin.x += self.movement }, completion: nil) } private func startAt(x: CGFloat) { self.text.layer.removeAllAnimations() self.text.frame.origin.x = x UIView.animate(withDuration: 2.0, delay: 0, options: [.curveLinear], animations: { self.text.frame.origin.x = x + self.movement }, completion: nil) } } private class CircleView: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext()! context.setFillColor(UIColor.white.cgColor) context.move(to: CGPoint(x: 0, y: 0)) context.addLine(to: CGPoint(x: rect.size.width / 2.0, y: 0)) let radius = rect.size.height / 2.0 context.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, startAngle: CGFloat.pi * 1.5, endAngle: CGFloat.pi * 0.5, clockwise: true) context.addLine(to: CGPoint(x: 0, y: rect.maxY)) context.addLine(to: CGPoint(x: 0, y: 0)) context.closePath() context.fillPath() context.move(to: CGPoint(x: rect.maxX, y: 0)) context.addLine(to: CGPoint(x: rect.midX, y: 0)) context.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, startAngle: CGFloat.pi * 1.5, endAngle: CGFloat.pi * 0.5, clockwise: false) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: 0)) context.closePath() context.fillPath() } } }
36.730769
175
0.562004
030442ff1bd50272303974e3256fba00619f2e9c
5,143
// // SegwitAddrCoder.swift // // Created by Evolution Group Ltd on 12.02.2018. // Copyright © 2018 Evolution Group Ltd. All rights reserved. // // Base32 address format for native v0-16 witness outputs implementation // https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki // Inspired by Pieter Wuille C++ implementation // import Foundation /// Segregated Witness Address encoder/decoder public class SegwitAddrCoder { public static let shared = SegwitAddrCoder() private let bech32 = Bech32() /// Convert from one power-of-2 number base to another private func convertBits(from: Int, to: Int, pad: Bool, idata: Data) throws -> Data { var acc: Int = 0 var bits: Int = 0 let maxv: Int = (1 << to) - 1 let maxAcc: Int = (1 << (from + to - 1)) - 1 var odata = Data() for ibyte in idata { acc = ((acc << from) | Int(ibyte)) & maxAcc bits += from while bits >= to { bits -= to odata.append(UInt8((acc >> bits) & maxv)) } } if pad { if bits != 0 { odata.append(UInt8((acc << (to - bits)) & maxv)) } } else if (bits >= from || ((acc << (to - bits)) & maxv) != 0) { throw CoderError.bitsConversionFailed } return odata } /// Decode segwit address public func decode(hrp: String? = nil, addr: String) throws -> (version: Int, program: Data) { let dec = try bech32.decode(addr) if let hrp = hrp, dec.hrp != hrp { throw CoderError.hrpMismatch(dec.hrp, hrp) } guard dec.checksum.count >= 1 else { throw CoderError.checksumSizeTooLow } let conv = try convertBits(from: 5, to: 8, pad: false, idata: dec.checksum.advanced(by: 1)) guard conv.count >= 2 && conv.count <= 40 else { throw CoderError.dataSizeMismatch(conv.count) } guard dec.checksum[0] <= 16 else { throw CoderError.segwitVersionNotSupported(dec.checksum[0]) } if dec.checksum[0] == 0 && conv.count != 20 && conv.count != 32 { throw CoderError.segwitV0ProgramSizeMismatch(conv.count) } return (Int(dec.checksum[0]), conv) } /// Encode segwit address public func encode(hrp: String, version: Int, program: Data) throws -> String { var enc = Data([UInt8(version)]) enc.append(try convertBits(from: 8, to: 5, pad: true, idata: program)) let result = bech32.encode(hrp, values: enc) guard let _ = try? decode(addr: result) else { throw CoderError.encodingCheckFailed } return result } public func encode2(hrp: String, program: Data) throws -> String { let enc = try convertBits(from: 8, to: 5, pad: true, idata: program) let result = bech32.encode(hrp, values: enc) return result } } extension SegwitAddrCoder { public enum CoderError: LocalizedError { case bitsConversionFailed case hrpMismatch(String, String) case checksumSizeTooLow case dataSizeMismatch(Int) case segwitVersionNotSupported(UInt8) case segwitV0ProgramSizeMismatch(Int) case encodingCheckFailed public var errorDescription: String? { switch self { case .bitsConversionFailed: return "Failed to perform bits conversion" case .checksumSizeTooLow: return "Checksum size is too low" case .dataSizeMismatch(let size): return "Program size \(size) does not meet required range 2...40" case .encodingCheckFailed: return "Failed to check result after encoding" case .hrpMismatch(let got, let expected): return "Human-readable-part \"\(got)\" does not match requested \"\(expected)\"" case .segwitV0ProgramSizeMismatch(let size): return "Segwit program size \(size) does not meet version 0 requirments" case .segwitVersionNotSupported(let version): return "Segwit version \(version) is not supported by this decoder" } } } } extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx" return map { String(format: format, $0) }.joined() } } func dataWithHexString(hex: String) -> Data { var hex = hex var data = Data() while(hex.characters.count > 0) { let c: String = hex.substring(to: hex.index(hex.startIndex, offsetBy: 2)) hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2)) var ch: UInt32 = 0 Scanner(string: c).scanHexInt32(&ch) var char = UInt8(ch) data.append(&char, count: 1) } return data }
35.715278
99
0.58565
d524f2e70115222a31390ee8c5a35116b7333386
3,678
import Foundation import azureSwiftRuntime public protocol DisasterRecoveryConfigsCreateOrUpdate { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var namespaceName : String { get set } var alias : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } var parameters : ArmDisasterRecoveryProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (ArmDisasterRecoveryProtocol?, Error?) -> Void) -> Void ; } extension Commands.DisasterRecoveryConfigs { // CreateOrUpdate creates or updates a new Alias(Disaster Recovery configuration) internal class CreateOrUpdateCommand : BaseCommand, DisasterRecoveryConfigsCreateOrUpdate { public var resourceGroupName : String public var namespaceName : String public var alias : String public var subscriptionId : String public var apiVersion = "2017-04-01" public var parameters : ArmDisasterRecoveryProtocol? public init(resourceGroupName: String, namespaceName: String, alias: String, subscriptionId: String, parameters: ArmDisasterRecoveryProtocol) { self.resourceGroupName = resourceGroupName self.namespaceName = namespaceName self.alias = alias self.subscriptionId = subscriptionId self.parameters = parameters super.init() self.method = "Put" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{namespaceName}"] = String(describing: self.namespaceName) self.pathParameters["{alias}"] = String(describing: self.alias) 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? ArmDisasterRecoveryData) 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(ArmDisasterRecoveryData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (ArmDisasterRecoveryProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: ArmDisasterRecoveryData?, error: Error?) in completionHandler(result, error) } } } }
49.04
181
0.646275
edb18b47a88be9fccc1bdd816cb8442776a719d2
911
// // TaoVerticalViews.swift // TaoAutoLayout // // Created by 刘涛 on 16/7/6. // Copyright © 2016年 tao6. All rights reserved. // import UIKit class TaoVerticalViews: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() // 上边控件 let tBtn = UIButton(title: "上", bgColor: UIColor.yellowColor()) addSubview(tBtn) // 中间的控件 let cBtn = UIButton(title: "中", bgColor: UIColor.blueColor()) addSubview(cBtn) // 下边的控件 let bBtn = UIButton(title: "下", bgColor: UIColor.magentaColor()) addSubview(bBtn) tao_VerticalTile([tBtn, cBtn, bBtn], insets: UIEdgeInsets.init(top: 74, left: 10, bottom: 10, right: 10)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
25.305556
113
0.591658
4b2b9e7c98732dea86b1e7f5c9fd46c34282a18d
4,753
// // SendDownloadCompletedSpec.swift // Exposure // // Created by Udaya Sri Senarathne on 2020-10-22. // Copyright © 2020 emp. All rights reserved. // import Quick import Nimble @testable import Exposure class SendDownloadCompletedSpec: QuickSpec { override func spec() { super.spec() let base = "https://exposure.empps.ebsd.ericsson.net" let customer = "BlixtGroup" let businessUnit = "Blixt" var env = Environment(baseUrl: base, customer: customer, businessUnit: businessUnit) let assetId = "assetId1_qwerty" let sessionToken = SessionToken(value: "token") let sendDownloadComplete = SendDownloadCompleted(assetId: assetId, environment: env, sessionToken: sessionToken) describe("SendDownloadComplete") { it("should have headers") { expect(sendDownloadComplete.headers).toNot(beNil()) expect(sendDownloadComplete.headers!).to(equal(sessionToken.authorizationHeader)) } it("Should fail with invalid endpoint url") { let endpoint = "/entitlement/" + assetId + "/downloadcompleted" expect(sendDownloadComplete.endpointUrl).toNot(equal(env.apiUrl+endpoint)) } it("should generate a correct endpoint url") { env.version = "v2" let endpoint = "/entitlement/" + assetId + "/downloadcompleted" expect(sendDownloadComplete.endpointUrl).to(equal(env.apiUrl+endpoint)) } } describe("SendDownloadComplete Response") { it("should process with valid json") { let json = DownloadCompleteJSON.valid() let result = json.decode(DownloadCompleted.self) expect(result).toNot(beNil()) expect(result?.assetId).toNot(beNil()) expect(result?.downloadCount).toNot(beNil()) } it("should init with required keys") { let json = DownloadCompleteJSON.requiredKeys() let result = json.decode(DownloadCompleted.self) expect(result).toNot(beNil()) } it("should not init with missing keys response") { let json = DownloadCompleteJSON.missingKeys() let result = json.decode(DownloadCompleted.self) expect(result).to(beNil()) } it("should not init with empty response") { let json = DownloadCompleteJSON.empty() let result = json.decode(DownloadCompleted.self) expect(result).to(beNil()) } } } } extension SendDownloadCompletedSpec { enum DownloadCompleteJSON { static let assetId = "VU-21702_qwerty" static let downloadCount = 2 static let downloads = [DownloadJson.valid()] static let changed = "202-10-29T07:00:41Z" static func valid() -> [String: Any] { return [ "assetId": DownloadCompleteJSON.assetId, "downloadCount": DownloadCompleteJSON.downloadCount, "downloads": DownloadCompleteJSON.downloads, "changed": DownloadCompleteJSON.changed, ] } static func requiredKeys() -> [String: Any] { return [ "assetId": DownloadCompleteJSON.assetId, "downloadCount": DownloadCompleteJSON.downloadCount ] } static func missingKeys() -> [String: Any] { return [ "downloads": DownloadCompleteJSON.downloads, "changed": DownloadCompleteJSON.changed ] } static func empty() -> [String: Any] { return [:] } } } public enum DownloadJson { static let time = "time" static let type = "type" static let clientIp = "clientIp" static let deviceId = "deviceId" static let deviceType = "deviceType" static let deviceModelId = "deviceModelId" static let userId = "userId" public static func valid() -> [String: Any] { return [ "time": DownloadJson.time, "type": DownloadJson.type, "clientIp": DownloadJson.clientIp, "deviceId": DownloadJson.deviceId, "deviceType": DownloadJson.deviceType, "deviceModelId": DownloadJson.deviceModelId, "userId": DownloadJson.userId, ] } public static func empty() -> [String: Any] { return [:] } }
33.471831
123
0.559436
ed3f84f35e62535768deed4bddb7a4120296aebf
1,306
// // Post.swift // MyFinalPlusApp // // Created by Faten Abdullh salem on 25/05/1443 AH. // import UIKit import Firebase struct Post { var id = "" var user:User var restaurantName = "" var DeliveryTime = "" var DeliveryPrice = "" var title = "" var description = "" var price = "" var imageUrl = "" var createdAt:Timestamp? init(dict:[String:Any],id:String,user:User) { print("POST",dict) if let title = dict["title"] as? String, let restaurantName = dict["restaurantName"] as? String, let DeliveryTime = dict["deliveryTime"] as? String, let DeliveryPrice = dict["deliveryPrice"] as? String, let description = dict["description"] as? String, let price = dict["price"] as? String, let imageUrl = dict["imageUrl"] as? String, let createdAt = dict["createdAt"] as? Timestamp{ self.restaurantName = restaurantName self.DeliveryTime = DeliveryTime self.DeliveryPrice = DeliveryPrice self.title = title self.description = description self.price = price self.imageUrl = imageUrl self.createdAt = createdAt } self.id = id self.user = user } }
27.208333
63
0.57657
fb39c033ed066b53bc9fa8c3c9eda4521f1836e8
1,655
// // ImageFetcher.swift // FlickrSearch // // Created by Sagar Dagdu on 01/08/21. // import Foundation import UIKit final class ImageFetcher { lazy private var runningRequests = [UUID : URLSessionDataTask]() private var session: URLSession private var imageCache: ImageCache init(session: URLSession = URLSession.shared, imageCache: ImageCache = .init(maxImageCount: 250)) { self.session = session self.imageCache = imageCache } func loadImage(_ url: URL, _ completion: @escaping (Result<UIImage, Error>) -> Void) -> UUID? { if let image = imageCache.image(for: url) { completion(.success(image)) return nil } let uuid = UUID() let task = session.dataTask(with: url) { data, response, error in defer { self.runningRequests[uuid] = nil } if let data = data, let image = UIImage(data: data) { self.imageCache.setImage(image, for: url) completion(.success(image)) return } guard let error = error else { return } guard (error as NSError).code == NSURLErrorCancelled else { completion(.failure(error)) return } } task.resume() runningRequests[uuid] = task return uuid } func cancelLoad(_ uuid: UUID) { runningRequests[uuid]?.cancel() runningRequests[uuid] = nil } }
25.859375
87
0.520242
1d0b45ef7213b7cf144fc0c7e48a9345f27592f1
2,341
// // HomeViewModel.swift // TheMovieDBAPI // // Created by Umut SERIFLER on 16/02/2021. // Copyright (c) 2021 UmutSERIFLER. All rights reserved. import Foundation class HomeViewModel: ViewProtocol { var reloadViewClosure: (() -> ()) = { } var showAlertClosure: ((String?) -> ()) = {_ in} var trendContents: [Int: ContentGroupModel] = [:] { didSet { self.reloadViewClosure() } } var requiredContentList: [MediaType] = [.all,.movie,.tv] private(set) var apiService : MovieDBAPIProviderProtocol! init(_ apiService: MovieDBAPIProviderProtocol = MovieDBAPIProvider()) { self.apiService = apiService } /// This method is called firstly to get configuration from API func getExtendedContents() { if Config.shared.resource == nil { apiService.getConfiguration { (result) in switch result { case .success(let configResult): Config.shared.resource = configResult self.getPopularContents() case .failure(let error): print(error.localizedDescription) } } } } /// This is added for future implementation /// - Parameters: /// - types: Media Type Tv / Movie /// - pageNumber: page Number /// - timeSlot: day / week func getPopularContents(types: [MediaType] = [.all,.movie,.tv], pageNumber: Int = 1, timeSlot: TimeWindow = .day) { for (index, type) in types.enumerated() { apiService.getTrending(type: type, timeSlot: timeSlot, page: pageNumber) { (result) in switch result { case .success(let successResult): self.trendContents.updateValue(ContentGroupModel(type, successResult), forKey: index) case .failure(let error): self.showAlertClosure(error.localizedDescription) } } } } func getContentsWithData() -> [Int: ContentGroupModel] { return self.trendContents } func getContentCount() -> Int { return self.trendContents.count } func getContents(in section: Int) -> ContentGroupModel? { return self.trendContents[section] } }
31.635135
119
0.577104
5b75a4da29fee589204627507a10223a7a037d69
1,640
// // AnotherFakeAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import PromiseKit open class AnotherFakeAPI { /** To test special tags - parameter body: (body) client model - returns: Promise<Client> */ open class func call123testSpecialTags( body: Client) -> Promise<Client> { let deferred = Promise<Client>.pending() call123testSpecialTagsWithRequestBuilder(body: body).execute { (response, error) -> Void in if let error = error { deferred.resolver.reject(error) } else if let response = response { deferred.resolver.fulfill(response.body!) } else { fatalError() } } return deferred.promise } /** To test special tags - PATCH /another-fake/dummy - To test special tags and operation ID starting with number - parameter body: (body) client model - returns: RequestBuilder<Client> */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder<Client> { let path = "/another-fake/dummy" let URLString = PetstoreClientAPI.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Client>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } }
31.538462
128
0.65
8f400adc4fad1c2fc661c4f3885c69844487f7d6
462
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing b> { { case c, var _ = f<1 { if true { struct d<1 { class b: a { case c, init<T where T>() { let f = f<1 { { enum b : b : a { func g<T where T where I.b : b { func g<T>() { protocol a { enum b : a { var _ = compose(x: b { func b let f = compose() { func b: d where I.b : b : b { class case c,
18.48
87
0.623377
03c5d90d2a005c1655ceb5021e80e6813b584003
25,177
// // Created by Krzysztof Zablocki on 14/09/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation import PathKit import SourceryFramework import SourceryUtils import SourceryRuntime import SourceryJS import SourcerySwift import TryCatch import xcproj class Sourcery { public static let version: String = SourceryVersion.current.value public static let generationMarker: String = "// Generated using Sourcery" public static let generationHeader = "\(Sourcery.generationMarker) \(Sourcery.version) — https://github.com/krzysztofzablocki/Sourcery\n" + "// DO NOT EDIT\n\n" enum Error: Swift.Error { case containsMergeConflictMarkers } fileprivate let verbose: Bool fileprivate let watcherEnabled: Bool fileprivate let arguments: [String: NSObject] fileprivate let cacheDisabled: Bool fileprivate let cacheBasePath: Path? fileprivate let prune: Bool fileprivate var status = "" fileprivate var templatesPaths = Paths(include: []) fileprivate var outputPath = Output("", linkTo: nil) // content annotated with file annotations per file path to write it to fileprivate var fileAnnotatedContent: [Path: [String]] = [:] /// Creates Sourcery processor init(verbose: Bool = false, watcherEnabled: Bool = false, cacheDisabled: Bool = false, cacheBasePath: Path? = nil, prune: Bool = false, arguments: [String: NSObject] = [:]) { self.verbose = verbose self.arguments = arguments self.watcherEnabled = watcherEnabled self.cacheDisabled = cacheDisabled self.cacheBasePath = cacheBasePath self.prune = prune } /// Processes source files and generates corresponding code. /// /// - Parameters: /// - files: Path of files to process, can be directory or specific file. /// - templatePath: Specific Template to use for code generation. /// - output: Path to output source code to. /// - forceParse: extensions of generated sourcery file that can be parsed /// - watcherEnabled: Whether daemon watcher should be enabled. /// - Throws: Potential errors. func processFiles(_ source: Source, usingTemplates templatesPaths: Paths, output: Output, forceParse: [String] = []) throws -> [FolderWatcher.Local]? { self.templatesPaths = templatesPaths self.outputPath = output let watchPaths: Paths switch source { case let .sources(paths): watchPaths = paths case let .projects(projects): watchPaths = Paths(include: projects.map({ $0.root }), exclude: projects.flatMap({ $0.exclude })) } let process: (Source) throws -> ParsingResult = { source in var result: ParsingResult switch source { case let .sources(paths): result = try self.parse(from: paths.include, exclude: paths.exclude, forceParse: forceParse, modules: nil) case let .projects(projects): var paths: [Path] = [] var modules = [String]() projects.forEach { project in project.targets.forEach { target in guard let projectTarget = project.file.target(named: target.name) else { return } let files: [Path] = project.file.sourceFilesPaths(target: projectTarget, sourceRoot: project.root) files.forEach { file in guard !project.exclude.contains(file) else { return } paths.append(file) modules.append(target.module) } } } result = try self.parse(from: paths, modules: modules) } try self.generate(source: source, templatePaths: templatesPaths, output: output, parsingResult: result, forceParse: forceParse) return result } var result = try process(source) guard watcherEnabled else { return nil } Log.info("Starting watching sources.") let sourceWatchers = topPaths(from: watchPaths.allPaths).map({ watchPath in return FolderWatcher.Local(path: watchPath.string) { events in let eventPaths: [Path] = events .filter { $0.flags.contains(.isFile) } .compactMap { let path = Path($0.path) return path.isSwiftSourceFile ? path : nil } var pathThatForcedRegeneration: Path? for path in eventPaths { guard let file = try? path.read(.utf8) else { continue } if !file.hasPrefix(Sourcery.generationMarker) { pathThatForcedRegeneration = path break } } if let path = pathThatForcedRegeneration { do { Log.info("Source changed at \(path.string)") result = try process(source) } catch { Log.error(error) } } } }) Log.info("Starting watching templates.") let templateWatchers = topPaths(from: templatesPaths.allPaths).map({ templatesPath in return FolderWatcher.Local(path: templatesPath.string) { events in let events = events .filter { $0.flags.contains(.isFile) && Path($0.path).isTemplateFile } if !events.isEmpty { do { if events.count == 1 { Log.info("Template changed \(events[0].path)") } else { Log.info("Templates changed: ") } try self.generate(source: source, templatePaths: Paths(include: [templatesPath]), output: output, parsingResult: result, forceParse: forceParse) } catch { Log.error(error) } } } }) return Array([sourceWatchers, templateWatchers].joined()) } private func topPaths(from paths: [Path]) -> [Path] { var top: [(Path, [Path])] = [] paths.forEach { path in // See if its already contained by the topDirectories guard top.first(where: { (_, children) -> Bool in return children.contains(path) }) == nil else { return } if path.isDirectory { top.append((path, (try? path.recursiveChildren()) ?? [])) } else { let dir = path.parent() let children = (try? dir.recursiveChildren()) ?? [] if children.contains(path) { top.append((dir, children)) } else { top.append((path, [])) } } } return top.map { $0.0 } } /// This function should be used to retrieve the path to the cache instead of `Path.cachesDir`, /// as it considers the `--cacheDisabled` and `--cacheBasePath` command line parameters. fileprivate func cachesDir(sourcePath: Path, createIfMissing: Bool = true) -> Path? { return cacheDisabled ? nil : Path.cachesDir(sourcePath: sourcePath, basePath: cacheBasePath, createIfMissing: createIfMissing) } /// Remove the existing cache artifacts if it exists. /// Currently this is only called from tests, and the `--cacheDisabled` and `--cacheBasePath` command line parameters are not considered. /// /// - Parameter sources: paths of the sources you want to delete the static func removeCache(for sources: [Path], cacheDisabled: Bool = false, cacheBasePath: Path? = nil) { if cacheDisabled { return } sources.forEach { path in let cacheDir = Path.cachesDir(sourcePath: path, basePath: cacheBasePath, createIfMissing: false) _ = try? cacheDir.delete() } } fileprivate func templates(from: Paths) throws -> [Template] { return try templatePaths(from: from).compactMap { if $0.extension == "swifttemplate" { let cachePath = cachesDir(sourcePath: $0) return try SwiftTemplate(path: $0, cachePath: cachePath, version: type(of: self).version) } else if $0.extension == "ejs" { guard EJSTemplate.ejsPath != nil else { Log.warning("Skipping template \($0). JavaScript templates require EJS path to be set manually when using Sourcery built with Swift Package Manager. Use `--ejsPath` command line argument to set it.") return nil } return try JavaScriptTemplate(path: $0) } else { return try StencilTemplate(path: $0) } } } private func templatePaths(from: Paths) -> [Path] { return from.allPaths.filter { $0.isTemplateFile } } } // MARK: - Parsing extension Sourcery { typealias ParsingResult = (types: Types, inlineRanges: [(file: String, ranges: [String: NSRange], indentations: [String: String])]) fileprivate func parse(from: [Path], exclude: [Path] = [], forceParse: [String] = [], modules: [String]?) throws -> ParsingResult { if let modules = modules { precondition(from.count == modules.count, "There should be module for each file to parse") } let startScan = currentTimestamp() Log.info("Scanning sources...") var inlineRanges = [(file: String, ranges: [String: NSRange], indentations: [String: String])]() var allResults = [FileParserResult]() let excludeSet = Set(exclude .map { $0.isDirectory ? try? $0.recursiveChildren() : [$0] } .compactMap({ $0 }).flatMap({ $0 })) try from.enumerated().forEach { index, from in let fileList = from.isDirectory ? try from.recursiveChildren() : [from] let sources = try fileList .filter { $0.isSwiftSourceFile } .filter { return !excludeSet.contains($0) } .compactMap { (path: Path) -> (path: Path, contents: String)? in do { return (path: path, contents: try path.read(.utf8)) } catch { Log.warning("Skipping file at \(path) as it does not exist") return nil } } .filter { let result = Verifier.canParse(content: $0.contents, path: $0.path, generationMarker: Sourcery.generationMarker, forceParse: forceParse) if result == .containsConflictMarkers { throw Error.containsMergeConflictMarkers } return result == .approved } .map { try FileParser(contents: $0.contents, path: $0.path, module: modules?[index], forceParse: forceParse) } var previousUpdate = 0 var accumulator = 0 let step = sources.count / 10 // every 10% let results = try sources.parallelMap({ try self.loadOrParse(parser: $0, cachesPath: cachesDir(sourcePath: from)) }, progress: !(verbose || watcherEnabled) ? nil : { _ in if accumulator > previousUpdate + step { previousUpdate = accumulator let percentage = accumulator * 100 / sources.count Log.info("Scanning sources... \(percentage)% (\(sources.count) files)") } accumulator += 1 }) allResults.append(contentsOf: results) } Log.benchmark("\tloadOrParse: \(currentTimestamp() - startScan)") let parserResult = allResults.reduce(FileParserResult(path: nil, module: nil, types: [], typealiases: [])) { acc, next in acc.typealiases += next.typealiases acc.types += next.types // swiftlint:disable:next force_unwrapping inlineRanges.append((next.path!, next.inlineRanges, next.inlineIndentations)) return acc } let uniqueTypeStart = currentTimestamp() //! All files have been scanned, time to join extensions with base class let types = Composer.uniqueTypes(parserResult) Log.benchmark("\tcombiningTypes: \(currentTimestamp() - uniqueTypeStart)\n\ttotal: \(currentTimestamp() - startScan)") Log.info("Found \(types.count) types.") return (Types(types: types), inlineRanges) } private func loadOrParse(parser: FileParser, cachesPath: @autoclosure () -> Path?) throws -> FileParserResult { guard let pathString = parser.path else { fatalError("Unable to retrieve \(String(describing: parser.path))") } guard let cachesPath = cachesPath() else { return try parser.parse() } let path = Path(pathString) let artifacts = cachesPath + "\(pathString.hash).srf" guard artifacts.exists, let modifiedDate = parser.modifiedDate, let unarchived = load(artifacts: artifacts.string, modifiedDate: modifiedDate) else { let result = try parser.parse() let data = NSKeyedArchiver.archivedData(withRootObject: result) do { try artifacts.write(data) } catch { fatalError("Unable to save artifacts for \(path) under \(artifacts), error: \(error)") } return result } return unarchived } private func load(artifacts: String, modifiedDate: Date) -> FileParserResult? { var unarchivedResult: FileParserResult? SwiftTryCatch.try({ if let unarchived = NSKeyedUnarchiver.unarchiveObject(withFile: artifacts) as? FileParserResult { if unarchived.sourceryVersion == Sourcery.version, unarchived.modifiedDate == modifiedDate { unarchivedResult = unarchived } } }, catch: { _ in Log.warning("Failed to unarchive \(artifacts) due to error, re-parsing") }, finallyBlock: {}) return unarchivedResult } } // MARK: - Generation extension Sourcery { fileprivate func generate(source: Source, templatePaths: Paths, output: Output, parsingResult: ParsingResult, forceParse: [String]) throws { let generationStart = currentTimestamp() Log.info("Loading templates...") let allTemplates = try templates(from: templatePaths) Log.info("Loaded \(allTemplates.count) templates.") Log.benchmark("\tLoading took \(currentTimestamp() - generationStart)") Log.info("Generating code...") status = "" if output.isDirectory { try allTemplates.forEach { template in let result = try generate(template, forParsingResult: parsingResult, outputPath: output.path, forceParse: forceParse) let outputPath = output.path + generatedPath(for: template.sourcePath) try self.output(result: result, to: outputPath) if let linkTo = output.linkTo { link(outputPath, to: linkTo) } } } else { let result = try allTemplates.reduce("") { result, template in return result + "\n" + (try generate(template, forParsingResult: parsingResult, outputPath: output.path, forceParse: forceParse)) } try self.output(result: result, to: output.path) if let linkTo = output.linkTo { link(output.path, to: linkTo) } } try fileAnnotatedContent.forEach { (path, contents) in try self.output(result: contents.joined(separator: "\n"), to: path) if let linkTo = output.linkTo { link(path, to: linkTo) } } if let linkTo = output.linkTo { try linkTo.project.writePBXProj(path: linkTo.projectPath) } Log.benchmark("\tGeneration took \(currentTimestamp() - generationStart)") Log.info("Finished.") } private func link(_ output: Path, to linkTo: Output.LinkTo) { guard let target = linkTo.project.target(named: linkTo.target) else { return } let sourceRoot = linkTo.projectPath.parent() let fileGroup: PBXGroup if let group = linkTo.group { do { let addedGroup = linkTo.project.addGroup(named: group, to: linkTo.project.rootGroup, options: []) fileGroup = addedGroup.object if let groupPath = linkTo.project.fullPath(fileElement: addedGroup, sourceRoot: sourceRoot) { try groupPath.mkpath() } } catch { Log.warning("Failed to create a folder for group '\(fileGroup.name ?? "")'. \(error)") } } else { fileGroup = linkTo.project.rootGroup } do { try linkTo.project.addSourceFile(at: output, toGroup: fileGroup, target: target, sourceRoot: sourceRoot) } catch { Log.warning("Failed to link file at \(output) to \(linkTo.projectPath). \(error)") } } private func output(result: String, to outputPath: Path) throws { var result = result if !result.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { if outputPath.extension == "swift" { result = Sourcery.generationHeader + result } if !outputPath.parent().exists { try outputPath.parent().mkpath() } try writeIfChanged(result, to: outputPath) } else { if prune && outputPath.exists { Log.verbose("Removing \(outputPath) as it is empty.") do { try outputPath.delete() } catch { Log.error("\(error)") } } else { Log.verbose("Skipping \(outputPath) as it is empty.") } } } private func generate(_ template: Template, forParsingResult parsingResult: ParsingResult, outputPath: Path, forceParse: [String]) throws -> String { guard watcherEnabled else { let generationStart = currentTimestamp() let result = try Generator.generate(parsingResult.types, template: template, arguments: self.arguments) Log.benchmark("\tGenerating \(template.sourcePath.lastComponent) took \(currentTimestamp() - generationStart)") return try processRanges(in: parsingResult, result: result, outputPath: outputPath, forceParse: forceParse) } var result: String = "" SwiftTryCatch.try({ do { result = try Generator.generate(parsingResult.types, template: template, arguments: self.arguments) } catch { Log.error(error) } }, catch: { error in result = error?.description ?? "" }, finallyBlock: {}) return try processRanges(in: parsingResult, result: result, outputPath: outputPath, forceParse: forceParse) } private func processRanges(in parsingResult: ParsingResult, result: String, outputPath: Path, forceParse: [String]) throws -> String { let start = currentTimestamp() defer { Log.benchmark("\t\tProcessing Ranges took \(currentTimestamp() - start)") } var result = result result = processFileRanges(for: parsingResult, in: result, outputPath: outputPath, forceParse: forceParse) result = try processInlineRanges(for: parsingResult, in: result, forceParse: forceParse) return TemplateAnnotationsParser.removingEmptyAnnotations(from: result) } private func processInlineRanges(`for` parsingResult: ParsingResult, in contents: String, forceParse: [String]) throws -> String { var (annotatedRanges, rangesToReplace) = TemplateAnnotationsParser.annotationRanges("inline", contents: contents, forceParse: forceParse) typealias MappedInlineAnnotations = ( range: NSRange, filePath: Path, rangeInFile: NSRange, toInsert: String, indentation: String ) try annotatedRanges .map { (key: $0, range: $1[0].range) } .compactMap { (key, range) -> MappedInlineAnnotations? in let generatedBody = contents.bridge().substring(with: range) if let (filePath, inlineRanges, inlineIndentations) = parsingResult.inlineRanges.first(where: { $0.ranges[key] != nil }) { // swiftlint:disable:next force_unwrapping return MappedInlineAnnotations(range, Path(filePath), inlineRanges[key]!, generatedBody, inlineIndentations[key] ?? "") } guard key.hasPrefix("auto:") else { rangesToReplace.remove(range) return nil } let autoTypeName = key.trimmingPrefix("auto:").components(separatedBy: ".").dropLast().joined(separator: ".") let toInsert = "\n// sourcery:inline:\(key)\n\(generatedBody)// sourcery:end\n" guard let definition = parsingResult.types.types.first(where: { $0.name == autoTypeName }), let path = definition.path, let contents = try? path.read(.utf8), let bodyRange = definition.bodyRange(contents) else { rangesToReplace.remove(range) return nil } let bodyEndRange = NSRange(location: NSMaxRange(bodyRange), length: 0) let bodyEndLineRange = contents.bridge().lineRange(for: bodyEndRange) let rangeInFile = NSRange(location: max(bodyRange.location, bodyEndLineRange.location), length: 0) return MappedInlineAnnotations(range, path, rangeInFile, toInsert, "") } .sorted { lhs, rhs in return lhs.rangeInFile.location > rhs.rangeInFile.location }.forEach { (arg) in let (_, path, rangeInFile, toInsert, indentation) = arg let content = try path.read(.utf8) let updated = content.bridge().replacingCharacters(in: rangeInFile, with: indent(toInsert: toInsert, indentation: indentation)) try writeIfChanged(updated, to: path) } var bridged = contents.bridge() rangesToReplace .sorted(by: { $0.location > $1.location }) .forEach { bridged = bridged.replacingCharacters(in: $0, with: "") as NSString } return bridged as String } private func processFileRanges(`for` parsingResult: ParsingResult, in contents: String, outputPath: Path, forceParse: [String]) -> String { let files = TemplateAnnotationsParser.parseAnnotations("file", contents: contents, aggregate: true, forceParse: forceParse) files .annotatedRanges .map { ($0, $1) } .forEach({ (filePath, ranges) in let generatedBody = ranges.map { contents.bridge().substring(with: $0.range) }.joined(separator: "\n") let path = outputPath + (Path(filePath).extension == nil ? "\(filePath).generated.swift" : filePath) var fileContents = fileAnnotatedContent[path] ?? [] fileContents.append(generatedBody) fileAnnotatedContent[path] = fileContents }) return files.contents } fileprivate func writeIfChanged(_ content: String, to path: Path) throws { guard path.exists else { return try path.write(content) } let existing = try path.read(.utf8) if existing != content { try path.write(content) } } private func indent(toInsert: String, indentation: String) -> String { guard indentation.isEmpty == false else { return toInsert } let lines = toInsert.components(separatedBy: "\n") return lines.enumerated() .map { index, line in guard !line.isEmpty else { return line } return index == lines.count - 1 ? line : indentation + line } .joined(separator: "\n") } internal func generatedPath(`for` templatePath: Path) -> Path { return Path("\(templatePath.lastComponentWithoutExtension).generated.swift") } }
42.03172
219
0.573619
cca7bca1d08091ae3fb69d78e50e1ae97c61083f
1,172
// // ViewController.swift // GoogleMCA // // Created by Ilan Klein on 15/02/2016. // Copyright © 2016 ibm. All rights reserved. // import UIKit import BMSCore class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var answerTextView: UILabel! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginToGoogle(_ sender: AnyObject) { let callBack:BMSCompletionHandler = {(response: Response?, error: Error?) in var ans:String = ""; if error == nil { ans="response:\(response?.responseText), no error" } else { ans="ERROR , error=\(error)" } DispatchQueue.main.async { self.answerTextView.text = ans } } let request = Request(url: AppDelegate.resourceURL, method: HttpMethod.GET) request.send(completionHandler: callBack) } }
26.636364
84
0.603242
b956f90b8122a32ce77e5e4594f10ac56df6480c
3,214
import Foundation @objc public final class SwiftInteropBridge: NSObject { let appContext: AppContext var registry: ModuleRegistry { appContext.moduleRegistry } @objc public init(modulesProvider: ModulesProviderObjCProtocol, legacyModuleRegistry: EXModuleRegistry) { self.appContext = AppContext(withModulesProvider: modulesProvider as! ModulesProviderProtocol, legacyModuleRegistry: legacyModuleRegistry) super.init() } @objc public func hasModule(_ moduleName: String) -> Bool { return registry.has(moduleWithName: moduleName) } @objc public func callFunction( _ functionName: String, onModule moduleName: String, withArgs args: [Any], resolve: @escaping EXPromiseResolveBlock, reject: @escaping EXPromiseRejectBlock ) { registry .get(moduleHolderForName: moduleName)? .call(function: functionName, args: args) { value, error in if let error = error { reject(error.code, error.description, error) } else if let error = error { reject("ERR_UNKNOWN_ERROR", error.localizedDescription, error) } else { resolve(value) } } } @objc public func callFunctionSync( _ functionName: String, onModule moduleName: String, withArgs args: [Any] ) -> Any? { return registry .get(moduleHolderForName: moduleName)? .callSync(function: functionName, args: args) } @objc public func exportedFunctionNames() -> [String: [[String: Any]]] { var constants = [String: [[String: Any]]]() for holder in registry { constants[holder.name] = holder.definition.functions.map({ functionName, function in return [ "name": functionName, "argumentsCount": function.argumentsCount, "key": functionName ] }) } return constants } @objc public func exportedModulesConstants() -> [String: Any] { return registry.reduce(into: [String: Any]()) { acc, holder in acc[holder.name] = holder.getConstants() } } @objc public func exportedViewManagersNames() -> [String] { return registry.compactMap { holder in return holder.definition.viewManager != nil ? holder.name : nil } } /** Returns view modules wrapped by the base `ViewModuleWrapper` class. */ @objc public func getViewManagers() -> [ViewModuleWrapper] { return registry.compactMap { holder in if holder.definition.viewManager != nil { return ViewModuleWrapper(holder) } else { return nil } } } // MARK: - Events /** Returns an array of event names supported by all Swift modules. */ @objc public func getSupportedEvents() -> [String] { return registry.reduce(into: [String]()) { events, holder in events.append(contentsOf: holder.definition.eventNames) } } /** Modifies listeners count for module with given name. Depending on the listeners count, `onStartObserving` and `onStopObserving` are called. */ @objc public func modifyEventListenersCount(_ moduleName: String, count: Int) { registry .get(moduleHolderForName: moduleName)? .modifyListenersCount(count) } }
26.561983
142
0.665215
1afc9cb3d38d3574e0ab0a8c6d3dc5481e14e902
3,095
// // VNSequenceRequestHandler+Rx.swift // RxVision // // Created by Maxim Volgin on 08/02/2019. // Copyright (c) RxSwiftCommunity. All rights reserved. // import Vision import RxSwift import CoreImage @available(iOS 11.0, *) extension Reactive where Base: VNSequenceRequestHandler { // MARK: - CGImage public func perform(_ requests: [RxVNRequest<CGImage>], on value: CGImage) throws { let _requests = RxVNRequest<CGImage>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value) } public func perform(_ requests: [RxVNRequest<CGImage>], on value: CGImage, orientation: CGImagePropertyOrientation) throws { let _requests = RxVNRequest<CGImage>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value, orientation: orientation) } // MARK: - CIImage public func perform(_ requests: [RxVNRequest<CIImage>], on value: CIImage) throws { let _requests = RxVNRequest<CIImage>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value) } public func perform(_ requests: [RxVNRequest<CIImage>], on value: CIImage, orientation: CGImagePropertyOrientation) throws { let _requests = RxVNRequest<CIImage>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value, orientation: orientation) } // MARK: - CVPixelBuffer public func perform(_ requests: [RxVNRequest<CVPixelBuffer>], on value: CVPixelBuffer) throws { let _requests = RxVNRequest<CVPixelBuffer>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value) } public func perform(_ requests: [RxVNRequest<CVPixelBuffer>], on value: CVPixelBuffer, orientation: CGImagePropertyOrientation) throws { let _requests = RxVNRequest<CVPixelBuffer>.setAndMap(requests, on: value) try self.base.perform(_requests, on: value, orientation: orientation) } // MARK: - Data public func perform(_ requests: [RxVNRequest<Data>], onImageData: Data) throws { let _requests = RxVNRequest<Data>.setAndMap(requests, on: onImageData) try self.base.perform(_requests, onImageData: onImageData) } public func perform(_ requests: [RxVNRequest<Data>], onImageData: Data, orientation: CGImagePropertyOrientation) throws { let _requests = RxVNRequest<Data>.setAndMap(requests, on: onImageData) try self.base.perform(_requests, onImageData: onImageData, orientation: orientation) } // MARK: - URL public func perform(_ requests: [RxVNRequest<URL>], onImageURL: URL) throws { let _requests = RxVNRequest<URL>.setAndMap(requests, on: onImageURL) try self.base.perform(_requests, onImageURL: onImageURL) } public func perform(_ requests: [RxVNRequest<URL>], onImageURL: URL, orientation: CGImagePropertyOrientation) throws { let _requests = RxVNRequest<URL>.setAndMap(requests, on: onImageURL) try self.base.perform(_requests, onImageURL: onImageURL, orientation: orientation) } }
40.194805
140
0.701777
76085bd22f19f06906adb89508a83db27e9296a3
3,011
// // App.swift // Push-ServerPackageDescription // // Created by Dan Lindsay on 2017-12-15. // import Foundation import Vapor import FluentProvider enum AppProperty: String { case title = "title" case bundleId = "bundleId" case teamId = "teamId" case keyId = "keyId" case keyPath = "keyPath" case deviceToken = "deviceToken" } final class App: Model { var storage = Storage() let title: String let bundleId: String let teamId: String let keyId: String let keyPath: String let deviceToken: String init(request: Request) throws { guard let title = request.data[AppProperty.title.rawValue]?.string, let bundleId = request.data[AppProperty.bundleId.rawValue]?.string, let teamId = request.data[AppProperty.teamId.rawValue]?.string, let keyId = request.data[AppProperty.keyId.rawValue]?.string, let keyPath = request.data[AppProperty.keyPath.rawValue]?.string, let deviceToken = request.data[AppProperty.deviceToken.rawValue]?.string else { throw Abort.badRequest } self.title = title self.bundleId = bundleId self.teamId = teamId self.keyId = keyId self.keyPath = keyPath self.deviceToken = deviceToken } required init(row: Row) throws { self.title = try row.get(AppProperty.title.rawValue) self.bundleId = try row.get(AppProperty.bundleId.rawValue) self.teamId = try row.get(AppProperty.teamId.rawValue) self.keyId = try row.get(AppProperty.keyId.rawValue) self.keyPath = try row.get(AppProperty.keyPath.rawValue) self.deviceToken = try row.get(AppProperty.deviceToken.rawValue) } func makeRow() throws -> Row { var row = Row() try row.set(AppProperty.title.rawValue, title) try row.set(AppProperty.bundleId.rawValue, bundleId) try row.set(AppProperty.teamId.rawValue, teamId) try row.set(AppProperty.keyId.rawValue, keyId) try row.set(AppProperty.keyPath.rawValue, keyPath) try row.set(AppProperty.deviceToken.rawValue, deviceToken) return row } } extension App: JSONRepresentable { func makeJSON() throws -> JSON { let row = try makeRow() return try JSON(node: row.object) } } extension App: Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { (apps) in apps.id() apps.string(AppProperty.title.rawValue) apps.string(AppProperty.bundleId.rawValue) apps.string(AppProperty.teamId.rawValue) apps.string(AppProperty.keyId.rawValue) apps.string(AppProperty.keyPath.rawValue) apps.string(AppProperty.deviceToken.rawValue) }) } static func revert(_ database: Database) throws { try database.delete(self) } }
28.40566
93
0.635337
cc521806c8638a7923198fbd5c3e07c0f9787989
225
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{ protocol c:A.c class A<T where g:d{ protocol c
25
87
0.76
5bf70ed2f65b5f09bcb1b17728b5d74b9808d274
2,441
// // ViewController.swift // JKSwiftyTableViewController // // Created by Jayesh Kawli Backup on 6/4/16. // Copyright © 2016 Jayesh Kawli Backup. All rights reserved. // import UIKit final class ViewController<Item>: UITableViewController { var undoOp: JKUndoOperation<Item> var items: [Item] { didSet { tableView.reloadData() self.navigationItem.leftBarButtonItem = items.count > 0 ? UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(self.deleteItem)) : nil self.navigationItem.rightBarButtonItem = undoOp.undoOperationAllowed ? UIBarButtonItem(barButtonSystemItem: .Undo, target: self, action: #selector(self.undoItem)) : nil } } let config: (UITableViewCell, Item) -> () init(items: [Item], config: (UITableViewCell, Item) -> (), style: UITableViewStyle, editable: Bool) { self.items = items self.config = config undoOp = JKUndoOperation(items) super.init(style: style) if editable { self.navigationItem.leftBarButtonItem = items.count > 0 ? UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(self.deleteItem)) : nil } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cellIdentifier") let item = items[indexPath.row] config(cell, item) return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { guard editingStyle == .Delete else { return } undoOp.addToListOfUndoItems(items) items.removeAtIndex(indexPath.row) } func deleteItem() { UIView.animateWithDuration(0.25) { self.tableView.editing = !self.tableView.editing } } func undoItem() { undoOp.removeFromListOfUndoItems() items = undoOp.currentItem } }
33.438356
180
0.659566
fcc7059f75d2d1b048f8c4daa1bd535e6382c337
2,177
// // AppDelegate.swift // TCActionSheetView // // Created by tancheng on 2018/7/17. // Copyright © 2018年 tancheng. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.319149
285
0.756546
8f5043ca2bcb32cc340e8557531c1b2883b0b975
1,769
import _SQLiteDflatOSShim #if os(Linux) typealias os_unfair_lock_s = pthread_mutex_t func os_unfair_lock() -> os_unfair_lock_s { var lock = os_unfair_lock_s() pthread_mutex_init(&lock, nil) return lock } func os_unfair_lock_lock(_ lock: UnsafeMutablePointer<os_unfair_lock_s>) { pthread_mutex_lock(lock) } func os_unfair_lock_unlock(_ lock: UnsafeMutablePointer<os_unfair_lock_s>) { pthread_mutex_unlock(lock) } #endif enum ThreadLocalStorage { static var transactionContext: SQLiteTransactionContext? { get { return tls_get_txn_context().map { Unmanaged<SQLiteTransactionContext>.fromOpaque($0).takeUnretainedValue() } } set(v) { let oldV = tls_get_txn_context() guard let v = v else { tls_set_txn_context(nil) if let oldV = oldV { Unmanaged<SQLiteTransactionContext>.fromOpaque(oldV).release() } return } tls_set_txn_context(Unmanaged.passRetained(v).toOpaque()) if let oldV = oldV { Unmanaged<SQLiteTransactionContext>.fromOpaque(oldV).release() } } } static var snapshot: SQLiteWorkspace.Snapshot? { get { return tls_get_sqlite_snapshot().map { Unmanaged<SQLiteWorkspace.Snapshot>.fromOpaque($0).takeUnretainedValue() } } set(v) { let oldV = tls_get_sqlite_snapshot() guard let v = v else { tls_set_sqlite_snapshot(nil) if let oldV = oldV { Unmanaged<SQLiteWorkspace.Snapshot>.fromOpaque(oldV).release() } return } tls_set_sqlite_snapshot(Unmanaged.passRetained(v).toOpaque()) if let oldV = oldV { Unmanaged<SQLiteWorkspace.Snapshot>.fromOpaque(oldV).release() } } } }
25.271429
80
0.661391
0153b0ba85ed7fbe8dfc98ac3b25c8fe81a2f422
2,611
// // DoozUnprovisionedMeshNode.swift // nordic_nrf_mesh // // Created by Alexis Barat on 06/07/2020. // import Foundation import nRFMeshProvision class DoozUnprovisionedDevice: NSObject{ //MARK: Public properties var unprovisionedDevice: UnprovisionedDevice? //MARK: Private properties private var provisioningManager: ProvisioningManager? init(messenger: FlutterBinaryMessenger, unprovisionedDevice: UnprovisionedDevice, provisioningManager: ProvisioningManager?) { super.init() self.unprovisionedDevice = unprovisionedDevice self.provisioningManager = provisioningManager _initChannel(messenger: messenger, unprovisionedDevice: unprovisionedDevice) } } private extension DoozUnprovisionedDevice { func _initChannel(messenger: FlutterBinaryMessenger, unprovisionedDevice: UnprovisionedDevice){ FlutterMethodChannel( name: FlutterChannels.DoozUnprovisionedMeshNode.getMethodChannelName(deviceUUID: unprovisionedDevice.uuid.uuidString), binaryMessenger: messenger ) .setMethodCallHandler { (call, result) in self._handleMethodCall(call, result: result) } } func _handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) { print("🥂 [\(self.classForCoder)] Received flutter call : \(call.method)") let _method = DoozUnprovisionedMeshNodeChannel(call: call) switch _method { case .error(let error): switch error { case FlutterCallError.notImplemented: result(FlutterMethodNotImplemented) case FlutterCallError.missingArguments: result(FlutterError(code: "missingArguments", message: "The provided arguments does not match required", details: nil)) case FlutterCallError.errorDecoding: result(FlutterError(code: "errorDecoding", message: "An error occured attempting to decode arguments", details: nil)) default: let nsError = error as NSError result(FlutterError(code: String(nsError.code), message: nsError.localizedDescription, details: nil)) } break case .getNumberOfElements: var nbElements = 0 if let _nbElements = provisioningManager?.provisioningCapabilities?.numberOfElements{ nbElements = Int(_nbElements) } result(nbElements) break } } }
33.909091
135
0.653773
56deab05b7b6c39a19be7947fdbf4794c036c9a3
2,791
// // SentMemesTableViewController.swift // MemeMe // // Created by Jess Gates on 6/10/16. // Copyright © 2016 Jess Gates. All rights reserved. // import UIKit class SentMemesTableViewController: UITableViewController { @IBOutlet weak var editButton: UIBarButtonItem! var memes: [MemeProperties] { return (UIApplication.shared.delegate as! AppDelegate).memes } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = false tableView!.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MemeTableCell")! let memeSelection = memes[indexPath.row] cell.textLabel!.text = memeSelection.topText + memeSelection.bottomText cell.imageView!.image = memeSelection.memedImage return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailController = storyboard?.instantiateViewController(withIdentifier: "MemeDetailsViewController") as! MemeDetailsViewController detailController.savedMeme = memes[indexPath.row] navigationController?.pushViewController(detailController, animated: true) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { tableView.beginUpdates() if editingStyle == .delete { let applicationDelegate = (UIApplication.shared.delegate as! AppDelegate) applicationDelegate.memes.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) tableView.reloadData() } tableView.endUpdates() } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) { let applicationDelegate = (UIApplication.shared.delegate as! AppDelegate) let memeToMove = memes[fromIndexPath.row] applicationDelegate.memes.remove(at: fromIndexPath.row) applicationDelegate.memes.insert(memeToMove, at: toIndexPath.row) } @IBAction func startEditing(_ sender: UIBarButtonItem) { self.isEditing = !self.isEditing } }
34.036585
143
0.672519
7af8ed6854e3b525104665fd5de1fe54c70ea60e
1,432
import Foundation public struct Page: Codable, Identifiable, Hashable { public static let index = Page(id: "index") public var id: String public var title = "" public var description = "" public var keywords = "" public var author = "" public internal(set) var content = "" public let created: Date init(id: String) { self.id = id created = .init() } public func content(_ string: String) -> Self { var page = self page.content = string return page } public func hash(into: inout Hasher) { into.combine(id) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } public var file: String { id + ".html" } func render(sections: [String]) -> String { """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport'/> <meta name="description" content="\(description)"> <meta name="keywords" content="\(keywords)"> <meta name="author" content="\(author)"> <title>\(title)</title> <link href="style.css" rel="stylesheet"> </head> <body> """ + sections.reduce(into: "") { $0 += """ <section> \($1) </section> """ } + """ </body> </html> """ } }
20.753623
93
0.562151
14eaeede1b2fa3e6dc8a3358f120ceac3bdfa415
2,847
// // AppDelegate.swift // Smash Up Counter iOS // // Created by Cyril on 08/01/2018. // Copyright © 2018 Cyril GY. All rights reserved. // import UIKit import SpriteKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var coordinator: ApplicationCoordinator? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Ensure that the view controller and its view defined in the storyboard are suitable for the application. guard let viewController = window?.rootViewController, let view = viewController.view as? SKView else { abort() } // The main coordinator drives the behaviour of the application. // Starting the main coordinator now displays the initial view. coordinator = ApplicationCoordinator(withView: view, andViewController: viewController) coordinator?.start() // The initial state and data of the application are initialized here. ApplicationState.instance.initialize() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.672131
285
0.736565
9c5242a60b9d5a89633c5f715982e5f5907124f5
1,534
// // AppDelegate.swift // NBU // // Created by Maxim Yakhin on 30.11.2020. // Copyright © 2020 Max Yakhin. 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. UserDefaults.standard.set("https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json", forKey: "jsonUrl") 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. } }
39.333333
179
0.746415
ab81b87c61139461864dcc0e453e375e93294230
3,710
import UIKit import ThemeKit import RxSwift import RxCocoa import StorageKit class MainViewController: ThemeTabBarController { private let disposeBag = DisposeBag() private let viewModel: MainViewModel private let marketModule = ThemeNavigationController(rootViewController: MarketModule.viewController()) private let balanceModule = ThemeNavigationController(rootViewController: WalletModule.viewController()) private let onboardingModule = ThemeNavigationController(rootViewController: OnboardingBalanceViewController()) private let transactionsModule = ThemeNavigationController(rootViewController: TransactionsRouter.module()) private let settingsModule = ThemeNavigationController(rootViewController: MainSettingsModule.viewController()) private var showAlerts = [(() -> ())]() init(viewModel: MainViewModel, selectedIndex: Int) { self.viewModel = viewModel super.init() self.selectedIndex = selectedIndex } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() subscribe(disposeBag, viewModel.balanceTabStateDriver) { [weak self] in self?.sync(balanceTabState: $0) } subscribe(disposeBag, viewModel.transactionsTabEnabledDriver) { [weak self] in self?.syncTransactionsTab(enabled: $0) } subscribe(disposeBag, viewModel.settingsBadgeDriver) { [weak self] in self?.setSettingsBadge(visible: $0) } subscribe(disposeBag, viewModel.releaseNotesUrlDriver) { [weak self] url in self?.showReleaseNotes(url: url) } if viewModel.needToShowJailbreakAlert { showJailbreakAlert() } viewModel.onLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) showNextAlert() } private func sync(balanceTabState: MainViewModel.BalanceTabState) { let balanceTabModule: UIViewController switch balanceTabState { case .balance: balanceTabModule = balanceModule case .onboarding: balanceTabModule = onboardingModule } viewControllers = [ marketModule, balanceTabModule, transactionsModule, settingsModule ] } private func syncTransactionsTab(enabled: Bool) { transactionsModule.viewControllers.first?.tabBarItem.isEnabled = enabled } private func setSettingsBadge(visible: Bool) { settingsModule.viewControllers.first?.tabBarItem.setDotBadge(visible: visible) } private func showReleaseNotes(url: URL?) { guard let url = url else { return } showAlerts.append({ let module = MarkdownModule.gitReleaseNotesMarkdownViewController(url: url, closeHandler: { [weak self] in self?.showNextAlert() }) DispatchQueue.main.async { self.present(ThemeNavigationController(rootViewController: module), animated: true) } }) } private func showJailbreakAlert() { showAlerts.append({ let jailbreakAlertController = NoPasscodeViewController(mode: .jailbreak, completion: { [weak self] in self?.viewModel.onSuccessJailbreakAlert() self?.showNextAlert() }) DispatchQueue.main.async { self.present(jailbreakAlertController, animated: true) } }) } private func showNextAlert() { guard let alert = showAlerts.first else { return } alert() showAlerts.removeFirst() } }
32.54386
127
0.669003
f8f48c169494e3295b3194be7fa84cd25f9eb9a0
526
import Flutter import UIKit public class SwiftFlutter3dBallPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_3d_ball", binaryMessenger: registrar.messenger()) let instance = SwiftFlutter3dBallPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } }
35.066667
103
0.779468
1d3eb9d1a7196cfd0ce956093676b4878f0ab812
13,176
// // JXAlertView.swift // ZPOperator // // Created by 杜进新 on 2017/6/25. // Copyright © 2017年 dujinxin. All rights reserved. // import UIKit enum JXAlertViewStyle : Int { case plain case list case custom } enum JXAlertViewShowPosition { case middle case bottom } private let reuseIdentifier = "reuseIdentifier" private let topBarHeight : CGFloat = 40 private let alertViewMargin : CGFloat = kScreenWidth * 0.1 private let alertViewWidth : CGFloat = UIScreen.main.bounds.width - 2 * alertViewMargin private let listHeight : CGFloat = 40 private let cancelViewHeight : CGFloat = 40 private let animateDuration : TimeInterval = 0.3 class JXAlertView: UIView { private var alertViewHeight : CGFloat = 0 private var alertViewTopHeight : CGFloat = 0 var title : String? var message : String? var actions : Array<String> = [String](){ didSet{ if actions.count > 5 { self.tableView.isScrollEnabled = true self.tableView.bounces = true self.tableView.showsVerticalScrollIndicator = true }else{ self.tableView.isScrollEnabled = false self.tableView.bounces = false self.tableView.showsVerticalScrollIndicator = false } //self.resetFrame(height: CGFloat(actions.count) * listHeight) self.resetFrame() } } var delegate : JXAlertViewDelegate? var style : JXAlertViewStyle = .plain var position : JXAlertViewShowPosition = .middle { didSet{ self.resetFrame() } } var selectRow : Int = -1 var contentHeight : CGFloat { set{//可以自己指定值带来替默认值eg: (myValue) var h : CGFloat = 0 if newValue > 0 { h = newValue alertViewHeight = newValue }else{ if style == .list{ let num : CGFloat = CGFloat(self.actions.count) h = (num > 5 ? 5.5 : num) * listHeight alertViewHeight = h } } if isUseTopBar { h += topBarHeight } self.frame = CGRect(x: alertViewMargin, y: 0, width: alertViewWidth, height: alertViewHeight + topBarHeight + cancelViewHeight + 10) } get{ return self.frame.height } } var isScrollEnabled : Bool = false { didSet{ if isScrollEnabled == true { self.tableView.isScrollEnabled = true self.tableView.bounces = true self.tableView.showsVerticalScrollIndicator = true }else{ self.tableView.isScrollEnabled = false self.tableView.bounces = false self.tableView.showsVerticalScrollIndicator = false } } } var isUseTopBar : Bool = false { didSet{ if isUseTopBar { alertViewTopHeight = topBarHeight if (self.topBarView.superview == nil){ self.addSubview(self.topBarView) } }else{ alertViewTopHeight = 0 if (self.topBarView.superview != nil){ self.topBarView.removeFromSuperview() } } self.resetFrame() } } var isSetCancelView : Bool = false { didSet{ if isSetCancelView { self.addSubview(self.cancelButton) self.resetFrame() } } } private var contentView : UIView? var customView: UIView? { didSet{ self.contentView = customView } } var topBarView: UIView = { let view = UIView() view.backgroundColor = UIColor.groupTableViewBackground return view }() lazy var tableView : UITableView = { let table = UITableView.init(frame: CGRect.init(), style: .plain) table.delegate = self table.dataSource = self table.isScrollEnabled = false table.bounces = false table.showsVerticalScrollIndicator = false table.showsHorizontalScrollIndicator = false table.separatorStyle = .none table.register(listViewCell.self, forCellReuseIdentifier: reuseIdentifier) return table }() lazy var cancelButton: UIButton = { let btn = UIButton() btn.backgroundColor = UIColor.white btn.setTitle("取消", for: UIControl.State.normal) btn.setTitleColor(JX333333Color, for: UIControl.State.normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 15) btn.addTarget(self, action: #selector(tapClick), for: UIControl.Event.touchUpInside) return btn }() lazy private var bgWindow : UIWindow = { let window = UIWindow() window.frame = UIScreen.main.bounds window.windowLevel = UIWindow.Level.alert + 1 window.backgroundColor = UIColor.clear window.isHidden = false return window }() lazy private var bgView : UIView = { let view = UIView() view.frame = UIScreen.main.bounds view.backgroundColor = UIColor.black view.alpha = 0 let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapClick)) view.addGestureRecognizer(tap) return view }() init(frame: CGRect, style:JXAlertViewStyle) { super.init(frame: frame) //self.rect = frame //self.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: frame.height) self.backgroundColor = UIColor.clear self.layer.cornerRadius = 15.0 self.clipsToBounds = true self.layer.masksToBounds = true self.style = style if style == .list { self.contentView = self.tableView }else if style == .custom{ }else{ } alertViewHeight = frame.height self.resetFrame() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func resetFrame(height:CGFloat = 0.0) { var h : CGFloat = 0 if height > 0 { h = height alertViewHeight = height }else{ if style == .list{ let num : CGFloat = CGFloat(self.actions.count) h = (num > 5 ? 5.5 : num) * listHeight alertViewHeight = h } } if isUseTopBar { h += topBarHeight } if isSetCancelView { h += cancelViewHeight + 10 } //如果为iPhoneX,则把底部的34空间让出来 // if UIScreen.main.isIphoneX { // h += 34 // } self.frame = CGRect.init(x: (UIScreen.main.bounds.width - alertViewWidth)/2, y: 0, width: alertViewWidth, height:h) } override func layoutSubviews() { super.layoutSubviews() if isUseTopBar { topBarView.frame = CGRect.init(x: 0, y: 0, width: alertViewWidth, height: alertViewTopHeight) //confirmButton.frame = CGRect.init(x: rect.width - 60, y: 0, width: 60, height: topBarHeight) } self.contentView?.frame = CGRect.init(x: 0, y: alertViewTopHeight, width: alertViewWidth, height: alertViewHeight) if isSetCancelView { cancelButton.frame = CGRect.init(x: 0, y: alertViewTopHeight + alertViewHeight + 10, width: alertViewWidth, height: cancelViewHeight) } } func show(){ self.show(inView: self.bgWindow) } func show(inView view:UIView? ,animate:Bool = true) { self.addSubview(self.contentView!) self.resetFrame(height: alertViewHeight) let superView : UIView if let v = view { superView = v }else{ superView = self.bgWindow } //let center = CGPoint.init(x: contentView.center.x, y: contentView.center.y - 64 / 2) let center = superView.center if position == .bottom { var frame = self.frame frame.origin.y = superView.frame.height self.frame = frame }else{ self.center = center } superView.addSubview(self.bgView) superView.addSubview(self) superView.isHidden = false if animate { UIView.animate(withDuration: animateDuration, delay: 0.0, options: .curveEaseIn, animations: { self.bgView.alpha = 0.5 if self.position == .bottom { var frame = self.frame frame.origin.y = superView.frame.height - self.frame.height self.frame = frame }else{ self.center = center } }, completion: { (finished) in if self.style == .list { self.tableView.reloadData() }else if self.style == .plain { } }) } } func dismiss(animate:Bool = true) { if animate { UIView.animate(withDuration: animateDuration, delay: 0.0, options: .curveEaseOut, animations: { self.bgView.alpha = 0.0 if self.position == .bottom { var frame = self.frame frame.origin.y = self.superview!.frame.height self.frame = frame }else{ self.center = self.superview!.center } }, completion: { (finished) in self.clearInfo() }) }else{ self.clearInfo() } } fileprivate func clearInfo() { bgView.removeFromSuperview() self.removeFromSuperview() bgWindow.isHidden = true } @objc private func tapClick() { self.dismiss() } fileprivate func viewDisAppear(row:Int) { // if self.delegate != nil && selectRow >= 0{ // self.delegate?.jxSelectView(self, didSelectRowAt: row) // } self.dismiss() } } extension JXAlertView : UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (actions.isEmpty == false) { return actions.count } return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return listHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! listViewCell if actions.isEmpty == false { cell.titleLabel.text = actions[indexPath.row] } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // if isUseTopBar { // selectRow = indexPath.row // }else{ // self.viewDisAppear(row: indexPath.row) // } //self.delegate?.willPresentJXAlertView!(self) self.delegate?.jxAlertView(self, clickButtonAtIndex: indexPath.row) self.dismiss() //self.delegate?.didPresentJXAlertView!(self) } } class listViewCell: UITableViewCell { lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = JX333333Color label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 14) return label }() lazy var separatorView: UIView = { let view = UIView() view.backgroundColor = UIColor.groupTableViewBackground return view }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.separatorView) self.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.titleLabel.frame = CGRect.init(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) self.separatorView.frame = CGRect.init(x: 0, y: self.bounds.height - 0.5, width: self.bounds.width, height: 0.5) } } @objc protocol JXAlertViewDelegate { func jxAlertView(_ alertView :JXAlertView, clickButtonAtIndex index:Int) @objc optional func jxAlertViewCancel(_ :JXAlertView) @objc optional func willPresentJXAlertView(_ :JXAlertView) @objc optional func didPresentJXAlertView(_ :JXAlertView) }
32.373464
145
0.568078
d5932c9e59b731ae317db157c24844b3ce06bb4d
2,823
// // Created on 18/03/2019 // Copyright © Vladimir Benkevich 2019 // import Foundation public class PincodeViewModel: ExtendedViewModel { public init(config: JetPincodeConfiguration, biomentricAuth: BiometricAuth?) { self.config = config self.biomentricAuth = biomentricAuth self.validaor = PincodeValidator(config) } fileprivate let validaor: PincodeValidator let config: JetPincodeConfiguration let biomentricAuth: BiometricAuth? lazy var deleteSymbolCommand = CommandFactory.owner(self) .action { $0.executeDeleteSymbol() } .predicate {$0.canExecuteDeleteSymbol() } .dependOn(pincode) lazy var appendSymbolCommand = CommandFactory.owner(self) .action { $0.executeAppendSymbol($1) } .dependOn(pincode) lazy var biomentricAuthCommand = CommandFactory.owner(self) .task { $0.executeBiomentricAuth() } .predicate { $0.canExecuteBiomentricAuth() } .dependOn(pincode) public weak var delegate: PincodeUIPresenterDelegate? { didSet { validaor.delegate = delegate } } lazy var pincode = Observable<String>("").validation(validaor) public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if config.showBiometricAuthOnDidAppear { biomentricAuthCommand.execute() } } fileprivate func executeAppendSymbol(_ symbol: String) { pincode.value = (pincode.value ?? "") + symbol } fileprivate func executeDeleteSymbol() { guard let code = pincode.value else { return } pincode.value = String(code.prefix(code.count - 1)) } fileprivate func canExecuteDeleteSymbol() -> Bool { guard let code = pincode.value else { return false } return !code.isEmpty && code.count < config.symbolsCount } fileprivate func executeBiomentricAuth() -> Task<String> { guard let lock = biomentricAuth else { return Task("") } return self.submit(task: lock.getCode()) .onSuccess { [delegate] in _ = delegate?.validate(code: $0) } } fileprivate func canExecuteBiomentricAuth() -> Bool { return biomentricAuth != nil } fileprivate class PincodeValidator: ValidationRule { typealias Value = String init(_ config: JetPincodeConfiguration) { self.config = config } let config: JetPincodeConfiguration weak var delegate: PincodeUIPresenterDelegate? func check(_ data: String?) -> ValidationResult { guard let code = data, config.symbolsCount == code.count else { return ValidationResult(true) } return ValidationResult(delegate?.validate(code: code) == true) } } }
29.40625
82
0.648955
69313fb679fcfc300351bcc88a0bc7594250b1a8
2,546
// // SceneDelegate.swift // BeanCounter // // Created by Robert Horrion on 10/8/19. // Copyright © 2019 Robert Horrion. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.666667
147
0.716418
75ede37a8254c89670a41597c3bee420594b7253
925
import Clibgit2 import Foundation extension Repository { /// The repository `HEAD` reference. public enum Head: Equatable { case attached(Branch) case detached(Commit) public var attached: Bool { switch self { case .attached: return true case .detached: return false } } public var detached: Bool { return !attached } public var branch: Branch? { switch self { case .attached(let branch): return branch case .detached: return nil } } public var commit: Commit? { switch self { case .attached(let branch): return branch.commit case .detached(let commit): return commit } } } }
22.02381
40
0.468108
6106ce56137e00aebe98862019f08928ae7ec2d9
340
// // HttpError.swift // // Created by Ivan Manov on 27.07.2020. // Copyright © 2020 @hellc. All rights reserved. // import Foundation public enum HttpError<E>: Error { case noInternetConnection case custom(_ error: E?) case unauthorized case forbidden case other(_ message: String?) case unsupportedResource }
18.888889
49
0.688235
c1271a33fa21c37cd520151ad01a17c59ccbb727
1,366
// // FontDisplayTableViewCell.swift // V2ex-Swift // // Created by huangfeng on 3/10/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class FontDisplayTableViewCell: BaseDetailTableViewCell { override func setup()->Void{ super.setup() self.detailMarkHidden = true self.clipsToBounds = true self.titleLabel.text = "一天,一匹小马驮着麦子去磨坊。当它驮着口袋向前跑去时,突然发现一条小河挡住了去路。小马为难了,这可怎么办呢?它向四周望了望,看见一头奶牛在河边吃草。\n\n One day, a colt took a bag of wheat to the mill. As he was running with the bag on his back, he came to a small river. The colt could not decide whether he could cross it. Looking around, he saw a cow grazing nearby." self.titleLabel.numberOfLines = 0 self.titleLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 24 self.titleLabel.baselineAdjustment = .none self.titleLabel.snp.remakeConstraints{ (make) -> Void in make.left.top.equalTo(self.contentView).offset(12) make.right.equalTo(self.contentView).offset(-12) make.height.lessThanOrEqualTo(self.contentView).offset(-12) } self.kvoController.observe(V2Style.sharedInstance, keyPath: "fontScale", options: [NSKeyValueObservingOptions.initial, NSKeyValueObservingOptions.new]) { (_, _, _) in self.titleLabel.font = v2ScaleFont(14) } } }
41.393939
328
0.688141
ebd339aa817031dc13b48b74ca5e24f25006277a
12,535
import Foundation protocol LeagueServiceV1 { func leagueList(sort: String, order: String, page: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void) func leagueGet(leagueId: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueGet?,String?) -> Void) func leagueRewardList(leagueId: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_RewardList?,String?) -> Void) func leagueRegister(leagueId: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void) func leagueQuestionNext(leagueId: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_QuestionGet?,String?) -> Void) func leagueAnswer(leagueId: String, questionId: String, answer: String, sessionId: String,completion : @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_CorrectAnswer?,String?) -> Void) } public class LeagueServiceV1Impl : LeagueServiceV1 { public func leagueList(sort: String, order: String, page: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void) { leagueList(sort: sort, order: order, page: page, sessionId: sessionId, completion: completion,force: true) } private func leagueList(sort: String, order: String, page: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(sort , forKey: "sort") params.updateValue(order , forKey: "order") params.updateValue(page , forKey: "page") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/list", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueList(sort: sort, order: order, page: page, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } public func leagueGet(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueGet?,String?) -> Void) { leagueGet(leagueId: leagueId, sessionId: sessionId, completion: completion,force: true) } private func leagueGet(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueGet?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(leagueId , forKey: "leagueId") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/league/get", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueGet(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueGet if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueGet(leagueId: leagueId, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } public func leagueRewardList(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_RewardList?,String?) -> Void) { leagueRewardList(leagueId: leagueId, sessionId: sessionId, completion: completion,force: true) } private func leagueRewardList(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_RewardList?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(leagueId , forKey: "leagueId") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/league/reward/list", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_RewardList(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_RewardList if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueRewardList(leagueId: leagueId, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } public func leagueRegister(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void) { leagueRegister(leagueId: leagueId, sessionId: sessionId, completion: completion,force: true) } private func leagueRegister(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(leagueId , forKey: "leagueId") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/league/register", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_LeagueList if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueRegister(leagueId: leagueId, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } public func leagueQuestionNext(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_QuestionGet?,String?) -> Void) { leagueQuestionNext(leagueId: leagueId, sessionId: sessionId, completion: completion,force: true) } private func leagueQuestionNext(leagueId: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_QuestionGet?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(leagueId , forKey: "leagueId") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/league/question/next", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_QuestionGet(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_QuestionGet if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueQuestionNext(leagueId: leagueId, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } public func leagueAnswer(leagueId: String, questionId: String, answer: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_CorrectAnswer?,String?) -> Void) { leagueAnswer(leagueId: leagueId, questionId: questionId, answer: answer, sessionId: sessionId, completion: completion,force: true) } private func leagueAnswer(leagueId: String, questionId: String, answer: String, sessionId: String,completion: @escaping (Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_CorrectAnswer?,String?) -> Void,force : Bool) { var params = Dictionary<String,Any>() params.updateValue(leagueId , forKey: "leagueId") params.updateValue(questionId , forKey: "questionId") params.updateValue(answer , forKey: "answer") params.updateValue(sessionId , forKey: "sessionId") let hasNounce = false RestService.post(url: PublicValue.getUrlBase() + "/api/v1/leagues/league/answer", params, completion: { (result, error) in do{ if let result = result { let serviceResponse = try Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_CorrectAnswer(serializedData: result) as Com_Vasl_Vaslapp_Modules_Game_League_Global_Proto_Holder_CorrectAnswer if serviceResponse.status == PublicValue.status_success { completion(serviceResponse,nil) } else { if serviceResponse.code == 401 && force { self.leagueAnswer(leagueId: leagueId, questionId: questionId, answer: answer, sessionId: sessionId, completion: completion,force: false) }else{ completion(serviceResponse,serviceResponse.msg) } } } }catch{ completion(nil,"") } }, force,hasNounce) } }
53.798283
229
0.612365
e298bceb8367506f1796cbeaff983c52b5495c63
1,330
// // ContentDetails.swift // YoutubeKit // // Created by Ryo Ishikawa on 12/30/2017 // // MARK: - Namespace public enum ContentDetails {} extension ContentDetails { public struct VideoList: Codable { public let definition: String public let duration: String public let caption: String public let dimension: String public let licensedContent: Bool public let projection: String } } extension ContentDetails { public struct ActivityList: Codable { public let upload: Upload? } } extension ContentDetails { public struct ChannelList: Codable { public let relatedPlaylists: RelatedPlaylists } } extension ContentDetails { public struct ChannelSectionsList: Codable { public let playlists: [String] } } extension ContentDetails { public struct SubscriptionsList: Codable { public let activityType: String public let newItemCount: Int public let totalItemCount: Int } } extension ContentDetails { public struct PlaylistItemsList: Codable { public let videoID: String public let videoPublishedAt: String? public enum CodingKeys: String, CodingKey { case videoID = "videoId" case videoPublishedAt = "videoPublishedAt" } } }
22.542373
54
0.665414
b981d06db27fbb54328d1cef34203643ee4ec9c7
5,270
// // TerminalString.swift // Chalk // // Created by Quentin Jin on 2018/10/19. // import Foundation public let chalk = Style() public let ck = Style() public struct Style { public var fgColor: TerminalColor? public var bgColor: TerminalColor? public var modifiers: Set<Modifier>? public init(fgColor: TerminalColor? = nil, bgColor: TerminalColor? = nil, modifiers: Set<Modifier>? = nil) { self.fgColor = fgColor self.bgColor = bgColor self.modifiers = modifiers } } public extension Style { func on(_ other: Style) -> Style { var style = self style.fgColor = other.fgColor ?? style.fgColor style.bgColor = other.bgColor ?? style.bgColor if style.modifiers == nil { style.modifiers = other.modifiers } else { style.modifiers?.formUnion(other.modifiers ?? []) } return style } func on(_ terminalStringConvertibles: TerminalStringConvertible...) -> TerminalString { let strings = terminalStringConvertibles .flatMap { $0.terminalString .strings .map { ($0.0, on($0.1)) } } return TerminalString(strings: strings) } } public extension Style { func modify(_ modifier: Modifier) -> Style { var style = self if style.modifiers == nil { style.modifiers = [modifier] } else { style.modifiers!.insert(modifier) } return style } var reset: Style { modify(.reset) } var bold: Style { modify(.bold) } var faint: Style { modify(.faint) } var dim: Style { // faint faint } var italic: Style { modify(.italic) } var underline: Style { modify(.underline) } var blink: Style { modify(.blink) } var reverse: Style { modify(.reverse) } var conceal: Style { modify(.conceal) } var hidden: Style { // conceal conceal } var crossedOut: Style { modify(.crossedOut) } var strikethrough: Style { // crossedOut crossedOut } } public extension Style { func fg(ansi16: ANSI16Color) -> Style { var style = self style.fgColor = ansi16 return style } func bg(ansi16: ANSI16Color) -> Style { var style = self style.bgColor = ansi16 return style } var black: Style { fg(ansi16: .black) } var red: Style { fg(ansi16: .red) } var green: Style { fg(ansi16: .green) } var yellow: Style { fg(ansi16: .yellow) } var blue: Style { fg(ansi16: .blue) } var magenta: Style { fg(ansi16: .magenta) } var cyan: Style { fg(ansi16: .cyan) } var white: Style { fg(ansi16: .white) } var blackBright: Style { fg(ansi16: .blackBright) } var redBright: Style { fg(ansi16: .redBright) } var greenBright: Style { fg(ansi16: .greenBright) } var yellowBright: Style { fg(ansi16: .yellowBright) } var blueBright: Style { fg(ansi16: .blueBright) } var magentaBright: Style { fg(ansi16: .magentaBright) } var cyanBright: Style { fg(ansi16: .cyanBright) } var whiteBright: Style { fg(ansi16: .whiteBright) } var gray: Style { blackBright } var bgBlack: Style { bg(ansi16: .black) } var bgRed: Style { bg(ansi16: .red) } var bgGreen: Style { bg(ansi16: .green) } var bgYellow: Style { bg(ansi16: .yellow) } var bgBlue: Style { bg(ansi16: .blue) } var bgMagenta: Style { bg(ansi16: .magenta) } var bgCyan: Style { bg(ansi16: .cyan) } var bgWhite: Style { bg(ansi16: .white) } var bgBlackBright: Style { bg(ansi16: .blackBright) } var bgRedBright: Style { bg(ansi16: .redBright) } var bgGreenBright: Style { bg(ansi16: .greenBright) } var bgYellowBright: Style { bg(ansi16: .yellowBright) } var bgBlueBright: Style { bg(ansi16: .blueBright) } var bgMagentaBright: Style { bg(ansi16: .magentaBright) } var bgCyanBright: Style { bg(ansi16: .cyanBright) } var bgWhiteBright: Style { bg(ansi16: .whiteBright) } var bgGray: Style { bgBlackBright } } public extension Style { func fg(_ color: RainbowColor) -> Style { var style = self style.fgColor = color return style } func bg(_ color: RainbowColor) -> Style { var style = self style.bgColor = color return style } func fg(_ color: ANSI16Color) -> Style { var style = self style.fgColor = color return style } func bg(_ color: ANSI16Color) -> Style { var style = self style.bgColor = color return style } }
18.109966
91
0.527514
e291afcc8b94729c7132e42bbe8fc07655e994e7
11,001
// // NKInputView.swift // NumericKeyboard // // Created by Marc Jordant on 23/07/16. // Copyright © 2016 singleTapps. All rights reserved. // import UIKit /** The class of the input view that shows a numeric keyboard - Author: Marc Jordant This numeric keyboard input view is intended to be a replacement of the default numeric keyboard on iPad. It shows only numerical keys instead of all symbols (including letters) */ open class NKInputView: UIView, UIInputViewAudioFeedback { // MARK: - Enum - /** The type of the numeric keyboard */ public enum NKKeyboardType : Int { /** A number pad (0-9). Suitable for PIN entry. */ case numberPad /** A number pad with a decimal point. */ case decimalPad /** A phone pad (0-9, +). */ case phonePad } /** The type of the return key of the keyboard. You can use the 4 predefined values: - Default - Search - Next - Save or use the Custom value and pass it a custom text */ public enum NKKeyboardReturnKeyType { /** Shows the text "Return" in the return key */ case `default` /** Shows the text "Search" in the return key */ case search /** Shows the text "Next" in the return key */ case next /** Shows the text "Save" in the return key */ case save /** Shows the text "Go" in the return key */ case go /** Shows the text "Join" in the return key */ case join /** Shows the text "Route" in the return key */ case route /** Shows the text "Send" in the return key */ case send /** Shows the text "Done" in the return key */ case done /** Use this value for specifying a custom text - parameters: - text: the custom text to use for the return key */ case custom(text: String, actionButton: Bool) func text() -> String { switch self { case .custom(let text, _): return text default: let podBundle = Bundle(for: NKInputView.self) let bundleURL = podBundle.url(forResource: "NumericKeyboard", withExtension: "bundle") let bundle = Bundle(url: bundleURL!)! return NSLocalizedString("NumericKeyboard.return-key.\(self)", bundle: bundle, comment: "") } } func backgroundColor() -> UIColor? { switch self { case .save, .search, .go: return UIColor(red: 9/255.0, green: 126/255.0, blue: 254/255.0, alpha: 1) case .custom(_, let actionButton) where actionButton: return UIColor(red: 9/255.0, green: 126/255.0, blue: 254/255.0, alpha: 1) default: return nil } } func textColor() -> UIColor? { switch self { case .save, .search, .go: return UIColor.white case .custom(_, let actionButton) where actionButton: return UIColor.white default: return nil } } } /** Indexes of additional buttons (those that can be added on the left) */ public enum AdditionalButtonIndex { case one, two, three, four } // MARK: - vars - fileprivate weak var textView: UITextInput? // MARK: - Private vars - fileprivate let TAG_B_DISMISS = 12 fileprivate let TAG_B_BACKWARD = 13 fileprivate let TAG_B_RETURN = 14 fileprivate var bLeft1Action: (() -> Void)? fileprivate var bLeft2Action: (() -> Void)? fileprivate var bLeft3Action: (() -> Void)? fileprivate var bLeft4Action: (() -> Void)? // MARK: - Outlets - @IBOutlet fileprivate var bNext: NKKeyboardButton! @IBOutlet fileprivate var bPlus: UIButton! @IBOutlet fileprivate var bDot: UIButton! @IBOutlet fileprivate var bLeft1: NKKeyboardButton! @IBOutlet fileprivate var bLeft2: NKKeyboardButton! @IBOutlet fileprivate var bLeft3: NKKeyboardButton! @IBOutlet fileprivate var bLeft4: NKKeyboardButton! // MARK: - Static methods - /** Sets a NKInputView instance as the inputView of the specified textField or textView. - returns: The NKInputView instance if the inputView has been set, nil otherwise - parameters: - textView: The textField or textView on which set this numeric keyboard input view. - type: the type of the numeric keyboard. Default value is NKKeyboardType.DecimalPad - returnKeyType: the type of the return key. Default value is NKKeyboardReturnKeyType.Default - important: Only affect the input view on iPad. Do nothing on iPhone or iPod */ @discardableResult public static func with(_ textView: UITextInput, type: NKKeyboardType = .decimalPad, returnKeyType: NKKeyboardReturnKeyType = .default) -> NKInputView? { guard UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad else { // This is not an iPad, do nothing return nil } // Load the view from xib let podBundle = Bundle(for: NKInputView.self) let bundleURL = podBundle.url(forResource: "NumericKeyboard", withExtension: "bundle") let bundle = Bundle(url: bundleURL!)! let nibName = "NumericKeyboard" let nib = UINib(nibName: nibName, bundle: bundle) let instance = nib.instantiate(withOwner: self, options: nil).first as! NKInputView instance.setup(textView, type: type, returnKeyType: returnKeyType) return instance } /** Sets the additional button at the given index. Up to 4 additional buttons can be added on the left of the keyboard. The place of each is specified with the index parameter. - parameter title: the title of the button - parameter at: the index of the button - parameter action: the block of code to execute when the UIControlEvents.touchUpInside event is triggered for this button */ open func setAdditionalButton(title: String, at index: AdditionalButtonIndex, action: @escaping () -> Void) { removeAdditionalButton(at: index) var button = bLeft1 switch index { case .one: button = bLeft1 bLeft1Action = action case .two: button = bLeft2 bLeft2Action = action case .three: button = bLeft3 bLeft3Action = action case .four: button = bLeft4 bLeft4Action = action } button?.returnType = .custom(text: title, actionButton: true) button?.isHidden = false button?.addTarget(self, action: #selector(NKInputView.additionalButtonTouched(sender:)), for: UIControl.Event.touchUpInside) } /** Removes the additional button at the given index. - parameter at: the index of the button */ open func removeAdditionalButton(at index: AdditionalButtonIndex) { var button = bLeft1 switch index { case .one: button = bLeft1 case .two: button = bLeft2 case .three: button = bLeft3 case .four: button = bLeft4 } button?.isHidden = true button?.removeTarget(nil, action: nil, for: UIControl.Event.touchUpInside) } // MARK: - Private methods - // Initialize the view fileprivate func setup(_ textView: UITextInput, type: NKKeyboardType, returnKeyType: NKKeyboardReturnKeyType = .default) { self.textView = textView if let textView = self.textView as? UITextField { textView.inputView = self } if let textView = self.textView as? UITextView { textView.inputView = self } if #available(iOS 9.0, *) { removeToolbar() } bNext.returnType = returnKeyType switch type { case .decimalPad: bPlus.isHidden = true case .numberPad: bDot.isHidden = true bPlus.isHidden = true case .phonePad: bDot.isHidden = true } bDot.setTitle((Locale.current as NSLocale).object(forKey: NSLocale.Key.decimalSeparator) as? String, for: UIControl.State.normal) } // Remove the Undo/Redo toolbar @available(iOS 9.0, *) fileprivate func removeToolbar() { var item : UITextInputAssistantItem? if let txtView = self.textView as? UITextField { item = txtView.inputAssistantItem } if let txtView = self.textView as? UITextView { item = txtView.inputAssistantItem } item?.leadingBarButtonGroups = [] item?.trailingBarButtonGroups = [] } fileprivate func isTextField() -> Bool { if let _ = self.textView as? UITextField { return true } return false } fileprivate func isTextView() -> Bool { if let _ = self.textView as? UITextView { return true } return false } // MARK: - Size management - override open var intrinsicContentSize : CGSize { return CGSize(width: 100, height: 313) } // MARK: - UIInputViewAudioFeedback - open var enableInputClicksWhenVisible: Bool { return true } // MARK: - Events - @IBAction fileprivate func buttonPressed(_ sender: UIButton) { UIDevice.current.playInputClick() switch sender.tag { case let (x) where x < 12: let decimalChar = (Locale.current as NSLocale).object(forKey: NSLocale.Key.decimalSeparator) as? String ?? "." let buttonsValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", decimalChar, "+"] let char = buttonsValues[sender.tag] textView?.insertText(char) if isTextField() { NotificationCenter.default.post(name: UITextField.textDidChangeNotification, object: self.textView) } else if isTextView() { NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: self.textView) } case TAG_B_BACKWARD: textView?.deleteBackward() if isTextField() { NotificationCenter.default.post(name: UITextField.textDidChangeNotification, object: self.textView) } else if isTextView() { NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: self.textView) } case TAG_B_RETURN: if isTextField() { let textField = textView as! UITextField let _ = textField.delegate?.textFieldShouldReturn?(textField) } else if isTextView() { textView?.insertText("\n") NotificationCenter.default.post(name: UITextView.textDidChangeNotification, object: self.textView) } case TAG_B_DISMISS: if let textView = self.textView as? UITextField { textView.resignFirstResponder() } if let textView = self.textView as? UITextView { textView.resignFirstResponder() } default: break } } @objc fileprivate func additionalButtonTouched(sender: UIButton) { switch sender { case bLeft1: bLeft1Action?() case bLeft2: bLeft2Action?() case bLeft3: bLeft3Action?() case bLeft4: bLeft4Action?() default: break } } }
25.524362
178
0.636397
d51a40bdef3dc31e0ee7b9f6fbb609604818608f
850
import Auth import SwiftUI @main struct RockMapApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate @StateObject private var appStore = AppStore.shared var body: some Scene { WindowGroup { appStore.rootView .environmentObject(appStore) } } } final class AppStore: ObservableObject { static let shared: AppStore = AppStore() private init() { rootViewType = AuthAccessor().isLoggedIn ? .main : .login } enum RootViewType { case main case login } @Published var rootViewType: RootViewType = .login @ViewBuilder var rootView: some View { switch rootViewType { case .main: MainTabView() case .login: LoginView() } } }
18.888889
75
0.587059
01729a0eaf535bea3ef6590317a3849655aac16d
146,024
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: operations.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // 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 // // 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 import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public enum Fuzzilli_Protobuf_UnaryOperator: SwiftProtobuf.Enum { public typealias RawValue = Int case preInc // = 0 case preDec // = 1 case postInc // = 2 case postDec // = 3 case logicalNot // = 4 case bitwiseNot // = 5 case plus // = 6 case minus // = 7 case UNRECOGNIZED(Int) public init() { self = .preInc } public init?(rawValue: Int) { switch rawValue { case 0: self = .preInc case 1: self = .preDec case 2: self = .postInc case 3: self = .postDec case 4: self = .logicalNot case 5: self = .bitwiseNot case 6: self = .plus case 7: self = .minus default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .preInc: return 0 case .preDec: return 1 case .postInc: return 2 case .postDec: return 3 case .logicalNot: return 4 case .bitwiseNot: return 5 case .plus: return 6 case .minus: return 7 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Fuzzilli_Protobuf_UnaryOperator: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Fuzzilli_Protobuf_UnaryOperator] = [ .preInc, .preDec, .postInc, .postDec, .logicalNot, .bitwiseNot, .plus, .minus, ] } #endif // swift(>=4.2) public enum Fuzzilli_Protobuf_BinaryOperator: SwiftProtobuf.Enum { public typealias RawValue = Int case add // = 0 case sub // = 1 case mul // = 2 case div // = 3 case mod // = 4 case bitAnd // = 5 case bitOr // = 6 case logicalAnd // = 7 case logicalOr // = 8 case xor // = 9 case lshift // = 10 case rshift // = 11 case exp // = 12 case unrshift // = 13 case UNRECOGNIZED(Int) public init() { self = .add } public init?(rawValue: Int) { switch rawValue { case 0: self = .add case 1: self = .sub case 2: self = .mul case 3: self = .div case 4: self = .mod case 5: self = .bitAnd case 6: self = .bitOr case 7: self = .logicalAnd case 8: self = .logicalOr case 9: self = .xor case 10: self = .lshift case 11: self = .rshift case 12: self = .exp case 13: self = .unrshift default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .add: return 0 case .sub: return 1 case .mul: return 2 case .div: return 3 case .mod: return 4 case .bitAnd: return 5 case .bitOr: return 6 case .logicalAnd: return 7 case .logicalOr: return 8 case .xor: return 9 case .lshift: return 10 case .rshift: return 11 case .exp: return 12 case .unrshift: return 13 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Fuzzilli_Protobuf_BinaryOperator: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Fuzzilli_Protobuf_BinaryOperator] = [ .add, .sub, .mul, .div, .mod, .bitAnd, .bitOr, .logicalAnd, .logicalOr, .xor, .lshift, .rshift, .exp, .unrshift, ] } #endif // swift(>=4.2) public enum Fuzzilli_Protobuf_Comparator: SwiftProtobuf.Enum { public typealias RawValue = Int case equal // = 0 case strictEqual // = 1 case notEqual // = 2 case strictNotEqual // = 3 case lessThan // = 4 case lessThanOrEqual // = 5 case greaterThan // = 6 case greaterThanOrEqual // = 7 case UNRECOGNIZED(Int) public init() { self = .equal } public init?(rawValue: Int) { switch rawValue { case 0: self = .equal case 1: self = .strictEqual case 2: self = .notEqual case 3: self = .strictNotEqual case 4: self = .lessThan case 5: self = .lessThanOrEqual case 6: self = .greaterThan case 7: self = .greaterThanOrEqual default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .equal: return 0 case .strictEqual: return 1 case .notEqual: return 2 case .strictNotEqual: return 3 case .lessThan: return 4 case .lessThanOrEqual: return 5 case .greaterThan: return 6 case .greaterThanOrEqual: return 7 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Fuzzilli_Protobuf_Comparator: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Fuzzilli_Protobuf_Comparator] = [ .equal, .strictEqual, .notEqual, .strictNotEqual, .lessThan, .lessThanOrEqual, .greaterThan, .greaterThanOrEqual, ] } #endif // swift(>=4.2) public struct Fuzzilli_Protobuf_LoadInteger { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadBigInt { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadFloat { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: Double = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadString { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadBoolean { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: Bool = false public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadUndefined { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadNull { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadRegExp { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var value: String = String() public var flags: UInt32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CreateObject { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyNames: [String] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CreateArray { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CreateTemplateString { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var parts: [String] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CreateObjectWithSpread { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyNames: [String] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CreateArrayWithSpread { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var spreads: [Bool] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadBuiltin { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var builtinName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_StoreProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_DeleteProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadElement { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var index: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_StoreElement { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var index: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_DeleteElement { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var index: Int64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadComputedProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_StoreComputedProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_DeleteComputedProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_TypeOf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_InstanceOf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_In { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginPlainFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndPlainFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginStrictFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndStrictFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginArrowFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndArrowFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginGeneratorFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndGeneratorFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginAsyncFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndAsyncFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginAsyncArrowFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndAsyncArrowFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginAsyncGeneratorFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var signature: Fuzzilli_Protobuf_FunctionSignature { get {return _signature ?? Fuzzilli_Protobuf_FunctionSignature()} set {_signature = newValue} } /// Returns true if `signature` has been explicitly set. public var hasSignature: Bool {return self._signature != nil} /// Clears the value of `signature`. Subsequent reads from it will return its default value. public mutating func clearSignature() {self._signature = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _signature: Fuzzilli_Protobuf_FunctionSignature? = nil } public struct Fuzzilli_Protobuf_EndAsyncGeneratorFunctionDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Return { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Yield { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_YieldEach { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Await { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallMethod { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var methodName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallComputedMethod { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallFunction { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Construct { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallFunctionWithSpread { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var spreads: [Bool] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_UnaryOperation { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var op: Fuzzilli_Protobuf_UnaryOperator = .preInc public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BinaryOperation { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var op: Fuzzilli_Protobuf_BinaryOperator = .add public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BinaryOperationAndReassign { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var op: Fuzzilli_Protobuf_BinaryOperator = .add public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Dup { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Reassign { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Compare { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var op: Fuzzilli_Protobuf_Comparator = .equal public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_ConditionalOperation { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Eval { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var code: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginClassDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var hasSuperclass_p: Bool = false public var constructorParameters: [Fuzzilli_Protobuf_Type] = [] public var instanceProperties: [String] = [] public var instanceMethodNames: [String] = [] public var instanceMethodSignatures: [Fuzzilli_Protobuf_FunctionSignature] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginMethodDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var numParameters: UInt32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndClassDefinition { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallSuperConstructor { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_CallSuperMethod { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var methodName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadSuperProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_StoreSuperProperty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var propertyName: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginWith { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndWith { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_LoadFromScope { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var id: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_StoreToScope { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var id: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginIf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginElse { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndIf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginSwitch { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginSwitchCase { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var fallsThrough: Bool = false public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndSwitch { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginWhile { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var comparator: Fuzzilli_Protobuf_Comparator = .equal public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndWhile { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginDoWhile { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var comparator: Fuzzilli_Protobuf_Comparator = .equal public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndDoWhile { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginFor { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var comparator: Fuzzilli_Protobuf_Comparator = .equal public var op: Fuzzilli_Protobuf_BinaryOperator = .add public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndFor { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginForIn { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndForIn { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginForOf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndForOf { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Break { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Continue { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginTry { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginCatch { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginFinally { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndTryCatch { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_ThrowException { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginCodeString { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndCodeString { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_BeginBlockStatement { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_EndBlockStatement { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } public struct Fuzzilli_Protobuf_Nop { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "fuzzilli.protobuf" extension Fuzzilli_Protobuf_UnaryOperator: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "PRE_INC"), 1: .same(proto: "PRE_DEC"), 2: .same(proto: "POST_INC"), 3: .same(proto: "POST_DEC"), 4: .same(proto: "LOGICAL_NOT"), 5: .same(proto: "BITWISE_NOT"), 6: .same(proto: "PLUS"), 7: .same(proto: "MINUS"), ] } extension Fuzzilli_Protobuf_BinaryOperator: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "ADD"), 1: .same(proto: "SUB"), 2: .same(proto: "MUL"), 3: .same(proto: "DIV"), 4: .same(proto: "MOD"), 5: .same(proto: "BIT_AND"), 6: .same(proto: "BIT_OR"), 7: .same(proto: "LOGICAL_AND"), 8: .same(proto: "LOGICAL_OR"), 9: .same(proto: "XOR"), 10: .same(proto: "LSHIFT"), 11: .same(proto: "RSHIFT"), 12: .same(proto: "EXP"), 13: .same(proto: "UNRSHIFT"), ] } extension Fuzzilli_Protobuf_Comparator: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "EQUAL"), 1: .same(proto: "STRICT_EQUAL"), 2: .same(proto: "NOT_EQUAL"), 3: .same(proto: "STRICT_NOT_EQUAL"), 4: .same(proto: "LESS_THAN"), 5: .same(proto: "LESS_THAN_OR_EQUAL"), 6: .same(proto: "GREATER_THAN"), 7: .same(proto: "GREATER_THAN_OR_EQUAL"), ] } extension Fuzzilli_Protobuf_LoadInteger: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadInteger" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.value) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.value != 0 { try visitor.visitSingularInt64Field(value: self.value, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadInteger, rhs: Fuzzilli_Protobuf_LoadInteger) -> Bool { if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadBigInt: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadBigInt" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.value) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.value != 0 { try visitor.visitSingularInt64Field(value: self.value, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadBigInt, rhs: Fuzzilli_Protobuf_LoadBigInt) -> Bool { if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadFloat: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadFloat" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularDoubleField(value: &self.value) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.value != 0 { try visitor.visitSingularDoubleField(value: self.value, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadFloat, rhs: Fuzzilli_Protobuf_LoadFloat) -> Bool { if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadString: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadString" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.value) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.value.isEmpty { try visitor.visitSingularStringField(value: self.value, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadString, rhs: Fuzzilli_Protobuf_LoadString) -> Bool { if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadBoolean: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadBoolean" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self.value) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.value != false { try visitor.visitSingularBoolField(value: self.value, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadBoolean, rhs: Fuzzilli_Protobuf_LoadBoolean) -> Bool { if lhs.value != rhs.value {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadUndefined: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadUndefined" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadUndefined, rhs: Fuzzilli_Protobuf_LoadUndefined) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadNull: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadNull" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadNull, rhs: Fuzzilli_Protobuf_LoadNull) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadRegExp: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadRegExp" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "value"), 2: .same(proto: "flags"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.value) }() case 2: try { try decoder.decodeSingularUInt32Field(value: &self.flags) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.value.isEmpty { try visitor.visitSingularStringField(value: self.value, fieldNumber: 1) } if self.flags != 0 { try visitor.visitSingularUInt32Field(value: self.flags, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadRegExp, rhs: Fuzzilli_Protobuf_LoadRegExp) -> Bool { if lhs.value != rhs.value {return false} if lhs.flags != rhs.flags {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CreateObject: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CreateObject" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyNames"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedStringField(value: &self.propertyNames) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyNames.isEmpty { try visitor.visitRepeatedStringField(value: self.propertyNames, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CreateObject, rhs: Fuzzilli_Protobuf_CreateObject) -> Bool { if lhs.propertyNames != rhs.propertyNames {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CreateArray: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CreateArray" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CreateArray, rhs: Fuzzilli_Protobuf_CreateArray) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CreateTemplateString: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CreateTemplateString" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "parts"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedStringField(value: &self.parts) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.parts.isEmpty { try visitor.visitRepeatedStringField(value: self.parts, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CreateTemplateString, rhs: Fuzzilli_Protobuf_CreateTemplateString) -> Bool { if lhs.parts != rhs.parts {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CreateObjectWithSpread: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CreateObjectWithSpread" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyNames"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedStringField(value: &self.propertyNames) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyNames.isEmpty { try visitor.visitRepeatedStringField(value: self.propertyNames, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CreateObjectWithSpread, rhs: Fuzzilli_Protobuf_CreateObjectWithSpread) -> Bool { if lhs.propertyNames != rhs.propertyNames {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CreateArrayWithSpread: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CreateArrayWithSpread" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "spreads"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedBoolField(value: &self.spreads) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.spreads.isEmpty { try visitor.visitPackedBoolField(value: self.spreads, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CreateArrayWithSpread, rhs: Fuzzilli_Protobuf_CreateArrayWithSpread) -> Bool { if lhs.spreads != rhs.spreads {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadBuiltin: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadBuiltin" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "builtinName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.builtinName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.builtinName.isEmpty { try visitor.visitSingularStringField(value: self.builtinName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadBuiltin, rhs: Fuzzilli_Protobuf_LoadBuiltin) -> Bool { if lhs.builtinName != rhs.builtinName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadProperty" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.propertyName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyName.isEmpty { try visitor.visitSingularStringField(value: self.propertyName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadProperty, rhs: Fuzzilli_Protobuf_LoadProperty) -> Bool { if lhs.propertyName != rhs.propertyName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_StoreProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".StoreProperty" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.propertyName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyName.isEmpty { try visitor.visitSingularStringField(value: self.propertyName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_StoreProperty, rhs: Fuzzilli_Protobuf_StoreProperty) -> Bool { if lhs.propertyName != rhs.propertyName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_DeleteProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".DeleteProperty" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.propertyName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyName.isEmpty { try visitor.visitSingularStringField(value: self.propertyName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_DeleteProperty, rhs: Fuzzilli_Protobuf_DeleteProperty) -> Bool { if lhs.propertyName != rhs.propertyName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadElement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadElement" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "index"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.index) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.index != 0 { try visitor.visitSingularInt64Field(value: self.index, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadElement, rhs: Fuzzilli_Protobuf_LoadElement) -> Bool { if lhs.index != rhs.index {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_StoreElement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".StoreElement" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "index"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.index) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.index != 0 { try visitor.visitSingularInt64Field(value: self.index, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_StoreElement, rhs: Fuzzilli_Protobuf_StoreElement) -> Bool { if lhs.index != rhs.index {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_DeleteElement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".DeleteElement" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "index"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.index) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.index != 0 { try visitor.visitSingularInt64Field(value: self.index, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_DeleteElement, rhs: Fuzzilli_Protobuf_DeleteElement) -> Bool { if lhs.index != rhs.index {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadComputedProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadComputedProperty" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadComputedProperty, rhs: Fuzzilli_Protobuf_LoadComputedProperty) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_StoreComputedProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".StoreComputedProperty" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_StoreComputedProperty, rhs: Fuzzilli_Protobuf_StoreComputedProperty) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_DeleteComputedProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".DeleteComputedProperty" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_DeleteComputedProperty, rhs: Fuzzilli_Protobuf_DeleteComputedProperty) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_TypeOf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".TypeOf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_TypeOf, rhs: Fuzzilli_Protobuf_TypeOf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_InstanceOf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".InstanceOf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_InstanceOf, rhs: Fuzzilli_Protobuf_InstanceOf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_In: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".In" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_In, rhs: Fuzzilli_Protobuf_In) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginPlainFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginPlainFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginPlainFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginPlainFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndPlainFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndPlainFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndPlainFunctionDefinition, rhs: Fuzzilli_Protobuf_EndPlainFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginStrictFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginStrictFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginStrictFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginStrictFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndStrictFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndStrictFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndStrictFunctionDefinition, rhs: Fuzzilli_Protobuf_EndStrictFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginArrowFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginArrowFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginArrowFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginArrowFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndArrowFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndArrowFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndArrowFunctionDefinition, rhs: Fuzzilli_Protobuf_EndArrowFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginGeneratorFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginGeneratorFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginGeneratorFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginGeneratorFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndGeneratorFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndGeneratorFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndGeneratorFunctionDefinition, rhs: Fuzzilli_Protobuf_EndGeneratorFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginAsyncFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginAsyncFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginAsyncFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginAsyncFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndAsyncFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndAsyncFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndAsyncFunctionDefinition, rhs: Fuzzilli_Protobuf_EndAsyncFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginAsyncArrowFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginAsyncArrowFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginAsyncArrowFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginAsyncArrowFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndAsyncArrowFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndAsyncArrowFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndAsyncArrowFunctionDefinition, rhs: Fuzzilli_Protobuf_EndAsyncArrowFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginAsyncGeneratorFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginAsyncGeneratorFunctionDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "signature"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._signature) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._signature { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginAsyncGeneratorFunctionDefinition, rhs: Fuzzilli_Protobuf_BeginAsyncGeneratorFunctionDefinition) -> Bool { if lhs._signature != rhs._signature {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndAsyncGeneratorFunctionDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndAsyncGeneratorFunctionDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndAsyncGeneratorFunctionDefinition, rhs: Fuzzilli_Protobuf_EndAsyncGeneratorFunctionDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Return: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Return" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Return, rhs: Fuzzilli_Protobuf_Return) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Yield: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Yield" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Yield, rhs: Fuzzilli_Protobuf_Yield) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_YieldEach: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".YieldEach" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_YieldEach, rhs: Fuzzilli_Protobuf_YieldEach) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Await: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Await" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Await, rhs: Fuzzilli_Protobuf_Await) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallMethod: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallMethod" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "methodName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.methodName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.methodName.isEmpty { try visitor.visitSingularStringField(value: self.methodName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallMethod, rhs: Fuzzilli_Protobuf_CallMethod) -> Bool { if lhs.methodName != rhs.methodName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallComputedMethod: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallComputedMethod" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallComputedMethod, rhs: Fuzzilli_Protobuf_CallComputedMethod) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallFunction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallFunction" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallFunction, rhs: Fuzzilli_Protobuf_CallFunction) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Construct: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Construct" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Construct, rhs: Fuzzilli_Protobuf_Construct) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallFunctionWithSpread: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallFunctionWithSpread" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "spreads"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedBoolField(value: &self.spreads) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.spreads.isEmpty { try visitor.visitPackedBoolField(value: self.spreads, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallFunctionWithSpread, rhs: Fuzzilli_Protobuf_CallFunctionWithSpread) -> Bool { if lhs.spreads != rhs.spreads {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_UnaryOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".UnaryOperation" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.op) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.op != .preInc { try visitor.visitSingularEnumField(value: self.op, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_UnaryOperation, rhs: Fuzzilli_Protobuf_UnaryOperation) -> Bool { if lhs.op != rhs.op {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BinaryOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BinaryOperation" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.op) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.op != .add { try visitor.visitSingularEnumField(value: self.op, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BinaryOperation, rhs: Fuzzilli_Protobuf_BinaryOperation) -> Bool { if lhs.op != rhs.op {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BinaryOperationAndReassign: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BinaryOperationAndReassign" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.op) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.op != .add { try visitor.visitSingularEnumField(value: self.op, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BinaryOperationAndReassign, rhs: Fuzzilli_Protobuf_BinaryOperationAndReassign) -> Bool { if lhs.op != rhs.op {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Dup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Dup" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Dup, rhs: Fuzzilli_Protobuf_Dup) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Reassign: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Reassign" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Reassign, rhs: Fuzzilli_Protobuf_Reassign) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Compare: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Compare" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "op"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.op) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.op != .equal { try visitor.visitSingularEnumField(value: self.op, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Compare, rhs: Fuzzilli_Protobuf_Compare) -> Bool { if lhs.op != rhs.op {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_ConditionalOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ConditionalOperation" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_ConditionalOperation, rhs: Fuzzilli_Protobuf_ConditionalOperation) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Eval: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Eval" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "code"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.code) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.code.isEmpty { try visitor.visitSingularStringField(value: self.code, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Eval, rhs: Fuzzilli_Protobuf_Eval) -> Bool { if lhs.code != rhs.code {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginClassDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginClassDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "hasSuperclass"), 2: .same(proto: "constructorParameters"), 3: .same(proto: "instanceProperties"), 4: .same(proto: "instanceMethodNames"), 5: .same(proto: "instanceMethodSignatures"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self.hasSuperclass_p) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.constructorParameters) }() case 3: try { try decoder.decodeRepeatedStringField(value: &self.instanceProperties) }() case 4: try { try decoder.decodeRepeatedStringField(value: &self.instanceMethodNames) }() case 5: try { try decoder.decodeRepeatedMessageField(value: &self.instanceMethodSignatures) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.hasSuperclass_p != false { try visitor.visitSingularBoolField(value: self.hasSuperclass_p, fieldNumber: 1) } if !self.constructorParameters.isEmpty { try visitor.visitRepeatedMessageField(value: self.constructorParameters, fieldNumber: 2) } if !self.instanceProperties.isEmpty { try visitor.visitRepeatedStringField(value: self.instanceProperties, fieldNumber: 3) } if !self.instanceMethodNames.isEmpty { try visitor.visitRepeatedStringField(value: self.instanceMethodNames, fieldNumber: 4) } if !self.instanceMethodSignatures.isEmpty { try visitor.visitRepeatedMessageField(value: self.instanceMethodSignatures, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginClassDefinition, rhs: Fuzzilli_Protobuf_BeginClassDefinition) -> Bool { if lhs.hasSuperclass_p != rhs.hasSuperclass_p {return false} if lhs.constructorParameters != rhs.constructorParameters {return false} if lhs.instanceProperties != rhs.instanceProperties {return false} if lhs.instanceMethodNames != rhs.instanceMethodNames {return false} if lhs.instanceMethodSignatures != rhs.instanceMethodSignatures {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginMethodDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginMethodDefinition" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "numParameters"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self.numParameters) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.numParameters != 0 { try visitor.visitSingularUInt32Field(value: self.numParameters, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginMethodDefinition, rhs: Fuzzilli_Protobuf_BeginMethodDefinition) -> Bool { if lhs.numParameters != rhs.numParameters {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndClassDefinition: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndClassDefinition" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndClassDefinition, rhs: Fuzzilli_Protobuf_EndClassDefinition) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallSuperConstructor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallSuperConstructor" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallSuperConstructor, rhs: Fuzzilli_Protobuf_CallSuperConstructor) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_CallSuperMethod: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".CallSuperMethod" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "methodName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.methodName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.methodName.isEmpty { try visitor.visitSingularStringField(value: self.methodName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_CallSuperMethod, rhs: Fuzzilli_Protobuf_CallSuperMethod) -> Bool { if lhs.methodName != rhs.methodName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadSuperProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadSuperProperty" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.propertyName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyName.isEmpty { try visitor.visitSingularStringField(value: self.propertyName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadSuperProperty, rhs: Fuzzilli_Protobuf_LoadSuperProperty) -> Bool { if lhs.propertyName != rhs.propertyName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_StoreSuperProperty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".StoreSuperProperty" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "propertyName"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.propertyName) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.propertyName.isEmpty { try visitor.visitSingularStringField(value: self.propertyName, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_StoreSuperProperty, rhs: Fuzzilli_Protobuf_StoreSuperProperty) -> Bool { if lhs.propertyName != rhs.propertyName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginWith: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginWith" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginWith, rhs: Fuzzilli_Protobuf_BeginWith) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndWith: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndWith" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndWith, rhs: Fuzzilli_Protobuf_EndWith) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_LoadFromScope: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".LoadFromScope" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.id.isEmpty { try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_LoadFromScope, rhs: Fuzzilli_Protobuf_LoadFromScope) -> Bool { if lhs.id != rhs.id {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_StoreToScope: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".StoreToScope" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.id.isEmpty { try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_StoreToScope, rhs: Fuzzilli_Protobuf_StoreToScope) -> Bool { if lhs.id != rhs.id {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginIf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginIf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginIf, rhs: Fuzzilli_Protobuf_BeginIf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginElse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginElse" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginElse, rhs: Fuzzilli_Protobuf_BeginElse) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndIf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndIf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndIf, rhs: Fuzzilli_Protobuf_EndIf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginSwitch: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginSwitch" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginSwitch, rhs: Fuzzilli_Protobuf_BeginSwitch) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginSwitchCase: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginSwitchCase" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "fallsThrough"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self.fallsThrough) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.fallsThrough != false { try visitor.visitSingularBoolField(value: self.fallsThrough, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginSwitchCase, rhs: Fuzzilli_Protobuf_BeginSwitchCase) -> Bool { if lhs.fallsThrough != rhs.fallsThrough {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndSwitch: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndSwitch" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndSwitch, rhs: Fuzzilli_Protobuf_EndSwitch) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginWhile: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginWhile" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "comparator"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.comparator) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.comparator != .equal { try visitor.visitSingularEnumField(value: self.comparator, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginWhile, rhs: Fuzzilli_Protobuf_BeginWhile) -> Bool { if lhs.comparator != rhs.comparator {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndWhile: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndWhile" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndWhile, rhs: Fuzzilli_Protobuf_EndWhile) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginDoWhile: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginDoWhile" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "comparator"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.comparator) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.comparator != .equal { try visitor.visitSingularEnumField(value: self.comparator, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginDoWhile, rhs: Fuzzilli_Protobuf_BeginDoWhile) -> Bool { if lhs.comparator != rhs.comparator {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndDoWhile: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndDoWhile" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndDoWhile, rhs: Fuzzilli_Protobuf_EndDoWhile) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginFor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginFor" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "comparator"), 2: .same(proto: "op"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.comparator) }() case 2: try { try decoder.decodeSingularEnumField(value: &self.op) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.comparator != .equal { try visitor.visitSingularEnumField(value: self.comparator, fieldNumber: 1) } if self.op != .add { try visitor.visitSingularEnumField(value: self.op, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginFor, rhs: Fuzzilli_Protobuf_BeginFor) -> Bool { if lhs.comparator != rhs.comparator {return false} if lhs.op != rhs.op {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndFor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndFor" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndFor, rhs: Fuzzilli_Protobuf_EndFor) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginForIn: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginForIn" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginForIn, rhs: Fuzzilli_Protobuf_BeginForIn) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndForIn: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndForIn" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndForIn, rhs: Fuzzilli_Protobuf_EndForIn) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginForOf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginForOf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginForOf, rhs: Fuzzilli_Protobuf_BeginForOf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndForOf: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndForOf" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndForOf, rhs: Fuzzilli_Protobuf_EndForOf) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Break: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Break" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Break, rhs: Fuzzilli_Protobuf_Break) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Continue: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Continue" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Continue, rhs: Fuzzilli_Protobuf_Continue) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginTry: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginTry" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginTry, rhs: Fuzzilli_Protobuf_BeginTry) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginCatch: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginCatch" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginCatch, rhs: Fuzzilli_Protobuf_BeginCatch) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginFinally: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginFinally" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginFinally, rhs: Fuzzilli_Protobuf_BeginFinally) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndTryCatch: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndTryCatch" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndTryCatch, rhs: Fuzzilli_Protobuf_EndTryCatch) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_ThrowException: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ThrowException" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_ThrowException, rhs: Fuzzilli_Protobuf_ThrowException) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginCodeString: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginCodeString" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginCodeString, rhs: Fuzzilli_Protobuf_BeginCodeString) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndCodeString: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndCodeString" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndCodeString, rhs: Fuzzilli_Protobuf_EndCodeString) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_BeginBlockStatement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BeginBlockStatement" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_BeginBlockStatement, rhs: Fuzzilli_Protobuf_BeginBlockStatement) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_EndBlockStatement: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EndBlockStatement" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_EndBlockStatement, rhs: Fuzzilli_Protobuf_EndBlockStatement) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Fuzzilli_Protobuf_Nop: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Nop" public static let _protobuf_nameMap = SwiftProtobuf._NameMap() public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Fuzzilli_Protobuf_Nop, rhs: Fuzzilli_Protobuf_Nop) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } }
38.166231
167
0.748418
d7f47462f31f93fbfd003763d067e3211c138103
4,266
// Copyright © 2016 Stefan van den Oord. All rights reserved. import Foundation #if SWIFT_PACKAGE || os(macOS) import AppKit #else import UIKit #endif /** * Protocol used to add all functionality to both `String` and `NSString`. * You normally don't need to use this directly yourself. * * Please note: I would have preferred for this protocol to be internal. * That doesn't work with Swift 3 however; when doing release builds you * get 'undefined symbol' linker errors. More info: * https://bugs.swift.org/browse/SR-2925 */ public protocol NonAttributedString: RichString { /** * Create a `NSAttributedString` version of the string. Should be internal, not public; * see remark above. * * - Returns: `NSAttributedString` version of this string. */ var rich: RichString { get } } /** * Protocol used to add all functionality to both `String` and `NSString`. * You normally don't need to use this protocol directly yourself. */ extension NonAttributedString { public func font(_ font: Font) -> NSAttributedString { return rich.font(font) } public func color(_ color: Color) -> NSAttributedString { return rich.color(color) } public func backgroundColor(_ color: Color) -> NSAttributedString { return rich.backgroundColor(color) } public func paragraphStyle(_ paragraphStyle: NSParagraphStyle) -> NSAttributedString { return rich.paragraphStyle(paragraphStyle) } public func paragraphStyle(configure: (NSMutableParagraphStyle) -> Void) -> NSAttributedString { return rich.paragraphStyle(configure: configure) } public func ligature(_ ligature: Bool) -> NSAttributedString { return rich.ligature(ligature) } public func kern(_ kern: Float) -> NSAttributedString { return rich.kern(kern) } public func strikeThrough(style: NSUnderlineStyle) -> NSAttributedString { return rich.strikeThrough(style: style) } public func strikeThrough(color: Color) -> NSAttributedString { return rich.strikeThrough(color: color) } public func strikeThrough(color: Color, style: NSUnderlineStyle) -> NSAttributedString { return rich.strikeThrough(color: color, style: style) } public func underline(style: NSUnderlineStyle) -> NSAttributedString { return rich.underline(style: style) } public func underline(color: Color) -> NSAttributedString { return rich.underline(color: color) } public func underline(color: Color, style: NSUnderlineStyle) -> NSAttributedString { return rich.underline(color: color, style: style) } public func stroke(width: Float, color: Color) -> NSAttributedString { return rich.stroke(width: width, color: color) } #if !os(watchOS) public func shadow(_ shadow: NSShadow) -> NSAttributedString { return rich.shadow(shadow) } public func shadow(configure: (NSShadow) -> Void) -> NSAttributedString { return rich.shadow(configure: configure) } public func attachment(configure: (NSTextAttachment) -> Void) -> NSAttributedString { return rich.attachment(configure: configure) } #endif public func letterPressed() -> NSAttributedString { return rich.letterPressed() } public func link(url: NSURL) -> NSAttributedString { return rich.link(url: url) } public func link(string: String) -> NSAttributedString { return rich.link(string: string) } public func baselineOffset(_ offset: Float) -> NSAttributedString { return rich.baselineOffset(offset) } public func obliqueness(_ obliqueness: Float) -> NSAttributedString { return rich.obliqueness(obliqueness) } public func expansion(_ expansion: Float) -> NSAttributedString { return rich.expansion(expansion) } } extension String: NonAttributedString { public var rich: RichString { return NSAttributedString(string: self) } } extension NSString: NonAttributedString { public var rich: RichString { return NSAttributedString(string: self as String) } }
29.219178
92
0.671824
4861949053c37fef7d07bc26556d6a1a832dcd24
238
public struct RunExerciseName { public static let Run: UInt16 = 0 public static let Walk: UInt16 = 1 public static let Jog: UInt16 = 2 public static let Sprint: UInt16 = 3 public static let Invalid: UInt16 = 0xFFFF }
26.444444
46
0.693277
e20b778e70e9b4d0a41af503dafbefc919272b6c
570
// // SquadMember+CoreDataProperties.swift // MarvelSquads // // Created by Magnus Holm on 04/09/2019. // Copyright © 2019 Magnus Holm. All rights reserved. // // import Foundation import CoreData extension SquadMember { @nonobjc public class func fetchRequest() -> NSFetchRequest<SquadMember> { return NSFetchRequest<SquadMember>(entityName: "SquadMember") } @NSManaged public var id: Int32 @NSManaged public var name: String? @NSManaged public var squadMemberDescription: String? @NSManaged public var imageUrl: String? }
21.923077
78
0.714035
e5946a131a398967995e73ef1450500d6b725f41
319
// // Collection+Extension.swift // WaveSlider // // Created by Yuki Ono on 2020/07/31. // Copyright © 2020 Yuki Ono. All rights reserved. // extension Collection where Element: BinaryFloatingPoint { func average() -> Element { isEmpty ? .zero : Element(reduce(.zero, +)) / Element(count) } }
21.266667
68
0.642633
bfbde097c4e7899d07e334f2428ab60c5b32281a
2,708
import Foundation internal class FoundationURLSessionDataDelegate: NSObject, URLSessionDataDelegate { fileprivate weak var stream: FoundationHTTPSSEStream? fileprivate weak var session: URLSession? fileprivate var fulfillClose: Bool = false fileprivate init(_ stream: FoundationHTTPSSEStream) { self.stream = stream } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { stream?.dataBuffer.append(data) stream?.dispatchEvents() } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { fatalError() } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { completionHandler(URLSession.ResponseDisposition.allow) guard let httpResponse = response as? HTTPURLResponse, !fulfillClose else { fulfillClose = false return } if httpResponse.statusCode == 200 { stream?.state = .open } if httpResponse.statusCode == 204 { stream?.state = .closed } self.session = session // store this initial response from the server self.stream?.initialResponse = Response.init( statusCode: httpResponse.statusCode, headers: httpResponse.allHeaderFields as? [String: String] ?? [:], body: nil ) } } public class FoundationHTTPSSEStream: RawSSEStream { // The reason we are disabling `weak_delegate` here is because // this isn't a typical delegate pattern. There's no risk of // a reference cycle as we want to retain this delegate as long // as the stream is retained. When the stream is deallocated, // the delegate will also be. // swiftlint:disable:next weak_delegate internal lazy var dataDelegate: FoundationURLSessionDataDelegate? = FoundationURLSessionDataDelegate(self) // The initial response from the Stitch server indicating whether or not the stream was successfully opened. // Will be 'nil' until the request is completed. internal var initialResponse: Response? public override func close() { dataDelegate?.stream?.state = .closing if let session = dataDelegate?.session { session.invalidateAndCancel() } // the session may not have begun yet. // we must still fulfill a close if called dataDelegate?.stream?.state = .closed dataDelegate = nil } }
35.631579
112
0.658789
e5ad4c8139a1a948caa28430bea7f0f882887fba
2,356
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "SlackKit", platforms: [ .macOS(.v10_10), .iOS(.v10), .tvOS(.v10) ], products: [ .library(name: "SlackKit", targets: ["SlackKit"]), .library(name: "SKClient", targets: ["SKClient"]), .library(name: "SKCore", targets: ["SKCore"]), .library(name: "SKRTMAPI", targets: ["SKRTMAPI"]), .library(name: "SKServer", targets: ["SKServer"]), .library(name: "SKWebAPI", targets: ["SKWebAPI"]) ], dependencies: [ .package(name: "Swifter", url: "https://github.com/httpswift/swifter.git", .upToNextMinor(from: "1.5.0")), .package(name: "WebSocket", url: "https://github.com/vapor/websocket", .upToNextMinor(from: "1.1.2")), .package(name: "Starscream", url: "https://github.com/daltoniam/Starscream", .upToNextMinor(from: "4.0.4")) ], targets: [ .target(name: "SlackKit", dependencies: ["SKCore", "SKClient", "SKRTMAPI", "SKServer"], path: "SlackKit/Sources"), .target(name: "SKClient", dependencies: ["SKCore"], path: "SKClient/Sources"), .target(name: "SKCore", path: "SKCore/Sources"), .target(name: "SKRTMAPI", dependencies: [ "SKCore", "SKWebAPI", .product(name: "Starscream", package: "Starscream", condition: .when(platforms: [.macOS, .iOS, .tvOS])), .product(name: "WebSocket", package: "WebSocket", condition: .when(platforms: [.macOS, .linux])), ], path: "SKRTMAPI/Sources"), .target(name: "SKServer", dependencies: ["SKCore", "SKWebAPI", "Swifter"], path: "SKServer/Sources"), .target(name: "SKWebAPI", dependencies: ["SKCore"], path: "SKWebAPI/Sources"), .testTarget(name: "SlackKitTests", dependencies: ["SlackKit", "SKCore", "SKClient", "SKRTMAPI", "SKServer"], path: "SlackKitTests", exclude: [ "Supporting Files" ], resources: [ .copy("Resources") ]) ], swiftLanguageVersions: [.v5] )
40.62069
124
0.513582
d959224638ca6f46421437b08f60d124e222b0ea
3,640
// // AuthenticatedViewController.swift // Instagram // // Created by Sijin Wang on 3/6/18. // Copyright © 2018 Sijin Wang. All rights reserved. // import UIKit import Parse class AuthenticatedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var posts: [PFObject]! = [] var refreshControl: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(AuthenticatedViewController.didPullToRefresh(_:)), for: .valueChanged) tableView.insertSubview(refreshControl, at: 0) fetchPosts() // Do any additional setup after loading the view. } @objc func didPullToRefresh(_ refreshControl: UIRefreshControl) { fetchPosts() } @IBAction func logOut(_ sender: Any) { print("logout clicked") NotificationCenter.default.post(name: NSNotification.Name("didLogout"), object: nil) } func fetchPosts() { // construct PFQuery let query = Post.query() query?.order(byDescending: "createdAt") query?.includeKey("author") query?.includeKey("_created_at") query?.limit = 20 // fetch data asynchronously query?.findObjectsInBackground(block: { (posts:[PFObject]?, error: Error?) in if let posts = posts { self.posts = posts // print(posts) self.tableView.reloadData() self.refreshControl.endRefreshing() } else { print(error?.localizedDescription) } }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoFeed", for: indexPath) as! PostCell let post = posts[indexPath.row] cell.captionLabel.text = (post["caption"] as! String) let imageFile = post["media"] as! PFFile let imageData = try? imageFile.getData() cell.postImageView.image = UIImage(data: imageData!) cell.selectionStyle = .none return cell; } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { let cell = sender as! UITableViewCell if let indexPath = tableView.indexPath(for: cell) { let post = posts[indexPath.row] let detailViewController = segue.destination as! PostDetailViewController detailViewController.post = post } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33.703704
127
0.631044
671fd95985a0683da4b3d307cf1d854cd946d490
1,413
// // PreworkUITests.swift // PreworkUITests // // Created by Vipata Kilembo on 1/24/21. // import XCTest class PreworkUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.860465
182
0.655343
5d9af0a66a60b4c71b627dfd94d6952e1f31bc5a
1,830
// // CollectingDataAboutWalls.swift // Maze // // Created by Gabrielle Miller-Messner on 11/6/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import Foundation extension ControlCenter { func isFacingWall(robot: ComplexRobotObject, direction: MazeDirection) -> Bool { let cell = mazeController.currentCell(robot) var isWall: Bool = false switch(direction) { case .Up: if cell.top { isWall = true } case .Down: if cell.bottom { isWall = true } case .Left: if cell.left { isWall = true } case .Right: if cell.right { isWall = true } } return isWall } func checkWalls(robot:ComplexRobotObject) -> (up: Bool, right: Bool, down: Bool, left: Bool, numberOfWalls: Int) { var numberOfWalls = 0 let cell = mazeController.currentCell(robot) // Check is there is a wall at the top of the current cell let isWallUp = cell.top if isWallUp { numberOfWalls += 1 } // Check if there is a wall to the right of the current cell let isWallRight = cell.right if isWallRight { numberOfWalls += 1 } let isWallLeft = cell.left if isWallLeft { numberOfWalls += 1 } let isWallBottom = cell.bottom if isWallBottom { numberOfWalls += 1 } return (isWallUp, isWallRight, isWallBottom, isWallLeft, numberOfWalls) } }
23.461538
118
0.484699
56314f67ab9ae7a489ec1ff6712ee9640c5127a9
8,739
// // Manager+Live.swift // ComposableCoreBluetooth // // Created by Philipp Gabriel on 15.07.20. // Copyright © 2020 Philipp Gabriel. All rights reserved. // import Foundation import CoreBluetooth import Combine import ComposableArchitecture private var dependencies: [AnyHashable: Dependencies] = [:] private struct Dependencies { let manager: CBCentralManager let delegate: BluetoothManager.Delegate let subscriber: Effect<BluetoothManager.Action, Never>.Subscriber } extension BluetoothManager { public static let live: BluetoothManager = { () -> BluetoothManager in var manager = BluetoothManager() manager.create = { id, queue, options in return .merge( Effect.run { subscriber in let delegate = Delegate(subscriber) let manager = CBCentralManager(delegate: delegate, queue: queue, options: options?.toDictionary()) dependencies[id] = Dependencies(manager: manager, delegate: delegate, subscriber: subscriber) return AnyCancellable { dependencies[id] = nil } }, Deferred(createPublisher: { dependencies[id]? .manager .publisher(for: \.isScanning) .map(BluetoothManager.Action.didUpdateScanningState) .eraseToAnyPublisher() ?? Effect.none.eraseToAnyPublisher() }).eraseToEffect() ) } manager.destroy = { id in .fireAndForget { dependencies[id]?.subscriber.send(completion: .finished) dependencies[id] = nil } } manager.connect = { id, peripheral, options in guard let rawPeripheral = dependencies[id]?.manager.retrievePeripherals(withIdentifiers: [peripheral.identifier]).first else { couldNotFindRawPeripheralValue() return .none } return .fireAndForget { dependencies[id]?.manager.connect(rawPeripheral, options: options?.toDictionary()) } } manager.cancelConnection = { id, peripheral in guard let rawPeripheral = dependencies[id]?.manager.retrievePeripherals(withIdentifiers: [peripheral.identifier]).first else { couldNotFindRawPeripheralValue() return .none } return .fireAndForget { dependencies[id]?.manager.cancelPeripheralConnection(rawPeripheral) } } manager.retrieveConnectedPeripherals = { id, uuids in guard let dependency = dependencies[id] else { couldNotFindBluetoothManager(id: id) return [] } return dependency .manager .retrieveConnectedPeripherals(withServices: uuids) .map(Peripheral.State.live) } manager.retrievePeripherals = { id, uuids in guard let dependency = dependencies[id] else { couldNotFindBluetoothManager(id: id) return [] } return dependency .manager .retrievePeripherals(withIdentifiers: uuids) .map(Peripheral.State.live) } manager.scanForPeripherals = { id, services, options in .fireAndForget { dependencies[id]?.manager.scanForPeripherals(withServices: services, options: options?.toDictionary()) } } manager.stopScan = { id in .fireAndForget { dependencies[id]?.manager.stopScan() } } if #available(iOS 13.1, macOS 10.15, macCatalyst 13.1, tvOS 13.0, watchOS 6.0, *) { manager._authorization = { CBCentralManager.authorization } } manager.state = { id in guard let dependency = dependencies[id] else { couldNotFindBluetoothManager(id: id) return .unknown } return dependency.manager.state } manager.peripheralEnvironment = { id, uuid in guard let dependency = dependencies[id] else { couldNotFindBluetoothManager(id: id) return nil } guard let rawPeripheral = dependencies[id]?.manager.retrievePeripherals(withIdentifiers: [uuid]).first else { couldNotFindRawPeripheralValue() return nil } return Peripheral.Environment.live(from: rawPeripheral, subscriber: dependency.subscriber) } #if os(iOS) || os(watchOS) || os(tvOS) || targetEnvironment(macCatalyst) manager.registerForConnectionEvents = { id, options in .fireAndForget { dependencies[id]?.manager.registerForConnectionEvents(options: options?.toDictionary()) } } #endif #if os(iOS) || os(watchOS) || os(tvOS) || targetEnvironment(macCatalyst) manager.supports = CBCentralManager.supports #endif return manager }() } extension BluetoothManager { class Delegate: NSObject, CBCentralManagerDelegate { let subscriber: Effect<BluetoothManager.Action, Never>.Subscriber init(_ subscriber: Effect<BluetoothManager.Action, Never>.Subscriber) { self.subscriber = subscriber } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { subscriber.send(.peripheral(peripheral.identifier, .didConnect)) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { if let error = error { if let error = error as? CBError { subscriber.send(.peripheral(peripheral.identifier, .didDisconnect(.coreBluetooth(error)))) } else { subscriber.send(.peripheral(peripheral.identifier, .didDisconnect(.unknown(error.localizedDescription)))) } } else { subscriber.send(.peripheral(peripheral.identifier, .didDisconnect(.none))) } } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { if let error = error { if let error = error as? CBError { subscriber.send(.peripheral(peripheral.identifier, .didFailToConnect(.coreBluetooth(error)))) } else { subscriber.send(.peripheral(peripheral.identifier, .didFailToConnect(.unknown(error.localizedDescription)))) } } else { subscriber.send(.peripheral(peripheral.identifier, .didFailToConnect(.unknown(.none)))) } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) { subscriber.send(.didDiscover(Peripheral.State.live(from: peripheral), BluetoothManager.AdvertismentData(from: advertisementData), RSSI)) } func centralManagerDidUpdateState(_ central: CBCentralManager) { subscriber.send(.didUpdateState(central.state)) } func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) { subscriber.send(.willRestore(RestorationOptions(from: dict))) } #if os(iOS) || os(watchOS) || os(tvOS) || targetEnvironment(macCatalyst) func centralManager(_ central: CBCentralManager, connectionEventDidOccur event: CBConnectionEvent, for peripheral: CBPeripheral) { subscriber.send(.peripheral(peripheral.identifier, .connectionEventDidOccur(event))) } #endif #if os(iOS) || os(watchOS) || os(tvOS) || targetEnvironment(macCatalyst) func centralManager(_ central: CBCentralManager, didUpdateANCSAuthorizationFor peripheral: CBPeripheral) { subscriber.send(.peripheral(peripheral.identifier, .didUpdateANCSAuthorization(peripheral.ancsAuthorized))) } #endif } }
38.497797
151
0.574322
f55fb9dffe545974e5885cfa7dc72e13f84c3018
2,038
// // Copyright (c) 2021 Related Code - https://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //----------------------------------------------------------------------------------------------------------------------------------------------- class Hotels1Cell: UITableViewCell { @IBOutlet var imageViewHotel: UIImageView! @IBOutlet var labelRatings: UILabel! @IBOutlet var labelHotelName: UILabel! @IBOutlet var labelAddress: UILabel! @IBOutlet var labelAmount: UILabel! @IBOutlet var buttonLikeDislike: UIButton! @IBOutlet var imageViewStar1: UIImageView! @IBOutlet var imageViewStar2: UIImageView! @IBOutlet var imageViewStar3: UIImageView! @IBOutlet var imageViewStar4: UIImageView! @IBOutlet var imageViewStar5: UIImageView! //------------------------------------------------------------------------------------------------------------------------------------------- func bindData(index: Int, hotel: [String: String]) { guard let ratings = hotel["ratings"] else { return } guard let name = hotel["name"] else { return } guard let address = hotel["address"] else { return } guard let amount = hotel["amount"] else { return } imageViewHotel.sample("Travel", "Resorts", index) labelRatings.text = ratings labelHotelName.text = name labelAddress.text = address labelAmount.text = amount } // MARK: - User actions //------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionLikeDislike(_ sender: Any) { print(#function) } }
39.960784
145
0.589794
2260e915ba473c3d761f46b8f968c688d9451bca
2,389
import GL public struct ShaderError: Error { let info: String init(_ info: String) { self.info = info } } open class Shader { public let vertexSource: String public let fragmentSource: String public var id: GLMap.UInt? public init(vertex vertexSource: String, fragment fragmentSource: String) { self.vertexSource = vertexSource self.fragmentSource = fragmentSource } /// compiles and links the shaders open func compile() throws { let vertexShader = glCreateShader(GLMap.VERTEX_SHADER) withUnsafePointer(to: vertexSource) { ptr in glShaderSource(vertexShader, 1, ptr, nil) } glCompileShader(vertexShader) let success = UnsafeMutablePointer<GLMap.Int>.allocate(capacity: 1) let info = UnsafeMutablePointer<GLMap.Char>.allocate(capacity: 512) glGetShaderiv(vertexShader, GLMap.COMPILE_STATUS, success) if (success.pointee == 0) { glGetShaderInfoLog(vertexShader, 512, nil, info) throw ShaderError(String(cString: info)) } else { print("Vertex shader successfully compiled.") } let fragmentShader = glCreateShader(GLMap.FRAGMENT_SHADER) withUnsafePointer(to: fragmentSource) { ptr in GL.glShaderSource(fragmentShader, 1, ptr, nil) } glCompileShader(fragmentShader) glGetShaderiv(fragmentShader, GLMap.COMPILE_STATUS, success) if (success.pointee == 0) { glGetShaderInfoLog(fragmentShader, 512, nil, info) throw ShaderError(String(cString: info)) } else { print("Fragment shader successfully compiled.") } self.id = glCreateProgram() glAttachShader(self.id!, vertexShader) glAttachShader(self.id!, fragmentShader) glLinkProgram(self.id!) glGetProgramiv(self.id!, GLMap.LINK_STATUS, success) if (success.pointee == 0) { glGetProgramInfoLog(self.id!, 512, nil, info) throw ShaderError(String(cString: info)) } else { print("Shader program linked successfully.") } glDeleteShader(vertexShader) glDeleteShader(fragmentShader) } open func use() { guard let id = self.id else { fatalError("Called use on shader before it was compiled.") } glUseProgram(id) } }
33.180556
103
0.641691
6243336470fc975eee2079f61e7b0d5907502766
802
// // BookShelfApp.swift // BookShelf // // Created by Peter Friese on 02/01/2021. // import SwiftUI @main struct BookShelfApp: App { // By pulling up the source of truth to the app, we make sure that all the app's // windows share the same source of truth. In case each BooksListView had their own // @StateObject var booksViewModel = BooksViewModel(), any changes made to any of // them wouldn't be reflected on the other ones. // See this in action by running the app on an iPad and then use multi-tasking to arrange // two app windows side-by-side. @StateObject var booksViewModel = BooksViewModel() var body: some Scene { WindowGroup { NavigationView { BooksListView(booksViewModel: booksViewModel) .navigationTitle("Books") } } } }
27.655172
91
0.690773
e21ff596a6a77a4acf4db8e6a8b7482f1ba62f15
8,791
// // Copyright © 2017 UserReport. All rights reserved. // import Foundation import UIKit import WebKit /// HTTP method definitions. internal enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" } internal class Network { struct Server { var api: String var sak: String var log: String var audiences: String } // MARK: - Properties internal var logger: Logger? internal var testMode: Bool = false private var session: URLSession? private let server: Server = { let env = ProcessInfo.processInfo.environment return Server(api: env["USERREPORT_SERVER_URL_API"] ?? "https://api.userreport.com/collect/v1", sak: env["USERREPORT_SERVER_URL_SAK"] ?? "https://sak.userreport.com", log: env["USERREPORT_SERVER_URL_LOG"] ?? "https://qa-relay.userreport.com/f/qa1-android-sdk-log/json", audiences: env["USERREPORT_SERVER_URL_AUDIENCES"] ?? "https://visitanalytics.userreport.com") }() // MARK: - Init init() { // Setup session configuration with additional headers let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.httpAdditionalHeaders = ["Content-Type": "application/json"] // Create session wirh configuration self.session = URLSession(configuration: sessionConfiguration) } // MARK: API func visit(info: Info, completion: @escaping ((Result<Empty>) -> Void)) { let url = URL(string: "\(self.server.api)/visit") let data = info.dictObject() self.sendRequest(httpMethod: HTTPMethod.POST, url: url, body: data, emptyReponse: true, completion: completion) } func invitation(info: Info, completion: @escaping ((Result<Invitation>) -> Void)) { let path = self.testMode ? "visit+invitation/testinvite" : "invitation" let url = URL(string: "\(self.server.api)/\(path)") let data = info.dictObject() self.sendRequest(httpMethod: HTTPMethod.POST, url: url, body: data, completion: completion) } func getQuarantineInfo(userId: String, mediaId: String, completion: @escaping ((Result<QuarantineResponse>) -> Void)) { let url = URL(string: "\(self.server.api)/quarantine/\(userId)/media/\(mediaId)/info") self.sendRequest(httpMethod: HTTPMethod.GET, url: url, body: nil, completion: completion) } func setQuarantine(reason: String, mediaId: String, invitationId: String, userId: String, completion: @escaping ((Result<Empty>) -> Void)) { let url = URL(string: "\(self.server.api)/quarantine") let data = ["reason": reason, "mediaId": mediaId, "invitationId": invitationId, "userId": userId] self.sendRequest(httpMethod: HTTPMethod.POST, url: url, body: data, emptyReponse: true, completion: completion) } func getConfig(media: Media, completion: @escaping ((Result<MediaSettings>) -> Void)) { let url = URL(string: "\(self.server.sak)/\(media.sakId)/media/\(media.mediaId)/ios.json") self.sendRequest(httpMethod: HTTPMethod.GET, url: url, body: nil, completion: completion) } func audiences(info: Info, completion: @escaping ((Result<Empty>) -> Void)) { //https://visitanalytics.userreport.com/hit.gif?t=[kitTcode]&rnd=%RANDOM%&d=IDFA&med=app_name let appName = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String let kitTcode = info.mediaSettings?.kitTcode let tCode = (kitTcode != nil) ? "t=\(kitTcode!)&" : "" let random = arc4random_uniform(UInt32.max) let idfa = info.user?.idfa ?? "" let url = URL(string: "\(self.server.audiences)/hit.gif?\(tCode)rnd=\(random)&d=\(idfa)&med=\(appName)") self.userAgent { (userAgent) in let headers = ["User-Agent": userAgent] self.sendRequest(httpMethod: HTTPMethod.POST, url: url, headers: headers, body: nil, emptyReponse: true, completion: completion) } } func logMessage(info: Info, message: String, completion: @escaping ((Result<Empty>) -> Void)) { let url = URL(string: self.server.log) var data = info.dictObject() data["message"] = message self.sendRequest(httpMethod: HTTPMethod.POST, url: url, body: data, emptyReponse: true, completion: completion) } // MARK: Network methods private var webView: WKWebView? = WKWebView() // Need for get default WebKit `User-Agent` header private var userAgentHeader: String? // Default WebKit `User-Agent` private func userAgent(_ completion: @escaping (String) -> Void) { // Return cached `User-Agent` if let userAgentHeader = self.userAgentHeader { self.webView = nil completion(userAgentHeader) return } // Get `User-Agent` from webView DispatchQueue.main.async { self.webView?.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in guard error == nil else { self.logger?.log("Can't get User-Agent for send audiences. Error: \(error?.localizedDescription ?? "")", level: .error) return } guard let userAgent = result as? String else { self.logger?.log("Can't get User-Agent for send audiences. Error: invalid result", level: .error) return } // Return `User-Agent` self.userAgentHeader = userAgent completion(userAgent) }) } } private func sendRequest<Value: Serialization>(httpMethod: HTTPMethod, url: URL?, headers: [String: String]? = nil, body: Any?, emptyReponse: Bool = false, completion: @escaping ((Result<Value>) -> Void)) { // Validate URL guard let url = url else { // Track error return } // Create request object var request = URLRequest(url: url) request.httpMethod = httpMethod.rawValue // Set headers if needed if let headers = headers { for (key, value) in headers { request.addValue(value, forHTTPHeaderField: key) } } // Set body if needed if let data = body { do { request.httpBody = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) } catch { //Track error self.logger?.log("Error JSON serialization: \(error.localizedDescription)", level: .error) } } // Send request let task = self.session?.dataTask(with: request, completionHandler: { (data, response, errorResponse) in guard errorResponse == nil else { // Track error let result = Result<Value>.failure(errorResponse!) completion(result) return } guard emptyReponse == false else { let empty = try! Value(dict: [:]) let result = Result<Value>.success(empty) completion(result) return } guard let data = data else { // Track error let error = URError.responseDataNilOrZeroLength(url: url) let result = Result<Value>.failure(error) completion(result) return } if let resp = response as? HTTPURLResponse, resp.statusCode > 299 { let logLevel : LogLevel = self.testMode ? .debug : .error self.logger?.log("Incorrect response status code: \(resp.statusCode.description)", level: logLevel) self.logger?.log("Response: \(String(decoding: data, as: UTF8.self))", level: logLevel) return } do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any?] let mediaSettings = try Value(dict: json) let result = Result<Value>.success(mediaSettings) completion(result) } catch { //Track error self.logger?.log("Error JSON serialization: \(error.localizedDescription)", level: .error) let result = Result<Value>.failure(error) completion(result) } }) task?.resume() } }
41.2723
210
0.581618
bb59e3de3a0b786322c12e35a09f92382620c422
3,777
// // AdverseEventSuspectEntityCausality.swift // Asclepius // Module: STU3 // // Copyright (c) 2022 Bitmatic Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import AsclepiusCore /// Information on the possible cause of the adverse event open class AdverseEventSuspectEntityCausality: BackboneElement { /// Assessment of if the entity caused the event public var assessment: CodeableConcept? /// AdverseEvent.suspectEntity.causalityProductRelatedness public var productRelatedness: AsclepiusPrimitive<AsclepiusString>? /// AdverseEvent.suspectEntity.causalityAuthor public var author: Reference? /// ProbabilityScale | Bayesian | Checklist public var method: CodeableConcept? override public init() { super.init() } public convenience init( fhirExtension: [Extension]? = nil, fhirId: AsclepiusPrimitive<AsclepiusString>? = nil, assessment: CodeableConcept? = nil, productRelatedness: AsclepiusPrimitive<AsclepiusString>? = nil, author: Reference? = nil, method: CodeableConcept? = nil ) { self.init() self.fhirExtension = fhirExtension self.fhirId = fhirId self.assessment = assessment self.productRelatedness = productRelatedness self.author = author self.method = method } // MARK: - Codable private enum CodingKeys: String, CodingKey { case assessment case productRelatedness; case _productRelatedness case author case method } public required init(from decoder: Decoder) throws { let codingKeyContainer = try decoder.container(keyedBy: CodingKeys.self) self.assessment = try CodeableConcept(from: codingKeyContainer, forKeyIfPresent: .assessment) self.productRelatedness = try AsclepiusPrimitive<AsclepiusString>(from: codingKeyContainer, forKeyIfPresent: .productRelatedness, auxKey: ._productRelatedness) self.author = try Reference(from: codingKeyContainer, forKeyIfPresent: .author) self.method = try CodeableConcept(from: codingKeyContainer, forKeyIfPresent: .method) try super.init(from: decoder) } override public func encode(to encoder: Encoder) throws { var codingKeyContainer = encoder.container(keyedBy: CodingKeys.self) try assessment?.encode(on: &codingKeyContainer, forKey: .assessment) try productRelatedness?.encode(on: &codingKeyContainer, forKey: .productRelatedness, auxKey: ._productRelatedness) try author?.encode(on: &codingKeyContainer, forKey: .author) try method?.encode(on: &codingKeyContainer, forKey: .method) try super.encode(to: encoder) } // MARK: - Equatable override public func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? AdverseEventSuspectEntityCausality else { return false } guard super.isEqual(to: _other) else { return false } return assessment == _other.assessment && productRelatedness == _other.productRelatedness && author == _other.author && method == _other.method } // MARK: - Hashable override public func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(assessment) hasher.combine(productRelatedness) hasher.combine(author) hasher.combine(method) } }
33.723214
163
0.724914
64fd7e7b344a1e57dc7e34c29bae76833dc75c40
1,439
// // EBWeatherAppUITests.swift // EBWeatherAppUITests // // Created by product on 13/11/2019. // Copyright © 2019 AAStocks. All rights reserved. // import XCTest class EBWeatherAppUITests: XCTestCase { override func 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 // 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. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
32.704545
182
0.656011