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
116c53b75407ed244dde84816280d06de425f330
4,853
// // ExerciseSelectionViewController.swift // Gymlog // // Created by Orlando Ortega on 2018-08-20. // Copyright © 2018 Orlando Ortega. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase class ExerciseSelectionViewController: UIViewController { @IBOutlet weak var exerciseDayLabel: UILabel! @IBOutlet weak var exerciseTextField: UITextField! @IBOutlet weak var tableView: UITableView! var currentExercise : Exercise! var currentRoutineDayFromPreviousVC : RoutineDay! var exerciseDayLabelText: String! //From last view controller which describe current routine var routineDayKey: String! var ref: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: .zero) //Previous routine day title presented as view controller title to organize exercises exerciseDayLabel.text = exerciseDayLabelText ref = Database.database().reference(fromURL: "https://gymlog-afa5e.firebaseio.com/") } @IBAction func addButtonPressed(_ sender: Any) { insertNewExercise() } func insertNewExercise() { if exerciseTextField.text! == "" { print("Empty Cell") } else { //Current exercise entered by user let tempExercise = Exercise(title: exerciseTextField.text!) currentRoutineDayFromPreviousVC.routineDayExercises.append(tempExercise) let indexPath = IndexPath(row: (currentRoutineDayFromPreviousVC.routineDayExercises.count) - 1, section: 0) writeToDatabase(currentExercise: tempExercise, with: indexPath) tableView.beginUpdates() tableView.insertRows(at: [indexPath], with: .automatic) tableView.endUpdates() view.endEditing(true) //Reset textfield exerciseTextField.text = "" } } func writeToDatabase(currentExercise: Exercise, with Index: IndexPath ) { let exercise = ["sets": currentExercise.sets ?? 0, "reps" : currentExercise.reps ?? 0, "weight" : currentExercise.weight ?? 0 ] //Setting up Schema let childUpdates = ["Exercises/\(routineDayKey!)/\(currentRoutineDayFromPreviousVC.routineDayExercises[Index.row].title)": exercise] ref.updateChildValues(childUpdates) } //Receives segueway from exercise option view controller when Done button is selected. @IBAction func unwindToExerciseScreen(_ sender: UIStoryboardSegue){} } //Table setup extension ExerciseSelectionViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (currentRoutineDayFromPreviousVC.routineDayExercises.count) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let exercise = currentRoutineDayFromPreviousVC.routineDayExercises[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseCell") as! ExerciseCell cell.exerciseTitle.text = exercise.title cell.exerciseSubtitle.text = "\(exercise.sets ?? 0) x \(exercise.reps ?? 0) \(exercise.weight ?? 0) lbs \(exercise.restTime ?? 0) mins" return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { currentRoutineDayFromPreviousVC.routineDayExercises.remove(at: indexPath.row) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = storyboard?.instantiateViewController(withIdentifier: "ExerciseOptionsViewController") as? ExerciseOptionsViewController //Sets title for next view controller vc?.exerciseTitleText = currentRoutineDayFromPreviousVC.routineDayExercises[indexPath.row].title //Sends routine day ID vc?.routineDayKey = currentRoutineDayFromPreviousVC.routineDayKey //Tracks current exercise currentExercise = currentRoutineDayFromPreviousVC.routineDayExercises[indexPath.row] self.navigationController?.pushViewController(vc!, animated: true) } }
34.913669
151
0.663095
728eed0600e705ae7673ccfc1d12245b8d3a7bd0
8,916
// // StoreKitWrapperTests.swift // PurchasesTests // // Created by RevenueCat. // Copyright © 2019 RevenueCat. All rights reserved. // import Foundation import XCTest import OHHTTPStubs import Nimble import Purchases class MockPaymentQueue: SKPaymentQueue { var addedPayments: [SKPayment] = [] override func add(_ payment: SKPayment) { addedPayments.append(payment) } var observers: [SKPaymentTransactionObserver] = [] override func add(_ observer: SKPaymentTransactionObserver) { observers.append(observer) } override func remove(_ observer: SKPaymentTransactionObserver) { let i = observers.firstIndex { $0 === observer } observers.remove(at: i!) } var finishedTransactions: [SKPaymentTransaction] = [] override func finishTransaction(_ transaction: SKPaymentTransaction) { finishedTransactions.append(transaction) } } class StoreKitWrapperTests: XCTestCase, RCStoreKitWrapperDelegate { let paymentQueue = MockPaymentQueue() var wrapper: RCStoreKitWrapper? override func setUp() { super.setUp() wrapper = RCStoreKitWrapper.init(paymentQueue: paymentQueue) wrapper?.delegate = self } var updatedTransactions: [SKPaymentTransaction] = [] func storeKitWrapper(_ storeKitWrapper: RCStoreKitWrapper, updatedTransaction transaction: SKPaymentTransaction) { updatedTransactions.append(transaction) } var removedTransactions: [SKPaymentTransaction] = [] func storeKitWrapper(_ storeKitWrapper: RCStoreKitWrapper, removedTransaction transaction: SKPaymentTransaction) { removedTransactions.append(transaction) } var promoPayment: SKPayment? var promoProduct: SKProduct? var shouldAddPromo = false func storeKitWrapper(_ storeKitWrapper: RCStoreKitWrapper, shouldAddStore payment: SKPayment, for product: SKProduct) -> Bool { promoPayment = payment promoProduct = product return shouldAddPromo } var productIdentifiersWithRevokedEntitlements: [String]? func storeKitWrapper(_ storeKitWrapper: RCStoreKitWrapper, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) { productIdentifiersWithRevokedEntitlements = productIdentifiers } func testObservesThePaymentQueue() { expect(self.paymentQueue.observers.count).to(equal(1)) } func testAddsPaymentsToTheQueue() { let payment = SKPayment.init(product: SKProduct.init()) wrapper?.add(payment) expect(self.paymentQueue.addedPayments).to(contain(payment)) } func testCallsDelegateWhenTransactionsAreUpdated() { let payment = SKPayment.init(product: SKProduct.init()) wrapper?.add(payment) let transaction = MockTransaction() transaction.mockPayment = payment wrapper?.paymentQueue(paymentQueue, updatedTransactions: [transaction]) expect(self.updatedTransactions).to(contain(transaction)) } @available(iOS 11.0, *) func testCallsDelegateWhenPromoPurchaseIsAvailable() { let product = SKProduct.init(); let payment = SKPayment.init(product: product) wrapper?.paymentQueue(paymentQueue, shouldAddStorePayment: payment, for: product) expect(self.promoPayment).to(be(payment)); expect(self.promoProduct).to(be(product)) } @available(iOS 11.0, *) func testPromoDelegateMethodPassesBackReturnValueFromOwnDelegate() { let product = SKProduct.init(); let payment = SKPayment.init(product: product) shouldAddPromo = (arc4random() % 2 == 0) as Bool let result = wrapper?.paymentQueue(paymentQueue, shouldAddStorePayment: payment, for: product) expect(result).to(equal(self.shouldAddPromo)) } func testCallsDelegateOncePerTransaction() { let payment1 = SKPayment.init(product: SKProduct.init()) wrapper?.add(payment1) let payment2 = SKPayment.init(product: SKProduct.init()) wrapper?.add(payment2) let transaction1 = MockTransaction() transaction1.mockPayment = payment1 let transaction2 = MockTransaction() transaction2.mockPayment = payment2 wrapper?.paymentQueue(paymentQueue, updatedTransactions: [transaction1, transaction2]) expect(self.updatedTransactions).to(contain([transaction1, transaction2])) } func testFinishesTransactions() { let payment = SKPayment.init(product: SKProduct.init()) wrapper?.add(payment) let transaction = MockTransaction() transaction.mockPayment = payment wrapper?.paymentQueue(paymentQueue, updatedTransactions: [transaction]) wrapper?.finish(transaction) expect(self.paymentQueue.finishedTransactions).to(contain(transaction)) } func testCallsRemovedTransactionDelegateMethod() { let transaction1 = MockTransaction() transaction1.mockPayment = SKPayment.init(product: SKProduct.init()) let transaction2 = MockTransaction() transaction2.mockPayment = SKPayment.init(product: SKProduct.init()) wrapper?.paymentQueue(paymentQueue, removedTransactions: [transaction1, transaction2]) expect(self.removedTransactions).to(contain([transaction1, transaction2])) } func testDoesntAddObserverWithoutDelegate() { wrapper?.delegate = nil expect(self.paymentQueue.observers.count).to(equal(0)) wrapper?.delegate = self expect(self.paymentQueue.observers.count).to(equal(1)) } func testDidRevokeEntitlementsForProductIdentifiersCallsDelegateWithRightArguments() { #if swift(>=5.3) if #available(iOS 14.0, macOS 14.0, tvOS 14.0, watchOS 7.0, *) { expect(self.productIdentifiersWithRevokedEntitlements).to(beNil()) let revokedProductIdentifiers = [ "mySuperProduct", "theOtherProduct" ] wrapper?.paymentQueue(paymentQueue, didRevokeEntitlementsForProductIdentifiers: revokedProductIdentifiers) expect(self.productIdentifiersWithRevokedEntitlements) == revokedProductIdentifiers } #endif } func testPaymentWithProductReturnsCorrectPayment() { guard let wrapper = wrapper else { fatalError("wrapper is not initialized!") } let productId = "mySuperProduct" let mockProduct = MockSKProduct(mockProductIdentifier: productId) let payment = wrapper.payment(with: mockProduct) expect(payment.productIdentifier) == productId } func testPaymentWithProductSetsSimulatesAskToBuyInSandbox() { guard let wrapper = wrapper else { fatalError("wrapper is not initialized!") } let mockProduct = MockSKProduct(mockProductIdentifier: "mySuperProduct") RCStoreKitWrapper.simulatesAskToBuyInSandbox = false let payment1 = wrapper.payment(with: mockProduct) expect(payment1.simulatesAskToBuyInSandbox) == false RCStoreKitWrapper.simulatesAskToBuyInSandbox = true let payment2 = wrapper.payment(with: mockProduct) expect(payment2.simulatesAskToBuyInSandbox) == true } func testPaymentWithProductAndDiscountReturnsCorrectPaymentWithDiscount() { if #available(iOS 12.2, macOS 10.14.4, watchOS 6.2, macCatalyst 13.0, tvOS 12.2, *) { guard let wrapper = wrapper else { fatalError("wrapper is not initialized!") } let productId = "mySuperProduct" let discountId = "mySuperDiscount" let mockProduct = MockSKProduct(mockProductIdentifier: productId) let mockDiscount = MockPaymentDiscount(mockIdentifier: discountId) let payment = wrapper.payment(with: mockProduct, discount: mockDiscount) expect(payment.productIdentifier) == productId expect(payment.paymentDiscount) == mockDiscount } } func testPaymentWithProductAndDiscountSetsSimulatesAskToBuyInSandbox() { if #available(iOS 12.2, macOS 10.14.4, watchOS 6.2, macCatalyst 13.0, tvOS 12.2, *) { guard let wrapper = wrapper else { fatalError("wrapper is not initialized!") } let mockProduct = MockSKProduct(mockProductIdentifier: "mySuperProduct") let mockDiscount = MockPaymentDiscount(mockIdentifier: "mySuperDiscount") RCStoreKitWrapper.simulatesAskToBuyInSandbox = false let payment1 = wrapper.payment(with: mockProduct, discount: mockDiscount) expect(payment1.simulatesAskToBuyInSandbox) == false RCStoreKitWrapper.simulatesAskToBuyInSandbox = true let payment2 = wrapper.payment(with: mockProduct) expect(payment2.simulatesAskToBuyInSandbox) == true } } }
36.097166
137
0.69179
c132ed194d1e59530f80d70dfc41fa34f7b476d6
471
// // RNACurrentProgram+.swift // LDLARadio // // Created by fox on 23/07/2019. // Copyright © 2019 Mobile Patagonia. All rights reserved. // import Foundation import CoreData extension RNACurrentProgram: Modellable { /// Function to obtain all the albums sorted by title static func all() -> [RNACurrentProgram]? { return all(predicate: nil, sortDescriptors: [NSSortDescriptor.init(key: "name", ascending: true)]) as? [RNACurrentProgram] } }
23.55
130
0.700637
612afceb27ae577709bb262620029f3f8ecfb7fb
5,545
// // CustomPickerVC.swift // TBVSample // // Created by Lahiru Chathuranga on 11/19/20. // import UIKit protocol CustomPickerVCDelegate { func didSelectDateAndLanguage(month: String, year: String, language: String) } class CustomPickerVC: UIViewController { // MARK: - Outlets @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var titleImage: UIImageView! @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var languageImage: UIImageView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var stackView: UIStackView! // MARK: - Variables let dropDown = MakeDropDown() var yearArray = [String]() var monthArray = [String]() var selectedLabel = UILabel() var dropDownRowHeight: CGFloat = 20 var isDropped: Bool = false var delegate: CustomPickerVCDelegate? override func viewDidLoad() { super.viewDidLoad() setupUI() setUpMonthGestures() setUpYearGestures() setUpLanguageGestures() } func setupUI() { [monthLabel, yearLabel, languageLabel].forEach { (lbl) in lbl?.layer.borderWidth = 1 lbl?.layer.cornerRadius = 4 lbl?.layer.borderColor = UIColor.lightGray.cgColor } contentView.layer.cornerRadius = 6 contentView.addShadowToView() } func setUpMonthGestures(){ self.monthLabel.isUserInteractionEnabled = true let testLabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(monthLabelTapped)) self.monthLabel.addGestureRecognizer(testLabelTapGesture) } func setUpYearGestures(){ self.yearLabel.isUserInteractionEnabled = true let testLabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(yearLabelTapped)) self.yearLabel.addGestureRecognizer(testLabelTapGesture) } func setUpLanguageGestures(){ self.languageLabel.isUserInteractionEnabled = true let testLabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(languageLabelTapped)) self.languageLabel.addGestureRecognizer(testLabelTapGesture) } @objc func monthLabelTapped() { if isDropped { self.dropDown.hideDropDown() self.isDropped = false } else { self.selectedLabel = monthLabel self.isDropped = true self.setUpDropDown(selectedPosition: monthLabel) self.monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December"] self.dropDown.showDropDown(height: self.dropDownRowHeight * 5) } } @objc func yearLabelTapped() { if isDropped { self.dropDown.hideDropDown() self.isDropped = false } else { self.selectedLabel = yearLabel self.isDropped = true self.setUpDropDown(selectedPosition: yearLabel) self.monthArray = ["2018", "2019", "2020", "2021"] self.dropDown.showDropDown(height: self.dropDownRowHeight * 5) } } @objc func languageLabelTapped() { if isDropped { self.dropDown.hideDropDown() self.isDropped = false } else { self.selectedLabel = languageLabel self.isDropped = true self.setUpDropDown(selectedPosition: languageLabel) self.monthArray = ["Sinhala", "Tamil", "English"] self.dropDown.showDropDown(height: self.dropDownRowHeight * 5) } } func setUpDropDown(selectedPosition: UILabel){ dropDown.makeDropDownIdentifier = "DROP_DOWN_NEW" dropDown.cellReusableIdentifier = "dropDownCell" dropDown.makeDropDownDataSourceProtocol = self dropDown.setUpDropDown(viewPositionReference: (selectedPosition.frame), offset: 2) dropDown.nib = UINib(nibName: "DropDownTableViewCell", bundle: nil) dropDown.setRowHeight(height: self.dropDownRowHeight) contentView.addSubview(dropDown) } @IBAction func pressedProceed(_ sender: Any) { if let month = monthLabel.text, let year = yearLabel.text, let language = languageLabel.text { self.delegate?.didSelectDateAndLanguage(month: month, year: year, language: language) self.dismiss(animated: true, completion: nil) } else { print("Fill all the fields") } } @IBAction func pressedCancel(_ sender: Any) { } } extension CustomPickerVC: MakeDropDownDataSourceProtocol{ func getDataToDropDown(cell: UITableViewCell, indexPos: Int, makeDropDownIdentifier: String) { if makeDropDownIdentifier == "DROP_DOWN_NEW"{ let customCell = cell as! DropDownTableViewCell customCell.countryNameLabel.text = self.monthArray[indexPos] } } func numberOfRows(makeDropDownIdentifier: String) -> Int { return self.monthArray.count } func selectItemInDropDown(indexPos: Int, makeDropDownIdentifier: String) { self.selectedLabel.text = self.monthArray[indexPos] self.dropDown.hideDropDown() self.selectedLabel = UILabel() self.isDropped = false } }
32.426901
141
0.635528
e9270398671db55a6b3a03b7d9ce291994fc9782
5,264
// // Generated.swift // iOS // // Created by Jason Zurita on 3/4/18. // Copyright © 2018 Lona. All rights reserved. // import UIKit enum Generated: String { case localAsset = "Local Asset" case nestedComponent = "Nested Component" case nestedButtons = "Nested Buttons" case button = "Button" case pressableRootView = "Pressable Root View" case fitContentParentSecondaryChildren = "Fit Content Parent Secondary Children" case fixedParentFillAndFitChildren = "Fixed Parent Fill and Fit Children" case fixedParentFitChild = "Fixed Parent Fit Child" case primaryAxis = "Primary Axis" case secondaryAxis = "Secondary Axis" case assign = "Assign" case ifEnabled = "If - Enabled" case ifDisabled = "If - Disabled" case borderWidthColor = "Border Width and Color" case textStyleConditionalTrue = "Text Style Conditional - True" case textStyleConditionalFalse = "Text Style Conditional - False" case textStylesTest = "Text Styles Test" case textAlignment = "Text Alignment" case boxModelConditionalSmall = "Box Model Conditional Small" case boxModelConditionalLarge = "Box Model Conditional Large" case shadowsTest = "Shadow Test" case visibilityTest = "Visibility Test" case optionals = "Optionals" static func allValues() -> [Generated] { return [ localAsset, nestedComponent, nestedButtons, button, pressableRootView, fitContentParentSecondaryChildren, fixedParentFillAndFitChildren, fixedParentFitChild, primaryAxis, secondaryAxis, assign, ifEnabled, ifDisabled, borderWidthColor, textStyleConditionalTrue, textStyleConditionalFalse, textStylesTest, textAlignment, boxModelConditionalSmall, boxModelConditionalLarge, shadowsTest, visibilityTest, optionals ] } var view: UIView { switch self { case .localAsset: return LocalAsset() case .nestedComponent: return NestedComponent() case .nestedButtons: return NestedButtons() case .button: var count = 0 let button = Button(label: "Tapped \(count)", secondary: false) button.onTap = { count += 1 button.label = "Tapped \(count)" } return button case .pressableRootView: return PressableRootView() case .fitContentParentSecondaryChildren: return FitContentParentSecondaryChildren() case .fixedParentFillAndFitChildren: return FixedParentFillAndFitChildren() case .fixedParentFitChild: return FixedParentFitChild() case .primaryAxis: return PrimaryAxis() case .secondaryAxis: return SecondaryAxis() case .assign: return Assign(text: "Hello Lona") case .ifEnabled: return If(enabled: true) case .ifDisabled: return If(enabled: false) case .borderWidthColor: return BorderWidthColor(alternativeStyle: true) case .textStyleConditionalTrue: return TextStyleConditional(large: true) case .textStyleConditionalFalse: return TextStyleConditional(large: false) case .textStylesTest: return TextStylesTest() case .textAlignment: return TextAlignment() case .boxModelConditionalSmall: return BoxModelConditional(margin: 4, size: 60) case .boxModelConditionalLarge: return BoxModelConditional(margin: 20, size: 120) case .shadowsTest: return ShadowsTest() case .visibilityTest: return VisibilityTest(enabled: true) case .optionals: return Optionals(boolParam: true, stringParam: "Hello World") } } var constraints: [Constraint] { switch self { case .localAsset, .pressableRootView: return [ equal(\.topAnchor, \.safeAreaLayoutGuide.topAnchor), equal(\.leftAnchor), ] case .button, .nestedComponent, .nestedButtons, .fixedParentFillAndFitChildren, .fixedParentFitChild, .primaryAxis, .secondaryAxis, .borderWidthColor, .textAlignment, .fitContentParentSecondaryChildren, .boxModelConditionalSmall, .boxModelConditionalLarge, .shadowsTest, .visibilityTest, .optionals: return [ equal(\.topAnchor, \.safeAreaLayoutGuide.topAnchor), equal(\.leftAnchor), equal(\.rightAnchor), ] default: return [ equal(\.topAnchor, \.safeAreaLayoutGuide.topAnchor), equal(\.bottomAnchor), equal(\.leftAnchor), equal(\.rightAnchor), ] } } }
33.316456
84
0.585866
7197a62bf183e01dcd7fddeecadf2c2f0deb37b6
772
// // CTA.swift // Driftt // // Created by Eoin O'Connell on 22/01/2016. // Copyright © 2016 Drift. All rights reserved. // import ObjectMapper class CTA: Mappable { /** Types of CTA the SDK can Parse - ChatResponse: Opens a MailCompose window when tapped - LinkToURL: Opens URL when tapped */ enum CTAType: String { case ChatResponse = "CHAT_RESPONSE" case LinkToURL = "LINK_TO_URL" } var copy: String? var ctaType: CTAType? var urlLink: URL? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { copy <- map["copy"] ctaType <- map["CtaType"] urlLink <- (map["UrlLink"], URLTransform()) } }
20.864865
62
0.562176
dd1b1ffee3c8fac63f1b1de90206bbb043acc994
3,497
// nef:begin:header /* layout: docs title: Overview */ // nef:end /*: # Effects {:.beginner} beginner The `BowEffects` module provides a foundation to work with side effects in a functional manner. In order to use it, you only need to import it: */ import BowEffects /*: This module includes multiple facilities to work with side effects: - **Type classes**: abstractions to suspend side effects and execute them asynchronous and concurrently. - **IO**: a powerful data type to encapsulate side effects and work with them in a functional manner. - **Utilities**: data types to work with resources and shared state functionally. ## Type classes Type classes in the Effects module abstract over the suspension of effects and their asynchronous and concurrent execution. The module contains the following type classes: | Type class | Description | | ---------------- | ------------------------------------------------------- | | MonadDefer | Enables delaying the evaluation of a computation | | Async | Enables running asynchronous computations that may fail | | Bracket | Provides safe resource acquisition, usage and release | | Effect | Enables suspension of side effects | | Concurrent | Enables concurrent execution of asynchronous operations | | ConcurrentEffect | Enables cancelation of effects running concurrently | | UnsafeRun | Enables unsafe execution of side effects | ## IO The IO data type is the core data type to provide suspension of side-effects. Its API lets us do powerful transformations and composition, and eventually evaluate them concurrently and asynchronously. IO also provides error handling capabilities. It lets us specify explicitly the type of errors that may happen in its underlying encapsulated side-effects and the type of values it produces. There are several variants of IO depending on the needs of our program: | Variant | Description | | -------------- | ----------- | | IO&lt;E, A&gt; | An encapsulated side effect producing values of type `A` and errors of type `E` | | UIO&lt;A&gt; | An encapsulated side effect producing values of type `A` that will never fail | | Task&lt;A&gt; | An encapsulated side effect producing values of type `A` and no explicit error type (using `Error`) | Besides, if we want to model side effects depending on a context of type `D`, we can use the `EnvIO<D, E, A>` type, or any of its variants: | Variant | Description | | -------------------- | ----------- | | EnvIO&lt;D, E, A&gt; | A side effect depending on context `D` that produces values of type `A` and errors of type `E` | | URIO&lt;D, A&gt; | A side effect depending on context `D` that produces values of type `A` and will never fail | | RIO&lt;D, A&gt; | A side effect depending on context `D` that produces values of type `A` and no explicit error type (using `Error`) | ## Utilities Besides the IO data types, the Effects module provides some utilities: | Data type | Description | | --------- | ----------- | | Atomic&lt;A&gt; | An atomically modifiable reference to a value | | Ref&lt;F, A&gt; | An asynchronous, concurrent mutable reference providing safe functional access and modification of its content | | Resource&lt;F, A&gt; | A resource that provides safe allocation, usage and release | */
49.957143
201
0.665428
75fb25d4fea7a6339106a9637dfeb20a139f530e
6,696
// // PseudoToLanguages.swift // MergeL10n // // Created by Luiz Barbosa on 17.06.20. // Copyright © 2020 Lautsprecher Teufel GmbH. All rights reserved. // import ArgumentParser import Combine import Foundation import FoundationExtensions import L10nModels struct World { let fileManager: SimpleFileManager let environmentVariables: EnvironmentVariables } extension World { static let `default` = World( fileManager: .default, environmentVariables: .default ) } extension SimpleFileManager { static let `default` = SimpleFileManager( fileExists: FileManager.default.fileExists, readTextFile: { path, encoding in Result { try String(contentsOfFile: path, encoding: encoding) } }, createTextFile: { path, contents, encoding in FileManager.default.createFile(atPath: path, contents: contents.data(using: encoding)) } ) } struct EnvironmentVariables { let get: (String) -> String? let set: (String, String) -> Void let loadDotEnv: (String) -> Void } extension EnvironmentVariables { static let `default` = EnvironmentVariables( get: { name in (getenv(name)).flatMap { String(utf8String: $0) } }, set: { key, value in setenv(key, value, 1) }, loadDotEnv: { path in guard let file = try? String(contentsOfFile: path, encoding: .utf8) else { return } file .split { $0 == "\n" || $0 == "\r\n" } .map(String.init) .forEach { fullLine in let line = fullLine.trimmingCharacters(in: .whitespacesAndNewlines) guard line[line.startIndex] != "#" else { return } guard !line.isEmpty else { return } let parts = line.split(separator: "=", maxSplits: 1).map(String.init) let key = parts[0].trimmingCharacters(in: .whitespacesAndNewlines) let value = parts[1].trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: .init(arrayLiteral: "\"")) setenv(key, value, 1) } } ) } struct PseudoToLanguages: ParsableCommand { @Option(help: "Separated-by-comma list of languages that should be created. Environment Variable SUPPORTED_LANGUAGES is an alternative.") var languages: String? @Option(help: "Separated-by-comma list of paths to base localizable strings folders. In this folder we expect to find zz.lproj directory and files. Environment Variable L10N_BASE_PATHS is an alternative.") var basePaths: String? @Option(default: "en", help: "Which language is used for development. Default: en.") var developmentLanguage: String func run() throws { let world = World.default let paramLanguages = self.languages let paramBasePaths = self.basePaths let paramDevelopmentLanguage = self.developmentLanguage _ = try languagesAndPaths(languages: paramLanguages, paths: paramBasePaths) .mapResultError(identity) .contramapEnvironment(\World.environmentVariables) .flatMapResult { languages, paths -> Reader<World, Result<[Void], Error>> in print("Running MergeL10n with languages: \(languages) and development language: \(paramDevelopmentLanguage)") return paths .traverse { folder in self.run(folder: folder, languages: languages, developmentLanguage: paramDevelopmentLanguage) .mapResultError(identity) .contramapEnvironment(\.fileManager) } .mapValue { $0.traverse(identity) } } .inject(world) .get() } private func run(folder: String, languages: [String], developmentLanguage: String) -> Reader<SimpleFileManager, Result<Void, LocalizedStringFileError>>{ Reader { fileManager in LocalizedStringFile(basePath: folder, language: "zz") .read(encoding: .utf16, requiresComments: true) .inject(fileManager) .flatMap { zzEntries in languages.traverse { language in LocalizedStringFile.replace( language: LocalizedStringFile(basePath: folder, language: language), withKeysFrom: zzEntries, fillWithEmpty: language == developmentLanguage, encoding: .utf8 ).inject(fileManager) } }.map(ignore) } } private func languagesAndPaths(languages: String?, paths: String?) -> Reader<EnvironmentVariables, Result<(languages: [String], paths: [String]), ValidationError>> { Reader { environmentVariables in if self.languages == nil || self.basePaths == nil { // Load the .env file environmentVariables.loadDotEnv(".env") } return zip( languages.map(Result<String, ValidationError>.success) ?? self.supportedLanguagesFromEnvironment().inject(environmentVariables), paths.map(Result<String, ValidationError>.success) ?? self.basePathsFromEnvironment().inject(environmentVariables) ).map { (languages: String, paths: String) -> (languages: [String], paths: [String]) in ( languages: languages.split(separator: ",").map(String.init), paths: paths.split(separator: ",").map(String.init) ) } } } private func supportedLanguagesFromEnvironment() -> Reader<EnvironmentVariables, Result<String, ValidationError>> { Reader { environmentVariables in environmentVariables.get("SUPPORTED_LANGUAGES") .toResult(orError: ValidationError( "Use --languages:\"en,pt\" option or set `SUPPORTED_LANGUAGES` environment variable before running the script. File .env is also an option." )) } } private func basePathsFromEnvironment() -> Reader<EnvironmentVariables, Result<String, ValidationError>> { Reader { environmentVariables in environmentVariables.get("L10N_BASE_PATHS") .toResult(orError: ValidationError( "Use --base-paths:\"SomeFolder/Resources,AnotherFolder/Resources\" option or set `L10N_BASE_PATHS` environment variable before running the script. File .env is also an option." )) } } }
41.85
209
0.606631
ed0cd619d9693ee25a33961c39686251fcfa3f44
13,386
// // TDGooglePlacePickerController.swift // TDGooglePlacePicker // // Created by jhonger delgado on 6/22/19. // Copyright © 2019 jhonger delgado. All rights reserved. // import GooglePlaces import GoogleMaps final public class TDGooglePlacePickerMapViewController: UIViewController { @IBOutlet weak var actualLocationView: UIView! @IBOutlet weak var loadingView: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var nearHeaderLabel: UILabel! @IBOutlet weak var selectedPlaceTextLabel: UILabel! @IBOutlet weak var searchDetailButton: UIBarButtonItem! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var bottomSearchButtonView: UIView! @IBOutlet weak var mapView: GMSMapView! @IBOutlet weak var distanceBetweenHeaderButton: NSLayoutConstraint! var delegate: TDGooglePlacePickerViewControllerDelegate? let locationManager = CLLocationManager() var nearPlaceInCoordenate:[PlaceResponse] = [] var isNearMenuOpen: Bool = false var pickerConfig: TDGooglePlacePickerConfig! var currentLocation: CLLocation? var selectedPlace: PlaceResponse? { didSet{ updateSelectedPlace() } } override public var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override public func viewDidLoad() { super.viewDidLoad() self.setNeedsStatusBarAppearanceUpdate() loadNav() loadMap() loadSearchButton() updateSelectedPlace() } // Config Section func loadNav(){ self.navigationController?.title = pickerConfig.titleNavigationButton self.navigationItem.leftBarButtonItem?.title = pickerConfig.backButton if let backgroundColor = pickerConfig.resultBackgroundColor { self.actualLocationView.backgroundColor = backgroundColor } } func loadMap(){ locationManager.delegate = self mapView.isMyLocationEnabled = pickerConfig.isUsedCurrentLocation mapView.settings.myLocationButton = pickerConfig.isUsedCurrentLocation tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 60, right: 0) mapView?.setMinZoom(Constants.minZoom, maxZoom: Constants.maxZoom) if self.pickerConfig.zoom < mapView.minZoom{ pickerConfig.zoom = mapView.minZoom } else if self.pickerConfig.zoom > mapView.maxZoom{ pickerConfig.zoom = mapView.maxZoom } mapView?.animate(toZoom: pickerConfig.zoom) mapView?.settings.scrollGestures = true mapView?.settings.zoomGestures = true mapView?.settings.tiltGestures = true mapView?.settings.rotateGestures = false mapView?.isMyLocationEnabled = pickerConfig.isUsedCurrentLocation mapView?.delegate = self locationManager.requestWhenInUseAuthorization() } func loadSearchButton(){ searchButton.setTitle(pickerConfig.titleSerchTextUnableButton, for: .normal) searchButton.setTitleColor(pickerConfig.colorTitleTextButton, for: .normal) nearHeaderLabel.text = pickerConfig.nearHeadertextTitle } private func formatTitle(with place: PlaceResponse) -> NSAttributedString{ let titleFontAtributtes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: pickerConfig.fontTitle] let subtitleFontAtributtes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: pickerConfig.fontText] let attributedString = NSMutableAttributedString() if place.name != place.formatedAdress { let title = NSAttributedString(string: place.name, attributes: titleFontAtributtes) attributedString.append(title) let subtitle = NSAttributedString(string: "\n" + place.formatedAdress, attributes: subtitleFontAtributtes) attributedString.append(subtitle) } else { let title = NSAttributedString(string: place.name, attributes: subtitleFontAtributtes) attributedString.append(title) } return attributedString } func updateSelectedPlace(){ if let place = selectedPlace{ searchButton.isEnabled = true searchButton.backgroundColor = pickerConfig.colorTitleBackgroundButton bottomSearchButtonView.backgroundColor = pickerConfig.colorTitleBackgroundButton selectedPlaceTextLabel.attributedText = formatTitle(with: place) searchButton.setTitle(pickerConfig.titleSerchTextButton, for: .normal) } else { searchButton.isEnabled = false searchButton.backgroundColor = .gray bottomSearchButtonView.backgroundColor = .gray selectedPlaceTextLabel.text = "--" searchButton.setTitle(pickerConfig.titleSerchTextUnableButton, for: .normal) } } //Events @IBAction func selectPlace(_ sender: Any) { guard let place = selectedPlace else { return } delegate?.placePicker(self, didPick: place) } @IBAction func cancel(_ sender: Any) { delegate?.placePickerDidCancel(self) } @IBAction func searchDetail(_ sender: Any) { let autocompleteController = GMSAutocompleteViewController() autocompleteController.delegate = self // Specify the place data types to return. let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) | UInt(GMSPlaceField.placeID.rawValue) | UInt(GMSPlaceField.coordinate.rawValue) | UInt(GMSPlaceField.formattedAddress.rawValue))! autocompleteController.placeFields = fields // Specify a filter. let filter = GMSAutocompleteFilter() filter.type = .noFilter filter.country = pickerConfig.country autocompleteController.autocompleteFilter = filter // Display the autocomplete view controller. navigationController?.pushViewController(autocompleteController, animated: true) } fileprivate func addMarker(_ coordinate: CLLocationCoordinate2D?, name: String?){ mapView.clear() guard let name = name, let coordinate = coordinate else { return } // Creates a marker in the center of the map. let marker = GMSMarker() marker.position = coordinate marker.title = name marker.map = mapView } fileprivate func tapLocationEvent(_ coordinate: CLLocationCoordinate2D){ let camera = GMSCameraPosition.camera(withLatitude: coordinate.latitude , longitude: coordinate.longitude, zoom: self.mapView?.camera.zoom ?? self.pickerConfig.zoom) self.mapView?.animate(to: camera) self.addMarker(coordinate, name: "-") if pickerConfig.seeNearbyPlace{ seeNearbyplaces(from: coordinate) } loadingView.startAnimating() TDGooglePlacePickerService.getLocationAproxName(with: coordinate) { [weak self] response in self?.loadingView.stopAnimating() self?.selectedPlace = response?.first self?.selectedPlace?.coordinate = coordinate self?.addMarker(self?.selectedPlace?.coordinate, name: self?.selectedPlace?.name) } } fileprivate func seeNearbyplaces(from coordinate: CLLocationCoordinate2D){ TDGooglePlacePickerService.getNearbyPlaces(with: coordinate) { [weak self] response in guard let response = response, let self = self else { return } self.nearPlaceInCoordenate = response self.openTableView(with: response.count) } } } // MARK: - GMSMapViewDelegate @ Eventos del mapa extension TDGooglePlacePickerMapViewController: GMSMapViewDelegate{ public func didTapMyLocationButton(for mapView: GMSMapView) -> Bool { guard let myLocation = mapView.myLocation else { locationManager.requestLocation() return false } tapLocationEvent(myLocation.coordinate) return false } public func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) { tapLocationEvent(coordinate) } public func mapView(_ mapView: GMSMapView, willMove gesture: Bool) { if isNearMenuOpen{ closeTableView() } } } // MARK: - Seccion del buscador extension TDGooglePlacePickerMapViewController: GMSAutocompleteViewControllerDelegate { // Handle the user's selection. public func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { self.loadingView.stopAnimating() let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude , longitude: place.coordinate.longitude, zoom: pickerConfig.zoom) mapView?.animate(to: camera) selectedPlace = PlaceResponse(place: place) addMarker(place.coordinate, name: place.name) navigationController?.popViewController(animated: true) } public func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { print("Error: ", error.localizedDescription) } // User canceled the operation. public func wasCancelled(_ viewController: GMSAutocompleteViewController) { navigationController?.popViewController(animated: true) } // Turn the network activity indicator on and off again. public func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } public func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } // MARK: Eventos de la tabla de sitios cercanos extension TDGooglePlacePickerMapViewController{ func openTableView(with resultCount: Int){ let sizeOfCell: CGFloat = 50.0 if resultCount < 5 { self.distanceBetweenHeaderButton.constant = sizeOfCell * CGFloat(resultCount) return } self.distanceBetweenHeaderButton.constant = sizeOfCell * CGFloat(5) UIView.animate(withDuration: 0.8, animations: { self.view.layoutIfNeeded() }, completion: { _ in self.isNearMenuOpen = true self.tableView.reloadData() }) } func closeTableView(){ nearPlaceInCoordenate = [] self.distanceBetweenHeaderButton.constant = 0 self.isNearMenuOpen = false UIView.animate(withDuration: 0.8, animations: { self.view.layoutIfNeeded() }, completion: { _ in self.tableView.reloadData() }) } } // MARK: - UITableViewDelegate @ Evento al seleccionar una celda extension TDGooglePlacePickerMapViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let place = nearPlaceInCoordenate[indexPath.row] selectedPlace = place let camera = GMSCameraPosition.camera(withLatitude: place.coordinate.latitude , longitude: place.coordinate.longitude, zoom: pickerConfig.zoom) mapView?.animate(to: camera) addMarker(place.coordinate, name: place.name) } } // MARK: - UITableViewDataSource @ Evento del datasource extension TDGooglePlacePickerMapViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nearPlaceInCoordenate.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "nearCell", for: indexPath) let place = nearPlaceInCoordenate[indexPath.row] cell.textLabel?.text = place.name cell.detailTextLabel?.text = place.formatedAdress return cell } } extension TDGooglePlacePickerMapViewController: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { guard status == .authorizedWhenInUse || status == .authorizedAlways else { mapView.isMyLocationEnabled = false mapView.settings.myLocationButton = false return } if let coordenate = pickerConfig.initialCoordenate { tapLocationEvent(coordenate) return } locationManager.requestLocation() } // 6 public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } self.tapLocationEvent(location.coordinate) } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } }
39.60355
224
0.690946
33834364ea6f9b3f5f023822fa0100036b9649f3
6,991
// // BrandingTableViewController.swift // Workspace-ONE-SDK-iOS-Swift-Sample // // Copyright 2021 VMware, Inc. // SPDX-License-Identifier: BSD-2-Clause // import UIKit /// Apply branding colours and images to SDK UI. /// Two Sources of Branding Information : Enterprise Branding and Static Branding. /// Here Enterprise branding is integrated for Static branding refer to a workspace one SDK document. class EnterpriseBrandingViewController: UITableViewController { private var brandingImageInformation = [(String, Any)]() private var brandingColorInformation = [(String, Any)]() override func viewDidLoad() { super.viewDidLoad() self.retrieveBrandingInfo() self.tableView.tableFooterView = UIView() } /// retrieving branding info and storing it in key-value pair and loading in UITableView. private func retrieveBrandingInfo() { guard let brandingPayload = AWSDKHelper.shared.brandingPayload else { return } if let organizationName = brandingPayload.organizationName { if(!organizationName.isEmpty) { brandingColorInformation.append(("Organization Name",organizationName)) } } if let primaryHighlightColor = brandingPayload.primaryHighlightColor { brandingColorInformation.append(("Primary highlight",primaryHighlightColor)) } if let primaryColor = brandingPayload.primaryColor { brandingColorInformation.append(("Primary",primaryColor)) } if let secondaryHighlightColor = brandingPayload.secondaryHighlightColor { brandingColorInformation.append(("Secondary highlight",secondaryHighlightColor)) } if let secondaryColor = brandingPayload.secondaryColor { brandingColorInformation.append(("Secondary",secondaryColor)) } if let toolbarColor = brandingPayload.toolbarColor { brandingColorInformation.append(("Toolbar",toolbarColor)) } if let primaryTextColor = brandingPayload.primaryTextColor { brandingColorInformation.append(("Primary text",primaryTextColor)) } if let secondaryTextColor = brandingPayload.secondaryTextColor { brandingColorInformation.append(("Secondary text",secondaryTextColor)) } if let loginTitleTextColor = brandingPayload.loginTitleTextColor { brandingColorInformation.append(("Login title text",loginTitleTextColor)) } if let tertiaryTextColor = brandingPayload.tertiaryTextColor { brandingColorInformation.append(("Tertiary text",tertiaryTextColor)) } if let toolbarTextColor = brandingPayload.toolbarTextColor { brandingColorInformation.append(("Toolbar text",toolbarTextColor)) } if let iPhoneBackgroundImageURL = brandingPayload.iPhoneBackgroundImageURL { brandingImageInformation.append(("iPhone background",iPhoneBackgroundImageURL)) } if let iPhone2xBackgroundImageURL = brandingPayload.iPhone2xBackgroundImageURL { brandingImageInformation.append((key: "iPhone2x background", value: iPhone2xBackgroundImageURL)) } if let iPhone52xBackgroundImageURL = brandingPayload.iPhone52xBackgroundImageURL { brandingImageInformation.append((key: "iPhone52x background", value: iPhone52xBackgroundImageURL)) } if let iPadBackgroundImageURL = brandingPayload.iPadBackgroundImageURL { brandingImageInformation.append((key: "iPad background", value: iPadBackgroundImageURL)) } if let iPad2xBackgroundImageURL = brandingPayload.iPad2xBackgroundImageURL { brandingImageInformation.append((key: "iPad2x background", value: iPad2xBackgroundImageURL)) } if let iPhoneCompanyLogoURL = brandingPayload.iPhoneCompanyLogoURL { brandingImageInformation.append((key: "iPhone company logo", value: iPhoneCompanyLogoURL)) } if let iPhone2xCompanyLogoURL = brandingPayload.iPhone2xCompanyLogoURL { brandingImageInformation.append((key: "iPhone2x company logo", value: iPhone2xCompanyLogoURL)) } if let iPadCompanyLogoURL = brandingPayload.iPadCompanyLogoURL { brandingImageInformation.append((key: "iPad company logo", value: iPadCompanyLogoURL)) } if let iPad2xCompanyLogoURL = brandingPayload.iPad2xCompanyLogoURL { brandingImageInformation.append((key: "iPad2x company logo", value: iPad2xCompanyLogoURL)) } self.tableView.reloadData() } } // MARK: - Table view data source extension EnterpriseBrandingViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return brandingColorInformation.count case 1: return brandingImageInformation.count default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "brandingCell", for: indexPath) as? BrandingCell else { return UITableViewCell() } // Configure the cell... switch indexPath.section { case 0: let labelKeyString = self.brandingColorInformation[indexPath.row].0 cell.brandingLabel.text = labelKeyString cell.brandingColorImage.isHidden = true cell.brandingColorLabel.isHidden = false cell.brandingColorLabel.backgroundColor = brandingColorInformation[indexPath.row].1 as? UIColor case 1: let labelKeyString = self.brandingImageInformation[indexPath.row].0 cell.brandingLabel.text = labelKeyString cell.brandingColorImage.isHidden = false cell.brandingColorLabel.isHidden = true // loading image from URL if let imgURL = brandingImageInformation[indexPath.row].1 as? URL { cell.brandingColorImage.load(url: imgURL) } default: break } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Colour Information" case 1: return "Image Information" default: return "" } } } class BrandingCell : UITableViewCell { @IBOutlet weak var brandingLabel: UILabel! @IBOutlet weak var brandingColorLabel: UILabel! @IBOutlet weak var brandingColorImage: UIImageView! }
39.275281
126
0.669861
b9d309cbf03f64dce046669ce59212a88e7d544a
672
// // Reporter.swift // IBLinterKit // // Created by SaitoYuta on 2017/12/11. // protocol Reporter { static var identifier: String { get } static func generateReport(violations: [Violation]) -> String } struct Reporters { static func reporter(from reporter: String) -> Reporter.Type { switch reporter { case XcodeReporter.identifier: return XcodeReporter.self case JSONReporter.identifier: return JSONReporter.self case EmojiReporter.identifier: return EmojiReporter.self default: fatalError("no reporter with identifier '\(reporter) available'") } } }
23.172414
77
0.636905
fbf50fc9d5443fc6bf6c5650e61e75874e6a52a1
742
struct Triangle { let a, b, c: Double init(_ a: Double, _ b: Double, _ c: Double) { (self.a, self.b, self.c) = (a, b, c) } var kind: String { let perimeter = (a + b + c) guard min(a, b, c) > 0 && // all side lengths are positive max(a, b, c) <= (perimeter) - max(a, b, c) // degenerate inclusive else { return "ErrorKind" } switch (a == b, b == c, c == a ) { case (true, true, true): return "Equilateral" // all three sides are the same length case (false, false, false): return "Scalene" // all sides are of different lengths default: return "Isosceles" // two sides are the same length } } }
29.68
78
0.508086
e4b715e2e344ac0cac3f5b44867190e8d68d38a2
4,432
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit /// A generic protocol which exposes the properties used by Apple's CKFetchRecordsOperation. public protocol CKFetchRecordsOperationProtocol: CKDatabaseOperationProtocol, CKDesiredKeys { /// - returns: the record IDs var recordIDs: [RecordID]? { get set } /// - returns: a per record progress block var perRecordProgressBlock: ((RecordID, Double) -> Void)? { get set } /// - returns: a per record completion block var perRecordCompletionBlock: ((Record?, RecordID?, Error?) -> Void)? { get set } /// - returns: the fetch record completion block var fetchRecordsCompletionBlock: (([RecordID: Record]?, Error?) -> Void)? { get set } } public struct FetchRecordsError<Record, RecordID: Hashable>: CloudKitError { public let underlyingError: Error public let recordsByID: [RecordID: Record]? } extension CKFetchRecordsOperation: CKFetchRecordsOperationProtocol, AssociatedErrorProtocol { // The associated error type public typealias AssociatedError = FetchRecordsError<Record, RecordID> } extension CKProcedure where T: CKFetchRecordsOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { public var recordIDs: [T.RecordID]? { get { return operation.recordIDs } set { operation.recordIDs = newValue } } public var perRecordProgressBlock: CloudKitProcedure<T>.FetchRecordsPerRecordProgressBlock? { get { return operation.perRecordProgressBlock } set { operation.perRecordProgressBlock = newValue } } public var perRecordCompletionBlock: CloudKitProcedure<T>.FetchRecordsPerRecordCompletionBlock? { get { return operation.perRecordCompletionBlock } set { operation.perRecordCompletionBlock = newValue } } func setFetchRecordsCompletionBlock(_ block: @escaping CloudKitProcedure<T>.FetchRecordsCompletionBlock) { operation.fetchRecordsCompletionBlock = { [weak self] recordsByID, error in if let strongSelf = self, let error = error { strongSelf.append(fatalError: FetchRecordsError(underlyingError: error, recordsByID: recordsByID)) } else { block(recordsByID) } } } } extension CloudKitProcedure where T: CKFetchRecordsOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { /// A typealias for the block types used by CloudKitOperation<CKFetchRecordsOperation> public typealias FetchRecordsPerRecordProgressBlock = (T.RecordID, Double) -> Void /// A typealias for the block types used by CloudKitOperation<CKFetchRecordsOperation> public typealias FetchRecordsPerRecordCompletionBlock = (T.Record?, T.RecordID?, Error?) -> Void /// A typealias for the block types used by CloudKitOperation<CKFetchRecordsOperation> public typealias FetchRecordsCompletionBlock = ([T.RecordID: T.Record]?) -> Void /// - returns: the record IDs public var recordIDs: [T.RecordID]? { get { return current.recordIDs } set { current.recordIDs = newValue appendConfigureBlock { $0.recordIDs = newValue } } } /// - returns: a block for the record progress public var perRecordProgressBlock: FetchRecordsPerRecordProgressBlock? { get { return current.perRecordProgressBlock } set { current.perRecordProgressBlock = newValue appendConfigureBlock { $0.perRecordProgressBlock = newValue } } } /// - returns: a block for the record completion public var perRecordCompletionBlock: FetchRecordsPerRecordCompletionBlock? { get { return current.perRecordCompletionBlock } set { current.perRecordCompletionBlock = newValue appendConfigureBlock { $0.perRecordCompletionBlock = newValue } } } /** Before adding the CloudKitOperation instance to a queue, set a completion block to collect the results in the successful case. Setting this completion block also ensures that error handling gets triggered. - parameter block: a FetchRecordsCompletionBlock block */ public func setFetchRecordsCompletionBlock(block: @escaping FetchRecordsCompletionBlock) { appendConfigureBlock { $0.setFetchRecordsCompletionBlock(block) } } }
38.206897
132
0.71074
0e0e71dbd5d3e0717f92333841eb3939684694de
2,899
// // NetworkConfig.swift // RxNetworks // // Created by Condy on 2021/10/5. // ///`Moya`文档 /// https://github.com/Moya/Moya /// ///`SwiftyJSON`文档 /// https://github.com/SwiftyJSON/SwiftyJSON import Foundation import Alamofire import RxSwift import Moya public typealias APIHost = String public typealias APIPath = String public typealias APINumber = Int public typealias APIMethod = Moya.Method public typealias APIParameters = Alamofire.Parameters public typealias APIPlugins = [RxNetworks.PluginSubType] public typealias APIStubBehavior = Moya.StubBehavior public typealias APIObservableJSON = RxSwift.Observable<Any> /// 网络配置信息,只需要在程序开启的时刻配置一次 /// Network configuration information, only need to be configured once when the program is started public struct NetworkConfig { /// Whether to add the Debugging plugin by default public static var addDebugging: Bool = false /// Whether to add the Indicator plugin by default public static var addIndicator: Bool = false /// Plugins that require default injection, generally not recommended /// However, you can inject this kind of global unified general plugin, such as secret key plugin, certificate plugin, etc. public static var injectionPlugins: [PluginSubType]? /// Set the request timeout, the default is 30 seconds public static var timeoutIntervalForRequest: TimeInterval = 30 /// Root path address public private(set) static var baseURL: APIHost = "" /// Default basic parameters, similar to: userID, token, etc. public private(set) static var baseParameters: APIParameters = [:] /// Default request type, default `post` public private(set) static var baseMethod: APIMethod = APIMethod.post /// Default Header argument public static var baseHeaders: [String:String] = [:] /// Configuration information /// - Parameters: /// - host: Root path address. /// - parameters: Default basic parameters, similar to: userID, token, etc. /// - method: Default request type, default `post` public static func setupDefault(host: APIHost = "", parameters: APIParameters = [:], method: APIMethod = APIMethod.post) { self.baseURL = host self.baseParameters = parameters self.baseMethod = method } /// Update the default basic parameter data, which is generally used for what operation the user has switched. /// - Parameters: /// - value: Update value /// - key: Update key public static func updateBaseParametersWithValue(_ value: AnyObject?, key: String) { var dict = NetworkConfig.baseParameters if let value = value { dict.updateValue(value, forKey: key) } else { dict.removeValue(forKey: key) } NetworkConfig.baseParameters = dict } }
37.166667
127
0.683339
298096800d8173cacd1bc973ca9b934477d9beec
3,818
// // Claim.swift // Odysee // // Created by Akinwale Ariwodola on 02/11/2020. // import Foundation class Claim: Decodable, Equatable, Hashable { var address: String? var amount: String? var canonicalUrl: String? var claimId: String? var claimOp: String? var confirmations: Int? var height: Int? var isChannelSignatureValid: Bool? var meta: Meta? var name: String? var normalizedName: String? var nout: Int? var permanentUrl: String? var shortUrl: String? var signingChannel: Claim? var repostedClaim: Claim? var timestamp: Int64? var txid: String? var type: String? var value: Metadata? var valueType: String? var selected: Bool = false private enum CodingKeys: String, CodingKey { case address, amount, canonicalUrl = "canonical_url", claimId = "claim_id", claimOp = "claim_op", confirmations, height, isChannelSignatureValid = "is_channel_signature_valid", meta, name, normalizedName = "normalized_name", nout, permanentUrl = "permanent_url", shortUrl = "short_url", signingChannel = "signing_channel", repostedClaim = "reposted_claim", timestamp, txid, value, valueType = "value_type" } struct Metadata: Decodable { var title: String? var description: String? var thumbnail: Resource? var languages: [String]? var tags: [String]? var locations: [Location]? // channel var publicKey: String? var publicKeyId: String? var cover: Resource? var email: String? var websiteUrl: String? var featured: [String]? // stream var license: String? var licenseUrl: String? var releaseTime: String? var author: String? var fee: Fee? var streamType: String? var source: Source? var video: StreamInfo? var audio: StreamInfo? var image: StreamInfo? var software: StreamInfo? private enum CodingKeys: String, CodingKey { case title, description, thumbnail, languages, tags, locations, publicKey = "public_key", publicKeyId = "public_key_id", cover, email, websiteUrl = "website_url", featured, license, licenseUrl = "license_url", releaseTime = "release_time", author, fee, streamType = "stream_type", source, video, audio, image, software } } struct Source: Decodable { var sdHash: String? var mediaType: String? var hash: String? var name: String? var size: String? private enum CodingKeys: String, CodingKey { case sdHash = "sd_hash", mediaType = "media_type", hash, name, size } } struct Fee: Decodable { var amount: String? var currency: String? var address: String? } struct Location: Decodable { var country: String? } struct Resource: Decodable { // TODO: make this `URL?` var url: String? } struct StreamInfo: Decodable { var duration: Int64? var height: Int64? var width: Int64? var os: String? } struct Meta: Decodable { var effectiveAmount: String? private enum CodingKeys: String, CodingKey { case effectiveAmount = "effective_amount" } } static func ==(lhs:Claim, rhs:Claim) -> Bool { return lhs.claimId == rhs.claimId } func hash(into hasher: inout Hasher) { claimId.hash(into: &hasher) } var outpoint: Outpoint? { if let txid = txid, let nout = nout { return Outpoint(txid: txid, index: nout) } else { return nil } } }
30.062992
135
0.593504
463884e55f75ef915d7dd0ead97e1f95cc682dca
596
// // Constants.swift // apduKit // // Created by Iain Munro on 24/08/2018. // Copyright © 2018 UL-TS. All rights reserved. // import Foundation public struct Constants { public static let EXTENDED_LENGTH = short(short.max)//Standard says 65536, but you can't represent a value that high in a short. public static let TAG_BYTE_SIZE = 1 public static let DEFAULT_MAX_EXPECTED_LENGTH = 0//0 means 255 public static let BYTE_OFFSET_TILL_LENGTH = Constants.TAG_BYTE_SIZE + 1//At least the tag and then the one byte of length public static let SIZE_RESPONSE_STATUS_CODE = 2 }
35.058824
132
0.741611
f4b84884ee3c9755593dbb788b2d54c853578d06
1,871
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 final class ProfileViewController: UIViewController { // MARK: - Properties @IBOutlet weak var profileImageView: ProfileImageView! @IBOutlet weak var fullNameLabel: ProfileNameLabel! }
51.972222
83
0.760556
091fd75ced1cc79b9ea4499363fb972260e97552
1,637
// Please help improve quicktype by enabling anonymous telemetry with: // // $ quicktype --telemetry enable // // You can also enable telemetry on any quicktype invocation: // // $ quicktype pokedex.json -o Pokedex.cs --telemetry enable // // This helps us improve quicktype by measuring: // // * How many people use quicktype // * Which features are popular or unpopular // * Performance // * Errors // // quicktype does not collect: // // * Your filenames or input data // * Any personally identifiable information (PII) // * Anything not directly related to quicktype's usage // // If you don't want to help improve quicktype, you can dismiss this message with: // // $ quicktype --telemetry disable // // For a full privacy policy, visit app.quicktype.io/privacy // import Foundation /// User login success struct UserLoginSucceeded: KBIEvent { let client: Client let common: Common let eventName: String let eventType: String let user: User enum CodingKeys: String, CodingKey { case client, common case eventName = "event_name" case eventType = "event_type" case user } } extension UserLoginSucceeded { init() throws { let es = EventsStore.shared guard let user = es.userProxy?.snapshot, let common = es.commonProxy?.snapshot, let client = es.clientProxy?.snapshot else { throw BIError.proxyNotSet } self.user = user self.common = common self.client = client eventName = "user_login_succeeded" eventType = "business" } }
24.432836
82
0.648137
f5f5de07a159605756a3d81c1ff2ad3fe9ca54d7
36,522
/* MIT License Copyright (c) 2017-2019 MessageKit 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 UIKit public enum MessageContentMode { case normal case multiSelect } /// A subclass of `MessageCollectionViewCell` used to display text, media, and location messages. open class MessageContentCell: MessageCollectionViewCell, UIGestureRecognizerDelegate { /// The view displaying the selection open var selectionImage: UIImageView = UIImageView() /// The view displaying the reaction open var reactionView: UIView = UIView() /// The view displaying the status open var statusView: UIView = UIView() /// The image view displaying the avatar. open var avatarView: AvatarView = AvatarView() /// The container used for styling and holding the message's content view. open var messageContainerView: UIView = { let containerView = UIView() containerView.backgroundColor = .clear return containerView }() open var contentContainerView: UIView = { let view = UIView() return view }() open var replyContainerView: UIView = { let view = UIView() view.clipsToBounds = true view.layer.cornerRadius = 17 return view }() /// The top label of the cell. open var cellTopLabel: InsetLabel = { let label = InsetLabel() label.textInsets = UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 7) label.numberOfLines = 1 label.textAlignment = .center label.backgroundColor = .clear return label }() open var sparateTopLine: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 17/255, green: 17/255, blue: 17/255, alpha: 0.1) view.translatesAutoresizingMaskIntoConstraints = false return view }() /// The bottom label of the cell. open var cellBottomLabel: InsetLabel = { let label = InsetLabel() label.numberOfLines = 0 label.textAlignment = .center return label }() /// The top label of the messageBubble. open var messageTopLabel: InsetLabel = { let label = InsetLabel() label.numberOfLines = 0 return label }() /// The bottom label of the messageBubble. open var messageBottomLabel: InsetLabel = { let label = InsetLabel() label.numberOfLines = 0 return label }() /// The time label of the messageBubble. open var messageTimestampLabel: InsetLabel = InsetLabel() // Should only add customized subviews - don't change accessoryView itself. open var accessoryView: UIView = UIView() lazy var replyIconImage: UIButton = { let replyIcon = UIButton() replyIcon.translatesAutoresizingMaskIntoConstraints = false replyIcon.alpha = 0 return replyIcon }() lazy var editIconImage: UIButton = { let replyIcon = UIButton() replyIcon.isUserInteractionEnabled = false return replyIcon }() open var messageContentMode: MessageContentMode = .normal /// Customized for gesture var startAnimation: Bool = false var presentMessage: MessageType! var isAvailableGesture: Bool = false var safePanWork: Bool = false /// The `MessageCellDelegate` for the cell. open weak var delegate: MessageCellDelegate? public override init(frame: CGRect) { super.init(frame: frame) contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] setupSubviews() setupGestures() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] setupSubviews() setupGestures() } open func setupGestures() { let panGesture = UIPanGestureRecognizer() panGesture.addTarget(self, action: #selector(handlePanGesture(_:))) panGesture.delegate = self contentView.addGestureRecognizer(panGesture) } open func setupSubviews() { contentView.addSubview(accessoryView) contentView.addSubview(sparateTopLine) contentView.addSubview(cellTopLabel) contentView.addSubview(messageTopLabel) contentView.addSubview(messageBottomLabel) contentView.addSubview(cellBottomLabel) contentView.addSubview(messageContainerView) messageContainerView.addSubview(replyContainerView) messageContainerView.addSubview(contentContainerView) contentView.addSubview(avatarView) contentView.addSubview(messageTimestampLabel) contentView.addSubview(editIconImage) messageContainerView.addSubview(reactionView) contentView.addSubview(statusView) contentView.addSubview(selectionImage) } open override func prepareForReuse() { super.prepareForReuse() cellTopLabel.text = nil cellBottomLabel.text = nil messageTopLabel.text = nil messageBottomLabel.text = nil messageTimestampLabel.attributedText = nil selectionImage.image = nil } // MARK: - Configuration open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) guard let attributes = layoutAttributes as? MessagesCollectionViewLayoutAttributes else { return } // Call this before other laying out other subviews replyIconImage.setImage(attributes.replyImageIcon, for: .normal) layoutMessageContainerView(with: attributes) layoutEditIcon(with: attributes) layoutReactionView(with: attributes) layoutStatusView(with: attributes) layoutMessageBottomLabel(with: attributes) layoutCellBottomLabel(with: attributes) layoutCellTopLabel(with: attributes) layoutMessageTopLabel(with: attributes) layoutAvatarView(with: attributes) layoutAccessoryView(with: attributes) layoutTimeLabelView(with: attributes) layoutSelectionView(with: attributes) } /// Used to configure the cell. /// /// - Parameters: /// - message: The `MessageType` this cell displays. /// - indexPath: The `IndexPath` for this cell. /// - messagesCollectionView: The `MessagesCollectionView` in which this cell is contained. open func configure(with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) { guard let dataSource = messagesCollectionView.messagesDataSource else { fatalError(MessageKitError.nilMessagesDataSource) } guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else { fatalError(MessageKitError.nilMessagesDisplayDelegate) } delegate = messagesCollectionView.messageCellDelegate presentMessage = message let messageColor = displayDelegate.backgroundColor(for: message, at: indexPath, in: messagesCollectionView) let messageRadius = displayDelegate.radiusMessage(for: message, at: indexPath, in: messagesCollectionView) let messageReplyColor = displayDelegate.replyColor(for: message, at: indexPath, in: messagesCollectionView) let messageBoderWidth = displayDelegate.borderMessageWidth(for: message, at: indexPath, in: messagesCollectionView) let messageBoderColor = displayDelegate.borderMesssageColor(for: message, at: indexPath, in: messagesCollectionView) displayDelegate.configureAvatarView(avatarView, for: message, at: indexPath, in: messagesCollectionView) displayDelegate.configureAccessoryView(accessoryView, for: message, at: indexPath, in: messagesCollectionView) displayDelegate.configureStatusView(statusView, for: message, at: indexPath, in: messagesCollectionView) if message.hasReaction > 0 { displayDelegate.configureReactionView(reactionView, for: message, at: indexPath, in: messagesCollectionView) } contentContainerView.backgroundColor = messageColor contentContainerView.layer.cornerRadius = messageRadius contentContainerView.layer.borderWidth = messageBoderWidth contentContainerView.layer.borderColor = messageBoderColor.cgColor replyContainerView.backgroundColor = messageReplyColor backgroundColor = .clear let topCellLabelText = dataSource.cellTopLabelAttributedText(for: message, at: indexPath) let bottomCellLabelText = dataSource.cellBottomLabelAttributedText(for: message, at: indexPath) let topMessageLabelText = dataSource.messageTopLabelAttributedText(for: message, at: indexPath) let bottomMessageLabelText = dataSource.messageBottomLabelAttributedText(for: message, at: indexPath) let messageTimestampLabelText = dataSource.messageTimestampLabelAttributedText(for: message, at: indexPath) cellTopLabel.attributedText = topCellLabelText cellBottomLabel.attributedText = bottomCellLabelText messageTopLabel.attributedText = topMessageLabelText messageBottomLabel.attributedText = bottomMessageLabelText messageTimestampLabel.attributedText = messageTimestampLabelText messageTimestampLabel.isHidden = !messagesCollectionView.showMessageTimestampOnSwipeLeft let selectionIcon = displayDelegate.selectionIcon(for: message, at: indexPath, in: messagesCollectionView) selectionImage.image = selectionIcon } /// Handle tap gesture on contentView and its subviews. open override func handleTapGesture(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: self) if messageContentMode == .multiSelect { let inTouch = convert(touchLocation, to: messageContainerView) delegate?.didTapCell(in: self, at: inTouch) return } switch true { case messageContainerView.frame.contains(touchLocation) && !cellContentView(canHandle: convert(touchLocation, to: messageContainerView)): let inTouch = convert(touchLocation, to: messageContainerView) if replyContainerView.frame.contains(inTouch) { delegate?.didTapRepliedMessage(in: self) } else if contentContainerView.frame.contains(inTouch) { delegate?.didTapMessage(in: self, at: inTouch) } else if reactionView.frame.contains(inTouch) { delegate?.didTapReactionView(in: self) } case avatarView.frame.contains(touchLocation): delegate?.didTapAvatar(in: self) case cellTopLabel.frame.contains(touchLocation): delegate?.didTapCellTopLabel(in: self) delegate?.didTapAnywhere() case cellBottomLabel.frame.contains(touchLocation): delegate?.didTapCellBottomLabel(in: self) delegate?.didTapAnywhere() case messageTopLabel.frame.contains(touchLocation): delegate?.didTapMessageTopLabel(in: self) delegate?.didTapAnywhere() case messageBottomLabel.frame.contains(touchLocation): delegate?.didTapMessageBottomLabel(in: self) case accessoryView.frame.contains(touchLocation): delegate?.didTapAccessoryView(in: self) case statusView.frame.contains(touchLocation): delegate?.didTapStatusView(in: self) default: delegate?.didTapBackground(in: self) delegate?.didTapAnywhere() } } open override func handleDoubleTapGesture(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: self) switch true { case messageContainerView.frame.contains(touchLocation): delegate?.didDoubleTapMessage(in: self) default: break } } open override func handleHoldGesture(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: self) switch true { case messageContainerView.frame.contains(touchLocation): if gesture.state == .began { UIView.animate(withDuration: 0.25) { self.messageContainerView.transform = CGAffineTransform(scaleX: 0.88, y: 0.88) self.editIconImage.transform = CGAffineTransform(scaleX: 0.88, y: 0.88) } completion: { (done) in self.delegate?.didHoldMessage(in: self, at: touchLocation) UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.4, options: [.allowUserInteraction]) { self.messageContainerView.transform = .identity self.editIconImage.transform = .identity } } } else { return } default: break } } @objc open override func handlePanGesture(_ gesture: UIGestureRecognizer) { guard let panGesture = gesture as? UIPanGestureRecognizer else { return } switch panGesture.state { case .began: startAnimation = true isAvailableGesture = false safePanWork = messageContainerView.frame.contains(gesture.location(in: self)) contentView.addSubview(replyIconImage) if presentMessage.isOwner { NSLayoutConstraint.activate([ replyIconImage.trailingAnchor.constraint(equalTo: messageContainerView.trailingAnchor, constant: 30), replyIconImage.widthAnchor.constraint(equalToConstant: 30), replyIconImage.heightAnchor.constraint(equalToConstant: 30), replyIconImage.centerYAnchor.constraint(equalTo: messageContainerView.centerYAnchor) ]) } else { NSLayoutConstraint.activate([ replyIconImage.leadingAnchor.constraint(equalTo: messageContainerView.leadingAnchor, constant: -30), replyIconImage.widthAnchor.constraint(equalToConstant: 30), replyIconImage.heightAnchor.constraint(equalToConstant: 30), replyIconImage.centerYAnchor.constraint(equalTo: messageContainerView.centerYAnchor) ]) } replyIconImage.alpha = 0 replyIconImage.isHidden = true case .changed: if !safePanWork { return } let translation = panGesture.translation(in: messageContainerView) if presentMessage.isOwner { if translation.x < 0 { self.messageContainerView.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.editIconImage.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.accessoryView.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.replyIconImage.transform = CGAffineTransform(translationX: max(-40, translation.x * 0.3), y: 0).scaledBy(x: min(1.0, (abs(translation.x * 0.3)) / 40), y: min(1.0, (abs(translation.x * 0.3)) / 40)) if abs(translation.x) >= 120 { if startAnimation { isAvailableGesture = true UIImpactFeedbackGenerator(style: .heavy).impactOccurred() startAnimation = false } } else { if abs(translation.x) >= 60 { replyIconImage.alpha = (min(120, abs(translation.x)) - 60) / 60 replyIconImage.isHidden = false } else { replyIconImage.isHidden = true replyIconImage.alpha = 0 } startAnimation = true isAvailableGesture = false } } } else { if translation.x > 0 { self.messageContainerView.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.editIconImage.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.accessoryView.transform = CGAffineTransform(translationX: translation.x * 0.4, y: 0) self.replyIconImage.transform = CGAffineTransform(translationX: min(40, translation.x * 0.3), y: 0).scaledBy(x: min(1.0, (abs(translation.x * 0.3)) / 40), y: min(1.0, (abs(translation.x * 0.3)) / 40)) if abs(translation.x) >= 120 { if startAnimation { isAvailableGesture = true UIImpactFeedbackGenerator(style: .heavy).impactOccurred() startAnimation = false } } else { if abs(translation.x) >= 60 { replyIconImage.alpha = (min(120, abs(translation.x)) - 60) / 60 replyIconImage.isHidden = false } else { replyIconImage.isHidden = true replyIconImage.alpha = 0 } startAnimation = true isAvailableGesture = false } } } case .ended: if !safePanWork { return } if isAvailableGesture { delegate?.didSwipeMessage(in: self) } UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.3, options: [.allowUserInteraction]) { self.messageContainerView.transform = .identity self.editIconImage.transform = .identity self.accessoryView.transform = .identity self.replyIconImage.transform = .identity self.replyIconImage.alpha = 0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.replyIconImage.isHidden = true self.replyIconImage.removeFromSuperview() } } completion: { (ok) in } default: break } } /// Handle pan gesture, return true when gestureRecognizer's touch point in `ContentView`'s frame open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer.isKind(of: UIPanGestureRecognizer.self), let panGesture = gestureRecognizer as? UIPanGestureRecognizer else { return false } let touchLocation = panGesture.location(in: self) if messageContainerView.frame.contains(touchLocation) { let translation = panGesture.translation(in: self.messageContainerView) if (abs(translation.x) > abs(translation.y)) { return true } else { return false } } else { return false } } /// Handle `ContentView`'s tap gesture, return false when `ContentView` doesn't needs to handle gesture open func cellContentView(canHandle touchPoint: CGPoint) -> Bool { return false } // MARK: - Origin Calculations /// Positions the cell's `AvatarView`. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutAvatarView(with attributes: MessagesCollectionViewLayoutAttributes) { var origin: CGPoint = .zero let padding = attributes.avatarLeadingTrailingPadding let reactionSize = attributes.messageReaction ? attributes.reactionViewSize : .zero let reactionHeight = reactionSize.height > 0 ? reactionSize.height - attributes.reactionViewTopMargin : 0 let selectionImageSize = attributes.messageSelectionImageSize let selectionImageWidth = selectionImageSize.width > 0 ? selectionImageSize.width + attributes.selectionImageLeadingMargin + attributes.selectionImageTrailingMargin : 0 switch attributes.avatarPosition.horizontal { case .cellLeading: origin.x = padding + selectionImageWidth case .cellTrailing: origin.x = attributes.frame.width - attributes.avatarSize.width - padding case .natural: fatalError(MessageKitError.avatarPositionUnresolved) } switch attributes.avatarPosition.vertical { case .messageLabelTop: origin.y = messageTopLabel.frame.minY case .messageTop: // Needs messageContainerView frame to be set origin.y = messageContainerView.frame.minY case .messageBottom: // Needs messageContainerView frame to be set origin.y = (messageContainerView.frame.maxY - reactionHeight) - attributes.avatarSize.height case .messageCenter: // Needs messageContainerView frame to be set origin.y = messageContainerView.frame.midY - (attributes.avatarSize.height/2) case .cellBottom: origin.y = attributes.frame.height - attributes.avatarSize.height default: break } avatarView.frame = CGRect(origin: origin, size: attributes.avatarSize) } /// Positions the cell's `MessageContainerView`. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutMessageContainerView(with attributes: MessagesCollectionViewLayoutAttributes) { var origin: CGPoint = .zero let containerSize = attributes.messageContainerSize let replySize = attributes.messageReplied ? attributes.messageReplyContainerSize : .zero let replyHeight = replySize.height > 0 ? replySize.height - attributes.messageReplyContainerMargin : 0 let reactionSize = attributes.messageReaction ? attributes.reactionViewSize : .zero let reactionHeight = reactionSize.height > 0 ? reactionSize.height - attributes.reactionViewTopMargin : 0 let selectionImageSize = attributes.messageSelectionImageSize let selectionImageWidth = attributes.messageSelectionImageSize.width > 0 ? attributes.messageSelectionImageSize.width + attributes.selectionImageLeadingMargin + attributes.selectionImageTrailingMargin : 0 switch attributes.avatarPosition.vertical { case .messageBottom: origin.y = attributes.size.height - attributes.messageContainerPadding.bottom - attributes.cellBottomLabelSize.height - attributes.messageBottomLabelSize.height - containerSize.height - attributes.messageContainerPadding.top - reactionHeight - attributes.statusViewSize.height - replyHeight case .messageCenter: if attributes.avatarSize.height > containerSize.height { let messageHeight = containerSize.height + attributes.messageContainerPadding.vertical origin.y = (attributes.size.height / 2) - (messageHeight / 2) } else { fallthrough } default: if attributes.accessoryViewSize.height > containerSize.height { let messageHeight = containerSize.height + attributes.messageContainerPadding.vertical origin.y = (attributes.size.height / 2) - (messageHeight / 2) } else { origin.y = attributes.cellTopLabelSize.height + attributes.messageTopLabelSize.height + attributes.messageContainerPadding.top } } let avatarPadding = attributes.avatarLeadingTrailingPadding let widthContainerView = max(containerSize.width, reactionSize.width + attributes.reactionViewLeadingMargin + attributes.reactionViewTrailingMargin, replySize.width) - selectionImageWidth switch attributes.avatarPosition.horizontal { case .cellLeading: origin.x = selectionImageWidth + attributes.avatarSize.width + attributes.messageContainerPadding.left + avatarPadding replyContainerView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: replySize) contentContainerView.frame = CGRect(x: 0, y: replyHeight, width: containerSize.width, height: containerSize.height) case .cellTrailing: origin.x = attributes.frame.width - attributes.avatarSize.width - widthContainerView - attributes.messageContainerPadding.right - avatarPadding replyContainerView.frame = CGRect(origin: CGPoint(x: widthContainerView - replySize.width, y: 0), size: replySize) contentContainerView.frame = CGRect(origin: CGPoint(x: widthContainerView - containerSize.width, y: replyHeight), size: containerSize) case .natural: fatalError(MessageKitError.avatarPositionUnresolved) } messageContainerView.frame = CGRect(origin: origin, size: CGSize(width: widthContainerView, height: containerSize.height + replyHeight + reactionHeight)) } open func layoutEditIcon(with attributes: MessagesCollectionViewLayoutAttributes) { if attributes.messageEditedStatus { editIconImage.setImage(attributes.editImageIcon, for: .normal) editIconImage.isHidden = false var origin: CGPoint = .zero let frame = messageContainerView.convert(contentContainerView.frame, to: contentView) let size = attributes.editIconSize if attributes.messageReplied { origin.y = frame.maxY - size.width } else { origin.y = frame.minY + (frame.height / 2) - (size.width / 2) } switch attributes.avatarPosition.horizontal { case .cellLeading: origin.x = frame.maxX + 8 case .cellTrailing: origin.x = frame.minX - 8 - size.width default: break } editIconImage.frame = CGRect(origin: origin, size: size) } else { editIconImage.frame = .zero editIconImage.isHidden = true } } /// Positions the cell's reaction view. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutReactionView(with attributes: MessagesCollectionViewLayoutAttributes) { let isReaction = attributes.messageReaction if !isReaction { reactionView.frame = .zero reactionView.isHidden = true contentContainerView.uncut() } else { var origin: CGPoint = .zero let reactionSize = attributes.reactionViewSize reactionView.isHidden = false origin.y = contentContainerView.frame.maxY - attributes.reactionViewTopMargin let messageContainterWidth = contentContainerView.frame.width switch attributes.avatarPosition.horizontal { case .cellLeading: if reactionSize.width > messageContainterWidth - attributes.reactionViewLeadingMargin - attributes.reactionViewTrailingMargin { origin.x = contentContainerView.frame.minX + attributes.reactionViewLeadingMargin } else { origin.x = contentContainerView.frame.maxX - attributes.reactionViewTrailingMargin - reactionSize.width } case .cellTrailing: if reactionSize.width > messageContainterWidth - attributes.reactionViewLeadingMargin - attributes.reactionViewTrailingMargin { origin.x = contentContainerView.frame.maxX - attributes.reactionViewTrailingMargin - reactionSize.width } else { origin.x = contentContainerView.frame.minX + attributes.reactionViewLeadingMargin } default: fatalError(MessageKitError.avatarPositionUnresolved) } reactionView.frame = CGRect(origin: origin, size: reactionSize) reactionView.layer.cornerRadius = reactionView.frame.height / 2 reactionView.clipsToBounds = true contentContainerView.cut(by: reactionView, margin: 3) } } /// Positions the cell's status view. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutStatusView(with attributes: MessagesCollectionViewLayoutAttributes) { var origin = CGPoint.zero origin.x = attributes.statusViewPadding.left origin.y = messageContainerView.frame.maxY + attributes.messageContainerPadding.bottom statusView.frame = CGRect(origin: origin, size: attributes.statusViewSize) } /// Positions the cell's top label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutCellTopLabel(with attributes: MessagesCollectionViewLayoutAttributes) { cellTopLabel.textAlignment = attributes.cellTopLabelAlignment.textAlignment cellTopLabel.textInsets = attributes.cellTopLabelAlignment.textInsets cellTopLabel.frame = CGRect(origin: CGPoint(x: bounds.midX - attributes.cellTopLabelSize.width / 2, y: 0), size: attributes.cellTopLabelSize) sparateTopLine.frame = CGRect(x: 16, y: attributes.cellTopLabelSize.height / 2 - 0.25, width: bounds.maxX - 32, height: 0.5) sparateTopLine.isHidden = true } /// Positions the cell's bottom label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutCellBottomLabel(with attributes: MessagesCollectionViewLayoutAttributes) { cellBottomLabel.textAlignment = attributes.cellBottomLabelAlignment.textAlignment cellBottomLabel.textInsets = attributes.cellBottomLabelAlignment.textInsets let y = messageBottomLabel.frame.maxY let origin = CGPoint(x: 0, y: y) cellBottomLabel.frame = CGRect(origin: origin, size: attributes.cellBottomLabelSize) } /// Positions the message bubble's top label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutMessageTopLabel(with attributes: MessagesCollectionViewLayoutAttributes) { messageTopLabel.textAlignment = attributes.messageTopLabelAlignment.textAlignment messageTopLabel.textInsets = attributes.messageTopLabelAlignment.textInsets let y = messageContainerView.frame.minY - attributes.messageContainerPadding.top - attributes.messageTopLabelSize.height let origin = CGPoint(x: 0, y: y) messageTopLabel.frame = CGRect(origin: origin, size: attributes.messageTopLabelSize) } /// Positions the message bubble's bottom label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutMessageBottomLabel(with attributes: MessagesCollectionViewLayoutAttributes) { messageBottomLabel.textAlignment = attributes.messageBottomLabelAlignment.textAlignment messageBottomLabel.textInsets = attributes.messageBottomLabelAlignment.textInsets let y = statusView.frame.maxY let origin = CGPoint(x: 0, y: y) messageBottomLabel.frame = CGRect(origin: origin, size: attributes.messageBottomLabelSize) } /// Positions the cell's accessory view. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutAccessoryView(with attributes: MessagesCollectionViewLayoutAttributes) { var origin: CGPoint = .zero let frame = messageContainerView.convert(contentContainerView.frame, to: contentView) // Accessory view is set at the side space of the messageContainerView switch attributes.accessoryViewPosition { case .messageLabelTop: origin.y = messageTopLabel.frame.minY case .messageTop: origin.y = frame.minY case .messageBottom: origin.y = frame.maxY - attributes.accessoryViewSize.height case .messageCenter: origin.y = frame.midY - (attributes.accessoryViewSize.height / 2) case .cellBottom: origin.y = attributes.frame.height - attributes.accessoryViewSize.height default: break } let iconEditMaxX = editIconImage.isHidden == true ? 0 : editIconImage.frame.width + 8 let iconEditMinX = editIconImage.isHidden == true ? 0 : editIconImage.frame.width + 8 // Accessory view is always on the opposite side of avatar switch attributes.avatarPosition.horizontal { case .cellLeading: origin.x = frame.maxX + attributes.accessoryViewPadding.left + iconEditMaxX case .cellTrailing: origin.x = frame.minX - attributes.accessoryViewPadding.right - attributes.accessoryViewSize.width - iconEditMinX case .natural: fatalError(MessageKitError.avatarPositionUnresolved) } accessoryView.frame = CGRect(origin: origin, size: attributes.accessoryViewSize) } /// Positions the message bubble's time label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutTimeLabelView(with attributes: MessagesCollectionViewLayoutAttributes) { let paddingLeft: CGFloat = 10 let origin = CGPoint(x: UIScreen.main.bounds.width + paddingLeft, y: contentContainerView.frame.minY + contentContainerView.frame.height * 0.5 - messageTimestampLabel.font.ascender * 0.5) let size = CGSize(width: attributes.messageTimeLabelSize.width, height: attributes.messageTimeLabelSize.height) messageTimestampLabel.frame = CGRect(origin: origin, size: size) } /// Positions the message bubble's time label. /// - attributes: The `MessagesCollectionViewLayoutAttributes` for the cell. open func layoutSelectionView(with attributes: MessagesCollectionViewLayoutAttributes) { let paddingLeft: CGFloat = attributes.selectionImageLeadingMargin let origin = CGPoint(x: paddingLeft, y: messageContainerView.frame.minY + messageContainerView.frame.height * 0.5 - attributes.messageSelectionImageSize.height * 0.5) let size = attributes.messageSelectionImageSize selectionImage.frame = CGRect(origin: origin, size: size) } open func highlightMessageContainerView(with color: UIColor) { self.contentContainerView.animateBorder(to: color, duration: 1) UIView.animate(withDuration: 0.25) { self.contentContainerView.transform = CGAffineTransform(scaleX: 0.88, y: 0.88) } completion: { (done) in UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.4, options: .allowUserInteraction) { self.contentContainerView.transform = .identity } } } }
46.823077
302
0.657905
69966f61fe4aab260cfded651429c2fef0b5e053
1,421
// // AppDelegate.swift // SwiftUIListExample // // Created by Shimaa Nagah on 11/12/19. // Copyright © 2019 Code95. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.394737
179
0.748768
0ac4907e922583bb284ff8bec7b1bd937922648c
768
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct B<T : A> { func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} struct d<f : e,e where g.h == f.h> { } } protocol a { typeal= D>(e: A.B) { } } } override func d() -> String { func} func b((Any, c))(Any, AnyObject func g<T where T.E == F>(f: B<T>) { } struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
22.588235
78
0.640625
bfc4e52a9d3601f883b637727b14604ea27ab7cc
4,055
// // AndesTextAreaView.swift // AndesUI // // Created by Nicolas Rostan Talasimov on 3/26/20. // import Foundation class AndesTextAreaView: AndesTextFieldAbstractView { @IBOutlet weak var textView: AndesUITextView! @IBOutlet weak var placeholderLabel: UILabel! override var text: String { get { return textView.text } set { textView.text = newValue textViewDidChange(textView) } } override var customInputView: UIView? { get { return textView.inputView } set (value) { textView.inputView = value } } override func loadNib() { let bundle = AndesBundle.bundle() bundle.loadNibNamed("AndesTextAreaView", owner: self, options: nil) textView.delegate = self self.textView.textContainerInset = UIEdgeInsets(top: config.paddings.top, left: config.paddings.left, bottom: config.paddings.bottom, right: config.paddings.right) textView.isScrollEnabled = false textView.clipsToBounds = false textView.onNeedsBorderUpdate = { [weak self] (view: UIView) in self?.updateBorder() } } override func updateView() { super.updateView() placeholderLabel.setAndesStyle(style: config.placeholderStyle) placeholderLabel.text = config.placeholderText placeholderLabel.isHidden = self.text.count > 0 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = config.inputTextStyle.lineSpacing self.textView.typingAttributes = [.font: config.inputTextStyle.font, .strokeColor: config.inputTextStyle.textColor, .paragraphStyle: paragraphStyle] self.textView.isUserInteractionEnabled = config.editingEnabled self.textView.textContainerInset = UIEdgeInsets(top: config.paddings.top, left: config.paddings.left, bottom: config.paddings.bottom, right: config.paddings.right) if let traits = config.textInputTraits { self.textView.setInputTraits(traits) } } } // MARK: - Utils functions for textview extension AndesTextAreaView { func sizeForText(_ txt: NSString) -> CGSize { let width = self.textView.textContainer.size.width let size = CGSize(width: width, height: .infinity) let textRect = txt.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: textView.typingAttributes, context: nil) return textRect.size } } extension AndesTextAreaView: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { self.delegate?.didBeginEditing() } func textViewDidEndEditing(_ textView: UITextView) { self.delegate?.didEndEditing(text: self.text) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { // max lines check if let maxLines = config.maxLines, maxLines > 0, let range = Range(range, in: textView.text) { let newStr = textView.text.replacingCharacters(in: range, with: text) if sizeForText(newStr as NSString).height > sizeForText(String(repeating: "\n", count: Int(maxLines - 1)) as NSString).height { return false } } return delegate?.textField(shouldChangeCharactersIn: range, replacementString: text) != false } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return delegate?.shouldBeginEditing() != false } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return delegate?.shouldEndEditing() != false } func textViewDidChangeSelection(_ textView: UITextView) { delegate?.didChangeSelection(selectedRange: textView.selectedTextRange) } func textViewDidChange(_ textView: UITextView) { self.delegate?.didChange() self.placeholderLabel.isHidden = self.text.count > 0 self.checkLengthAndUpdateCounterLabel() } }
35.884956
171
0.676695
de7c4330f16483e2929093967df15106578d6b8f
6,797
// // Copyright (c) 2020 Cristian Ortega Gómez (https://github.com/corteggo) // // 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 UIKit // MARK: - Navigation transitions public extension UIWindow { /// Transition Options struct TransitionOptions { /// Curve of animation /// /// - linear: linear /// - easeIn: ease in /// - easeOut: ease out /// - easeInOut: ease in - ease out // swiftlint:disable:next nesting missing_docs public enum Curve { /// Linear case linear /// Ease-in case easeIn /// Ease-out case easeOut /// Ease-in-out case easeInOut /// Return the media timing function associated with curve var function: CAMediaTimingFunction { let key: String! switch self { case .linear: key = CAMediaTimingFunctionName.linear.rawValue case .easeIn: key = CAMediaTimingFunctionName.easeIn.rawValue case .easeOut: key = CAMediaTimingFunctionName.easeOut.rawValue case .easeInOut: key = CAMediaTimingFunctionName.easeInEaseOut.rawValue } return CAMediaTimingFunction(name: CAMediaTimingFunctionName(rawValue: key)) } } /// Direction of the animation /// /// - fade: fade to new controller /// - toTop: slide from bottom to top /// - toBottom: slide from top to bottom /// - toLeft: pop to left /// - toRight: push to right // swiftlint:disable:next nesting missing_docs public enum Direction { /// Fade case fade /// To top case toTop /// To bottom case toBottom /// To left case toLeft /// To right case toRight /// Return the associated transition /// /// - Returns: transition func transition() -> CATransition { let transition = CATransition() transition.type = CATransitionType.push switch self { case .fade: transition.type = CATransitionType.fade transition.subtype = nil case .toLeft: transition.subtype = CATransitionSubtype.fromLeft case .toRight: transition.subtype = CATransitionSubtype.fromRight case .toTop: transition.subtype = CATransitionSubtype.fromTop case .toBottom: transition.subtype = CATransitionSubtype.fromBottom } return transition } } /// Background of the transition /// /// - solidColor: solid color /// - customView: custom view // swiftlint:disable:next nesting missing_docs public enum Background { /// Solid color case solidColor(_: UIColor) } /// Duration of the animation (default is 0.20s) public var duration: TimeInterval = 0.20 /// Direction of the transition (default is `toRight`) public var direction: TransitionOptions.Direction = .toRight /// Style of the transition (default is `linear`) public var style: TransitionOptions.Curve = .linear /// Background of the transition (default is `nil`) public var background: TransitionOptions.Background? /// Initialize a new options object with given direction and curve /// /// - Parameters: /// - direction: direction /// - style: style public init(direction: TransitionOptions.Direction = .toRight, style: TransitionOptions.Curve = .linear) { self.direction = direction self.style = style } /// Initializes a new instance public init() { } /// Return the animation to perform for given options object var animation: CATransition { let transition = self.direction.transition() transition.duration = self.duration transition.timingFunction = self.style.function return transition } } /// Change the root view controller of the window /// /// - Parameters: /// - controller: controller to set /// - options: options of the transition func setRootViewController(_ controller: UIViewController, options: TransitionOptions = TransitionOptions()) { var transitionWnd: UIWindow? if let background = options.background { transitionWnd = UIWindow(frame: UIScreen.main.bounds) switch background { case .solidColor(let color): transitionWnd?.backgroundColor = color } transitionWnd?.makeKeyAndVisible() } // Make animation self.layer.add(options.animation, forKey: kCATransition) self.rootViewController = controller self.makeKeyAndVisible() if let wnd = transitionWnd { DispatchQueue.main.asyncAfter(deadline: (.now() + 1 + options.duration), execute: { wnd.removeFromSuperview() }) } } }
36.154255
114
0.562307
08ee8047590053309b5a2a56b7af60b138aab08d
4,140
import Foundation public extension Collection where Index == Int { func sectionedDifference<ID, Item, CID>(from old: Self, identifiedBy identifier: (Element) -> ID, areEqual: (Element, Element) -> Bool, items: (Element) -> [Item], identifiedBy itemIdentifier: (Item) -> CID, areEqual areItemsEqual: (Item, Item) -> Bool) -> SectionedCollectionDiff where ID: Hashable, CID: Hashable { var removedChildren: [CID: [IndexPath]] = [:] var insertedChildren: [CID: [IndexPath]] = [:] typealias Move = CollectionDiff<Set<IndexPath>>.Move var childMoves: [Move] = [] var childUpdatesBefore: [IndexPath] = [] var childUpdatesAfter: [IndexPath] = [] let rawDiff: CollectionDiff<IndexSet> = rawDifference(from: old, identifiedBy: identifier, areEqual: areEqual) for move in rawDiff.moves { let oldElement = old[move.from] let newElement = self[move.to] let oldItems = items(oldElement) let newItems = items(newElement) let itemDiff: CollectionDiff<IndexSet> = newItems.difference(from: oldItems, identifiedBy: itemIdentifier, areEqual: areItemsEqual) for index in itemDiff.removals { removedChildren[itemIdentifier(oldItems[index]), default: []].append(IndexPath(indexes: [move.from, index])) } for index in itemDiff.insertions { insertedChildren[itemIdentifier(newItems[index]), default: []].append(IndexPath(indexes: [move.to, index])) } childMoves += itemDiff.moves.map { Move( from: IndexPath(indexes: [move.from, $0.from]), to: IndexPath(indexes: [move.to, $0.to]) ) } childUpdatesBefore += itemDiff.updatesBefore.map { IndexPath(indexes: [move.from, $0]) } childUpdatesAfter += itemDiff.updatesAfter.map { IndexPath(indexes: [move.to, $0]) } } var childRemovals: [IndexPath] = [] var childInsertions: [IndexPath] = [] for (childID, indexes) in removedChildren { for removedIndexPath in indexes { if let insertedIndexPath = insertedChildren[childID]?.popLast() { childMoves.append(Move(from: removedIndexPath, to: insertedIndexPath)) if !areItemsEqual( items(old[removedIndexPath[0]])[removedIndexPath[1]], items(self[insertedIndexPath[0]])[insertedIndexPath[1]] ) { childUpdatesBefore.append(removedIndexPath) childUpdatesAfter.append(insertedIndexPath) } } else { childRemovals.append(removedIndexPath) } } } for indexes in insertedChildren.values { childInsertions += indexes } return SectionedCollectionDiff( section: rawDiff.optimizingMoves(), item: .init( removals: Set(childRemovals), insertions: Set(childInsertions), moves: childMoves, updatesAfter: Set(childUpdatesAfter), updatesBefore: Set(childUpdatesBefore) ) ) } func sectionedDifference<ID, Item, CID, SectionValue, ItemValue>(from old: Self, identifiedBy identifier: (Element) -> ID, areEqualBy sectionValue: (Element) -> SectionValue, items: (Element) -> [Item], identifiedBy itemIdentifier: (Item) -> CID, areEqualBy itemValue: (Item) -> ItemValue) -> SectionedCollectionDiff where ID: Hashable, CID: Hashable, SectionValue: Equatable, ItemValue: Equatable { sectionedDifference( from: old, identifiedBy: identifier, areEqual: { sectionValue($0) == sectionValue($1) }, items: items, identifiedBy: itemIdentifier, areEqual: { itemValue($0) == itemValue($1) } ) } }
41.4
137
0.574396
e9815931107fd3e4a87e0570d3724ba67c2e3707
3,664
// // oneD_math.swift // swix // // Created by Scott Sievert on 6/11/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate // SLOW PARTS: almost everything // to speed up first: abs, sign, norm, rand, randn /// applies the function to every element of an array and takes only that argument. This is just a simple for-loop. If you want to use some custom fancy function, define it yourself. func apply_function(function: Double->Double, x: matrix) -> matrix{ var y = zeros(x.count) for i in 0..<x.count{ y[i] = function(x[i]) } return y } func sin(x: matrix) -> matrix{ return apply_function(sin, x) } func cos(x: matrix) -> matrix{ return apply_function(cos, x) } func tan(x: matrix) -> matrix{ return apply_function(tan, x) } /// log_e(.) func log(x: matrix) -> matrix{ var y = apply_function(log, x) return y } func abs(x: matrix) -> matrix{ return apply_function(abs, x) } func sqrt(x: matrix) -> matrix{ var y = apply_function(sqrt, x) return y } func round(x: matrix) -> matrix{ return apply_function(round, x) } func floor(x: matrix) -> matrix{ var y = apply_function(floor, x) return y } func ceil(x: matrix) -> matrix{ var y = apply_function(ceil, x) return y } func sign(x: Double) -> Double{ if x < 0{ return -1 } else{ return 1 } } func sign(x: matrix)->matrix{ return apply_function(sign, x) } func pow(x: matrix, power: Double) -> matrix{ var y = zeros(x.count) for i in 0..<x.count{ y[i] = pow(x[i], power) } return y } func sum(x: matrix) -> Double{ var y = zeros(x.count) var s: Double = 0 for i in 0..<x.count{ s = x[i] + s } return s } func avg(x: matrix) -> Double{ var y: Double = sum(x) return y / x.count.double } func std(x: matrix) -> Double{ var y: Double = avg(x) var z = x - y return sqrt(sum(pow(z, 2) / x.count.double)) } /// variance used since var is a keyword func variance(x: matrix) -> Double{ var y: Double = avg(x) var z = x - y return sum(pow(z, 2) / x.count.double) } func norm(x: matrix, type:String="l2") -> Double{ if type=="l2"{ return sqrt(sum(pow(x, 2)))} if type=="l1"{ return sum(abs(x))} if type=="l0"{ var count = 0.0 for i in 0..<x.n{ if x[i] != 0{ count += 1 } } return count } assert(false, "type of norm unrecongnized") return -1.0 } func cumsum(x: matrix) -> matrix{ let N = x.count var y = zeros(N) for i in 0..<N{ if i==0 { y[i] = x[0] } else if i==1 { y[i] = x[0] + x[1] } else { y[i] = x[i] + y[i-1] } } return y } func rand() -> Double{ return Double(arc4random()) / pow(2, 32) } func rand(N: Int) -> matrix{ var x = zeros(N) for i in 0..<N{ x[i] = rand() } return x } func randn() -> Double{ var u:Double = rand() var v:Double = rand() var x = sqrt(-2*log(u))*cos(2*pi*v); return x } func randn(N: Int, mean: Double=0, sigma: Double=1) -> matrix{ var x = zeros(N) for i in 0..<N{ x[i] = randn() } var y = (x * sigma) + mean; return y } func min(x: matrix, absValue:Bool=false) -> Double{ // absValue not implemeted yet var min = inf var xP = matrixToPointer(x) var minC = min_objc(xP, x.n.cint) return minC } func max(x: matrix, absValue:Bool=false) -> Double{ // absValue not implemeted yet var xP = matrixToPointer(x) var maxC = max_objc(xP, x.n.cint); return maxC }
21.552941
182
0.562227
1d03143f6e61f11e87fceafed551dd2222cd3daf
177
// // MovieCell.swift // MovieApp // // Created by Kerim Caglar on 1.05.2021. // import UIKit protocol MovieCell: UICollectionViewCell { func showMovie(movie:Movie?) }
13.615385
42
0.689266
38431f5e2941990c00e927f926c1f271211bab6d
5,184
//: Playground - noun: a place where people can play internal enum OperatorAssociativity { case leftAssociative case rightAssociative } public enum OperatorType: CustomStringConvertible { case add case subtract case divide case multiply case percent case exponent public var description: String { switch self { case .add: return "+" case .subtract: return "-" case .divide: return "/" case .multiply: return "*" case .percent: return "%" case .exponent: return "^" } } } public enum TokenType: CustomStringConvertible { case openBracket case closeBracket case Operator(OperatorToken) case operand(Double) public var description: String { switch self { case .openBracket: return "(" case .closeBracket: return ")" case .Operator(let operatorToken): return operatorToken.description case .operand(let value): return "\(value)" } } } public struct OperatorToken: CustomStringConvertible { let operatorType: OperatorType init(operatorType: OperatorType) { self.operatorType = operatorType } var precedence: Int { switch operatorType { case .add, .subtract: return 0 case .divide, .multiply, .percent: return 5 case .exponent: return 10 } } var associativity: OperatorAssociativity { switch operatorType { case .add, .subtract, .divide, .multiply, .percent: return .leftAssociative case .exponent: return .rightAssociative } } public var description: String { return operatorType.description } } func <= (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence <= right.precedence } func < (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence < right.precedence } public struct Token: CustomStringConvertible { let tokenType: TokenType init(tokenType: TokenType) { self.tokenType = tokenType } init(operand: Double) { tokenType = .operand(operand) } init(operatorType: OperatorType) { tokenType = .Operator(OperatorToken(operatorType: operatorType)) } var isOpenBracket: Bool { switch tokenType { case .openBracket: return true default: return false } } var isOperator: Bool { switch tokenType { case .Operator(_): return true default: return false } } var operatorToken: OperatorToken? { switch tokenType { case .Operator(let operatorToken): return operatorToken default: return nil } } public var description: String { return tokenType.description } } public class InfixExpressionBuilder { private var expression = [Token]() public func addOperator(_ operatorType: OperatorType) -> InfixExpressionBuilder { expression.append(Token(operatorType: operatorType)) return self } public func addOperand(_ operand: Double) -> InfixExpressionBuilder { expression.append(Token(operand: operand)) return self } public func addOpenBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .openBracket)) return self } public func addCloseBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .closeBracket)) return self } public func build() -> [Token] { // Maybe do some validation here return expression } } // This returns the result of the shunting yard algorithm public func reversePolishNotation(_ expression: [Token]) -> String { var tokenStack = Stack<Token>() var reversePolishNotation = [Token]() for token in expression { switch token.tokenType { case .operand(_): reversePolishNotation.append(token) case .openBracket: tokenStack.push(token) case .closeBracket: while tokenStack.count > 0, let tempToken = tokenStack.pop(), !tempToken.isOpenBracket { reversePolishNotation.append(tempToken) } case .Operator(let operatorToken): for tempToken in tokenStack.makeIterator() { if !tempToken.isOperator { break } if let tempOperatorToken = tempToken.operatorToken { if operatorToken.associativity == .leftAssociative && operatorToken <= tempOperatorToken || operatorToken.associativity == .rightAssociative && operatorToken < tempOperatorToken { reversePolishNotation.append(tokenStack.pop()!) } else { break } } } tokenStack.push(token) } } while tokenStack.count > 0 { reversePolishNotation.append(tokenStack.pop()!) } return reversePolishNotation.map({token in token.description}).joined(separator: " ") } // Simple demo let expr = InfixExpressionBuilder() .addOperand(3) .addOperator(.add) .addOperand(4) .addOperator(.multiply) .addOperand(2) .addOperator(.divide) .addOpenBracket() .addOperand(1) .addOperator(.subtract) .addOperand(5) .addCloseBracket() .addOperator(.exponent) .addOperand(2) .addOperator(.exponent) .addOperand(3) .build() print(expr.description) print(reversePolishNotation(expr))
21.873418
102
0.671489
c14c227f6f9c5577c8b67984b61cf8265c11d61a
7,875
// // Tests.swift // BetterSegmentedControl // // Created by George Marmaridis on 23/04/16. // Copyright © 2016 George Marmaridis. All rights reserved. // import Quick import Nimble @testable import BetterSegmentedControl class BetterSegmentedControlSpec: QuickSpec { override func spec() { describe("a BetterSegmentedControl") { context("after it is initialized") { context("using the designated initializer") { var control: BetterSegmentedControl! beforeEach({ control = BetterSegmentedControl( frame: CGRect(x: 0, y: 0, width: 300, height: 44), titles: ["One","Two"], index: 1, options: [.backgroundColor(.red), .titleColor(.blue), .indicatorViewBackgroundColor(.green), .selectedTitleColor(.purple), .bouncesOnChange(false), .alwaysAnnouncesValue(true), .announcesValueImmediately(true), .panningDisabled(true), .cornerRadius(10.0), .indicatorViewInset(4.0), .indicatorViewBorderWidth(2.0), .indicatorViewBorderColor(.red),.titleFont(UIFont(name: "HelveticaNeue-Light", size: 14.0)!), .selectedTitleFont(UIFont(name: "HelveticaNeue-Light", size: 14.0)!), .titleBorderWidth(2.0), .titleBorderColor(UIColor.red)]) }) it("has the frame passed", closure: { expect(control.frame.equalTo(CGRect(x: 0, y: 0, width: 300, height: 44))).to(beTrue()) }) it("has the index passed", closure: { expect(control.index) == 1 }) it("has the titles passed", closure: { expect(control.titles) == ["One","Two"] }) it("has the background color passed", closure: { expect(control.backgroundColor).to(equal(UIColor.red)) }) it("has the title color passed", closure: { expect(control.titleColor).to(equal(UIColor.blue)) }) it("has the indicator view background color passed", closure: { expect(control.indicatorViewBackgroundColor).to(equal(UIColor.green)) }) it("has the selected title color passed", closure: { expect(control.selectedTitleColor).to(equal(UIColor.purple)) }) it("doesn't bounce on change", closure: { expect(control.bouncesOnChange).to(beFalse()) }) it("can always announces its value on change", closure: { expect(control.alwaysAnnouncesValue).to(beTrue()) }) it("announces value immediately", closure: { expect(control.announcesValueImmediately).to(beTrue()) }) it("has panning disabled", closure: { expect(control.panningDisabled).to(beTrue()) }) it("has the corner radius passed in init", closure: { expect(control.cornerRadius).to(equal(10.0)) }) it("has the indicator view insets passed in init", closure: { expect(control.indicatorViewInset).to(equal(4.0)) }) it("has the indicator view border width passed in init", closure: { expect(control.indicatorViewBorderWidth).to(equal(2.0)) }) it("has the indicator view border color passed in init", closure: { expect(control.indicatorViewBorderColor).to(equal(UIColor.red)) }) it("has the custom title font passed in init", closure: { expect(control.titleFont).to(equal(UIFont(name: "HelveticaNeue-Light", size: 14.0)!)) }) it("has the custom selected title font passed in init", closure: { expect(control.selectedTitleFont).to(equal(UIFont(name: "HelveticaNeue-Light", size: 14.0)!)) }) it("has the title border width passed in init", closure: { expect(control.titleBorderWidth).to(equal(2.0)) }) context("when a subview is added to its indicator") { var underlineView: UIView! beforeEach({ underlineView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) control.addSubviewToIndicator(underlineView) }) it("has has a superview", closure: { expect(underlineView.superview).toNot(beNil()) }) } } context("using initWithCoder") { var control: BetterSegmentedControl! beforeEach({ let storyboard = UIStoryboard(name: "Test", bundle: Bundle(for: type(of: self))) let viewController = storyboard.instantiateInitialViewController() as! TestViewController UIApplication.shared.keyWindow!.rootViewController = viewController expect(viewController).toNot(beNil()) expect(viewController.view).toNot(beNil()) control = viewController.control }) it("is not nil", closure: { expect(control).toNot(beNil()) }) it("has the frame set in IB", closure: { expect(control.frame.equalTo(CGRect(x: 10, y: 30, width: 480, height: 40))).to(beTrue()) }) it("has the default index 0", closure: { expect(control.index) == 0 }) it("has the default titles 'First, Second'", closure: { expect(control.titles) == ["First", "Second"] }) it("has the background color set in IB", closure: { expect(control.backgroundColor).to(equal(UIColor(red: 0, green: 0, blue: 0, alpha: 1))) }) it("has the title color set in IB", closure: { expect(control.titleColor).to(equal(UIColor(red: 1, green: 1, blue: 1, alpha: 1))) }) it("has the indicator view background color set in IB", closure: { expect(control.indicatorViewBackgroundColor).to(equal(UIColor(red: 1, green: 1, blue: 1, alpha: 1))) }) it("has the selected title color set in IB", closure: { expect(control.selectedTitleColor).to(equal(UIColor(red: 0, green: 0, blue: 0, alpha: 1))) }) } } } } }
53.938356
131
0.457016
f4bc001a6d46b1f30da9c1b98f7721ed2fc52206
522
// // Vertex.swift // international-business-example // // Created by Jorge Poveda on 23/9/21. // import Foundation public struct Vertex<T: Hashable> { var data: T } extension Vertex: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(data) } static public func ==(lhs: Vertex, rhs: Vertex) -> Bool { // 2 return lhs.data == rhs.data } } extension Vertex: CustomStringConvertible { public var description: String { return "\(data)" } }
17.4
66
0.622605
f47f1fb21f19c2cce13adbb3b1dee3c3cab0e116
6,372
/// HTTPClient.swift /// iCombineNetwork /// /// - author: Leon Nguyen /// - date: 28/8/21 /// import iCombine import Foundation /// Manage HTTP requests open class HTTPClient: HTTPClientType { private let networkConnectionManager: NetworkConnectionManagerType private let session: URLSession /// Intiialize the client /// /// - Parameters: /// - session: The URLSession configured, including SSL pinning /// - networkConnectionManager: The network connection status manager public init(session: URLSession = URLSession.shared, networkConnectionManager: NetworkConnectionManagerType = NetworkConnectionManager()) { self.networkConnectionManager = networkConnectionManager self.session = session } public func requestObject<Object: Decodable>( with request: URLRequest, promoting businessErrorTypes: [BusinessError.Type] = []) -> AnyPublisher<Object?, HTTPError> { guard networkConnectionManager.isConnected else { return Fail<Object?, HTTPError>(error: .network(.connection)) .eraseToAnyPublisher() } return session.dataTaskPublisher(for: request) .mapNetworkError() .catchBusinessError(businessErrorTypes) .catchServerError() .decodeObject() } public func requestObjects<Object: Decodable>( with request: URLRequest, promoting businessErrorTypes: [BusinessError.Type] = []) -> AnyPublisher<[Object]?, HTTPError> { guard networkConnectionManager.isConnected else { return Fail<[Object]?, HTTPError>(error: .network(.connection)) .eraseToAnyPublisher() } return session.dataTaskPublisher(for: request) .mapNetworkError() .catchBusinessError(businessErrorTypes) .catchServerError() .decodeObjects() } public func requestData(with request: URLRequest) -> AnyPublisher<Data?, HTTPError> { guard networkConnectionManager.isConnected else { return Fail<Data?, HTTPError>(error: .network(.connection)) .eraseToAnyPublisher() } return session.dataTaskPublisher(for: request) .mapNetworkError() .catchServerError() .map { $0.data } .eraseToAnyPublisher() } public func requestObject<Object: Decodable>( from url: URL, using method: RequestMethod, attaching header: RequestHeader? = nil, attaching parameters: URLParameters? = nil, with body: RequestBody? = nil, as bodyType: RequestBodyType? = nil, promoting businessErrorTypes: [BusinessError.Type] = []) -> AnyPublisher<Object?, HTTPError> { do { let request = try self.request(from: url, using: method, attaching: header, attaching: parameters, with: body, as: bodyType) return requestObject(with: request, promoting: businessErrorTypes) } catch HTTPError.encoding { return Fail<Object?, HTTPError>(error: .encoding) .eraseToAnyPublisher() } catch HTTPError.url { return Fail<Object?, HTTPError>(error: .url) .eraseToAnyPublisher() } catch { return Fail<Object?, HTTPError>(error: .unknown) .eraseToAnyPublisher() } } public func requestObjects<Object: Decodable>( from url: URL, using method: RequestMethod, attaching header: RequestHeader? = nil, attaching parameters: URLParameters? = nil, with body: RequestBody? = nil, as bodyType: RequestBodyType? = nil, promoting businessErrorTypes: [BusinessError.Type] = []) -> AnyPublisher<[Object]?, HTTPError> { do { let request = try self.request(from: url, using: method, attaching: header, attaching: parameters, with: body, as: bodyType) return requestObjects(with: request, promoting: businessErrorTypes) } catch HTTPError.encoding { return Fail<[Object]?, HTTPError>(error: .encoding) .eraseToAnyPublisher() } catch HTTPError.url { return Fail<[Object]?, HTTPError>(error: .url) .eraseToAnyPublisher() } catch { return Fail<[Object]?, HTTPError>(error: .unknown) .eraseToAnyPublisher() } } public func requestData( from url: URL, using method: RequestMethod, attaching header: RequestHeader?, attaching parameters: URLParameters?, with body: RequestBody?, as bodyType: RequestBodyType?) -> AnyPublisher<Data?, HTTPError> { do { let request = try self.request(from: url, using: method, attaching: header, attaching: parameters, with: body, as: bodyType) return requestData(with: request) } catch HTTPError.url { return Fail<Data?, HTTPError>(error: .url) .eraseToAnyPublisher() } catch { return Fail<Data?, HTTPError>(error: .unknown) .eraseToAnyPublisher() } } private func request(from url: URL, using method: RequestMethod, attaching header: RequestHeader?, attaching parameters: URLParameters?, with body: RequestBody?, as bodyType: RequestBodyType?) throws -> URLRequest { var request = URLRequest(url: url) request.httpMethod = method.rawValue request.allHTTPHeaderFields = header if let parameters = parameters { guard let url = url.attaching(parameters) else { throw HTTPError.url } request.url = url } if let body = body, let bodyType = bodyType { request.allHTTPHeaderFields?["Content-Type"] = bodyType.contentType guard let data = body.data(as: bodyType) else { throw HTTPError.encoding } request.httpBody = data } return request } } /// The response type of a HTTP request public typealias DataTaskResponse = URLSession.CombineDataTaskPublisher.Output
37.928571
136
0.604049
e2118f297635f3c5c342f54bf2a1815dd381171a
5,819
// // SubGridSpecificationViewController.swift // gribParserTest // // Created by Bo Gustafsson on 2019-01-11. // Copyright © 2019 Bo Gustafsson. All rights reserved. // import Cocoa protocol SubGridSpecificationDelegate { var swCornerPoint : Point? {get set} var neCornerPoint : Point? {get set} var iSkip : Int? {get set} var jSkip : Int? {get set} } class SubGridSpecificationViewController: NSViewController { @IBOutlet weak private var swLonTextField: NSTextField? { didSet { if let x = swLon { swLonTextField?.cell?.title = String(x) } else { swLonTextField?.cell?.title = "" } } } @IBOutlet weak private var swLatTextField: NSTextField? { didSet { if let x = swLat { swLatTextField?.cell?.title = String(x) } else { swLatTextField?.cell?.title = "" } } } @IBOutlet weak private var neLonTextField: NSTextField? { didSet { if let x = neLon { neLonTextField?.cell?.title = String(x) } else { neLonTextField?.cell?.title = "" } } } @IBOutlet weak private var neLatTextField: NSTextField? { didSet { if let x = neLat { neLatTextField?.cell?.title = String(x) } else { neLatTextField?.cell?.title = "" } } } @IBOutlet weak private var iSkipTextField: NSTextField? { didSet { if let i = iSkip { iSkipTextField?.cell?.title = String(i) } else { iSkipTextField?.cell?.title = "" } } } @IBOutlet weak private var jSkipTextField: NSTextField? { didSet { if let j = jSkip { jSkipTextField?.cell?.title = String(j) } else { jSkipTextField?.cell?.title = "" } } } var delegate: SubGridSpecificationDelegate? var swLon : Double? { didSet { if let x = swLon { swLonTextField?.cell?.title = String(x) } else { swLonTextField?.cell?.title = "" } } } var swLat : Double? { didSet { if let x = swLat { swLatTextField?.cell?.title = String(x) } else { swLatTextField?.cell?.title = "" } } } var neLon : Double? { didSet { if let x = neLon { neLonTextField?.cell?.title = String(x) } else { neLonTextField?.cell?.title = "" } } } var neLat : Double? { didSet { if let x = neLat { neLatTextField?.cell?.title = String(x) } else { neLatTextField?.cell?.title = "" } } } var iSkip : Int? { didSet { if let i = iSkip { iSkipTextField?.cell?.title = String(i) } else { iSkipTextField?.cell?.title = "" } } } var jSkip : Int? { didSet { if let j = jSkip { jSkipTextField?.cell?.title = String(j) } else { jSkipTextField?.cell?.title = "" } } } @IBAction private func newNumber(_ sender: NSTextField) { if let title = sender.cell?.title, let x = Double(title) { switch sender { case swLonTextField!: swLon = x case swLatTextField!: swLat = x case neLonTextField!: neLon = x case neLatTextField!: neLat = x case iSkipTextField!: iSkip = Int(x) _ = test() case jSkipTextField!: jSkip = Int(x) _ = test() default: break } } } private func test() -> Bool { if let swL = swLat, let neL = neLat, neL <= swL {return false} if let swL = swLon, let neL = neLon, neL <= swL {return false} if let i = iSkip, i <= 0 { iSkip = nil return false } if let i = jSkip, i <= 0 { jSkip = nil return false } return true } @IBAction private func done(_ sender: NSButton) { if test() { if let lat = swLat, let lon = swLon { delegate?.swCornerPoint = Point(id: 1, lon: lon, lat: lat) } else { delegate?.swCornerPoint = nil } if let lat = neLat, let lon = neLon { delegate?.neCornerPoint = Point(id: 1, lon: lon, lat: lat) } else { delegate?.neCornerPoint = nil } if let iS = iSkip { delegate?.iSkip = iS } else { delegate?.iSkip = nil } if let jS = jSkip { delegate?.jSkip = jS } else { delegate?.jSkip = nil } self.presentingViewController?.dismiss(self) } } @IBAction private func cancel(_ sender: NSButton) { self.presentingViewController?.dismiss(self) } @IBAction private func reset(_ sender: NSButton) { swLon = nil swLat = nil neLon = nil neLat = nil iSkip = nil jSkip = nil } override func viewWillAppear() { super.viewWillAppear() view.window?.title = "Output grid dimensions" } }
27.065116
74
0.456608
f46c78d87d23b6140233729a56d3f58785776aaa
757
// // _HTMLRepresentable.swift // Timetable-SDK-Swift // // Created by Sergej Jaskiewicz on 25.09.16. // // import Foundation import Scrape internal protocol _HTMLRepresentable { var _html: String? { get set } var _page: HTMLDocument? { get set } } internal extension _HTMLRepresentable { internal mutating func getHTML(for url: URL) throws { _html = try String(contentsOf: url, encoding: .utf8) } internal mutating func parseHTML() throws { guard let html = _html else { throw FetchingError.parseError } if let document = HTMLDocument(html: html, encoding: .utf8) { _page = document } else { throw FetchingError.parseError } } }
21.628571
70
0.622193
ed3a3b25489ffadaadefebcdaa0a901d117016d1
971
// // ExampleTests.swift // ExampleTests // // Created by Victor on 04/11/2016. // Copyright © 2016 Victor Rodriguez. All rights reserved. // import XCTest @testable import Example class ExampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.243243
111
0.633368
1cdc978d53e77c2591fb9650829fb8c602e67d07
291
// // Array+SafeSubscript.swift // K9 Recipes // // Created by Orkhan Huseynov on 9/7/19. // Copyright © 2019 Orkhan Huseynov. All rights reserved. // extension Array { subscript (safe index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil } }
20.785714
62
0.621993
33d800150a4aa050d538e78fe3a6da99bb8a2e45
15,277
// // KSYRecordVC.swift // KSYLiveDemo_Swift // // Created by iVermisseDich on 2017/1/23. // Copyright © 2017年 com.ksyun. All rights reserved. // import UIKit class KSYRecordVC: UIViewController { var url: URL! var player: KSYMoviePlayerController? var kit: KSYUIRecorderKit? var stat: UILabel! var videoView: UIView! var btnPlay: UIButton! var btnPause: UIButton! var btnResume: UIButton! var btnStop: UIButton! var btnQuit: UIButton! var labelHWCodec: UILabel! var switchHWCodec: UISwitch! var labelVolume: UILabel! var sliderVolume: UISlider! var btnStartRecord: UIButton! var btnStopRecord: UIButton! var recordFilePath: String! init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(url: URL) { self.init() self.url = url } override func viewDidLoad() { super.viewDidLoad() initUI() setupUIKit() } func initUI() { videoView = UIView() videoView.backgroundColor = .white view.addSubview(videoView) btnPlay = addButton(with: "播放", action: #selector(onPlayVideo(sender:))) btnPause = addButton(with: "暂停", action: #selector(onPauseVideo(sender:))) btnResume = addButton(with: "继续", action: #selector(onResumeVideo(sender:))) btnStop = addButton(with: "停止", action: #selector(onStopVideo(sender:))) btnQuit = addButton(with: "退出", action: #selector(onQuit(sender:))) btnStartRecord = addButton(with: "开始录屏", action: #selector(onStartRecordVideo(sender:))) btnStopRecord = addButton(with: "停止录屏", action: #selector(onStopRecordVideo(sender:))) btnStartRecord.isEnabled = false btnStopRecord.isEnabled = false stat = UILabel() stat.backgroundColor = .clear stat.textColor = .red stat.numberOfLines = 0 stat.textAlignment = .left view.addSubview(stat) labelHWCodec = UILabel() labelHWCodec.text = "硬解码" labelHWCodec.textColor = .lightGray view.addSubview(labelHWCodec) labelVolume = UILabel() labelVolume.text = "音量" labelVolume.textColor = .lightGray view.addSubview(labelVolume) switchHWCodec = UISwitch() view.addSubview(switchHWCodec) switchHWCodec.isOn = true sliderVolume = UISlider() sliderVolume.minimumValue = 0 sliderVolume.maximumValue = 100 sliderVolume.value = 100 sliderVolume.addTarget(self, action: #selector(onVolumeChanged(slider:)), for: .valueChanged) view.addSubview(sliderVolume) layoutUI() view.bringSubview(toFront: stat) stat.frame = UIScreen.main.bounds } func addButton(with title: String, action: Selector) -> UIButton { let btn = UIButton.init(type: .roundedRect) btn.setTitle(title, for: .normal) btn.backgroundColor = .lightGray btn.addTarget(self, action: action, for: .touchUpInside) btn.layer.masksToBounds = true btn.layer.cornerRadius = 5 btn.layer.borderColor = UIColor.black.cgColor btn.layer.borderWidth = 1 view.addSubview(btn) return btn } func layoutUI() { let wdt: CGFloat = view.bounds.width let hgt: CGFloat = view.bounds.height let gap: CGFloat = 15 let btnWdt: CGFloat = (wdt - gap) / 5 - gap let btnHgt: CGFloat = 30 var xPos: CGFloat = 0 var yPos: CGFloat = 0 yPos = gap * 2 xPos = gap labelVolume.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos += btnWdt + gap sliderVolume.frame = CGRect.init(x: xPos, y: yPos, width: wdt - 3 * gap - btnWdt, height: btnHgt) yPos += btnHgt + gap xPos = gap labelHWCodec.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt * 2, height: btnHgt) xPos += btnWdt + gap switchHWCodec.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) videoView.frame = CGRect.init(x: 0, y: 0, width: wdt, height: hgt) xPos = gap yPos = hgt - btnHgt - gap btnPlay.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos += gap + btnWdt btnPause.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos += gap + btnWdt btnResume.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos += gap + btnWdt btnStop.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos += gap + btnWdt btnQuit.frame = CGRect.init(x: xPos, y: yPos, width: btnWdt, height: btnHgt) xPos = gap yPos -= btnHgt + gap let newWidth: CGFloat = btnWdt * 2 btnStartRecord.frame = CGRect.init(x: xPos, y: yPos, width: newWidth, height: btnHgt) xPos += gap + newWidth btnStopRecord.frame = CGRect.init(x: xPos, y: yPos, width: newWidth, height: btnHgt) } func handlePlayerNotify(notify: Notification) { guard let _ = player else { return } if Notification.Name.MPMoviePlayerPlaybackDidFinish == notify.name { let reason: Int = (notify.userInfo![MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] as! NSNumber).intValue if reason == MPMovieFinishReason.playbackEnded.rawValue { stat.text = "player finish"; }else if reason == MPMovieFinishReason.playbackError.rawValue { stat.text = "player Error : \(notify.userInfo!["error"])" }else if reason == MPMovieFinishReason.userExited.rawValue { stat.text = "player userExited" } } } func toast(message: String) { let toast = UIAlertView.init(title: nil, message: message, delegate: nil, cancelButtonTitle: nil) toast.show() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { toast.dismiss(withClickedButtonIndex: 0, animated: true) } } func initPlayer(with url: URL) { player = KSYMoviePlayerController.init(contentURL: self.url, sharegroup: GPUImageContext.sharedImageProcessing().context.sharegroup) setupObservers() // player 视频数据输入 player?.textureBlock = { [weak self] (textureId: GLuint, width: Int32, height: Int32, pts: Double) -> Void in let size = CGSize.init(width: CGFloat(width), height: CGFloat(height)) let _pts = CMTime.init(value: Int64(pts * 1000), timescale: 1000) self?.kit?.process(with: textureId, textureSize: size, time: _pts) } // player 音频数据输入 player?.audioDataBlock = { [weak self] (buf) -> Void in let pts = CMSampleBufferGetPresentationTimeStamp(buf!) if pts.value < 0 { print("audio pts < 0") return } self?.kit?.processAudioSampleBuffer(buf: buf!) } player?.videoDecoderMode = switchHWCodec.isOn ? MPMovieVideoDecoderMode.hardware : MPMovieVideoDecoderMode.software player?.view.frame = videoView.bounds videoView.addSubview(player!.view) videoView.bringSubview(toFront: stat) player?.prepareToPlay() } func setupObservers() { NotificationCenter.default.addObserver(self, selector: #selector(handlePlayerNotify(notify:)), name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: player) NotificationCenter.default.addObserver(self, selector: #selector(onStreamStateChange(notify:)), name: NSNotification.Name.KSYStreamStateDidChange, object: nil) } func releaseObservers() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: player) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.KSYStreamStateDidChange, object: nil) } func onVolumeChanged(slider: UISlider) { guard let _ = player else { return } player!.setVolume(slider.value / 100, rigthVolume: slider.value / 100) } func onPlayVideo(sender: NSObject) { if let _ = player { player!.setUrl(URL.init(string: "rtmp://live.hkstv.hk.lxdns.com/live/hks")) player!.prepareToPlay() } else { initPlayer(with: url) btnStartRecord.isEnabled = true btnStopRecord.isEnabled = false } } func onPauseVideo(sender: NSObject) { guard let _ = player else { return } player!.pause() } func onResumeVideo(sender: NSObject) { guard let _ = player else { return } player!.play() } func onStopVideo(sender: UIButton?) { guard let _ = player else { return } player!.stop() releaseObservers() player!.view.removeFromSuperview() player = nil } func onQuit(sender: NSObject) { onStopVideo(sender: nil) dismiss(animated: false, completion: nil) stat.text = nil } func onStartRecordVideo(sender: NSObject) { guard let _ = recordFilePath else { return } deleteFile(file: recordFilePath!) let path: URL = URL.init(string: recordFilePath!)! kit?.startRecord(path: path) btnStartRecord.isEnabled = false btnStopRecord.isEnabled = true } func onStopRecordVideo(sender: NSObject) { kit?.stopRecord() btnStartRecord.isEnabled = true btnStopRecord.isEnabled = false } // MARK: record kit setup func setupUIKit() { recordFilePath = (NSHomeDirectory() as NSString).appendingPathComponent("Documents/RecordAv.mp4") kit = KSYUIRecorderKit() addUIToKit() } func addUIToKit() { kit?.contentView.addSubview(labelVolume) kit?.contentView.addSubview(sliderVolume) kit?.contentView.addSubview(labelHWCodec) kit?.contentView.addSubview(switchHWCodec) kit?.contentView.addSubview(btnPlay) kit?.contentView.addSubview(btnPause) kit?.contentView.addSubview(btnResume) kit?.contentView.addSubview(btnStopRecord) kit?.contentView.addSubview(btnQuit) kit?.contentView.addSubview(btnStartRecord) kit?.contentView.addSubview(btnStopRecord) kit?.contentView.addSubview(stat) if let _ = player { kit?.contentView.addSubview((player?.view)!) } view.addSubview((kit?.contentView)!) kit?.contentView.sendSubview(toBack: videoView) } func onStreamError(errCode: KSYStreamErrorCode) { switch errCode { case KSYStreamErrorCode.CONNECT_BREAK: // Reconnect tryReconnect() break case KSYStreamErrorCode.AV_SYNC_ERROR: print("audio video is not synced, please check timestamp") tryReconnect() break case KSYStreamErrorCode.CODEC_OPEN_FAILED: print("video codec open failed, try software codec") kit?.writer?.videoCodec = KSYVideoCodec.X264 tryReconnect() break default: () } } func onStreamStateChange(notify: Notification) { guard let _ = kit?.writer else { return } print("stream State \(kit!.writer!.getCurStreamStateName())") // 状态为KSYStreamStateIdle且_bRecord为true时,录制视频 if kit!.writer!.streamState == KSYStreamState.idle && !kit!.bPlayRecord { saveVideoToAlbum(path: recordFilePath) } if kit!.writer!.streamState == KSYStreamState.error { onStreamError(errCode: kit!.writer!.streamErrorCode) } } func tryReconnect() { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { [weak self] in print("try again") let path: URL = URL.init(string: (self?.recordFilePath)!)! self?.kit?.startRecord(path: path) } } //保存视频到相簿 func saveVideoToAlbum(path: String) { let fm = FileManager.default if !fm.fileExists(atPath: path) { return } DispatchQueue.global().async { [weak self] in if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) { UISaveVideoAtPathToSavedPhotosAlbum(path, self, #selector(self?.didFinishSaving(videoPath:error:contextInfo:)), nil) } } } //保存mp4文件完成时的回调 func didFinishSaving(videoPath: String, error: Error?, contextInfo: UnsafeMutableRawPointer) { var msg: String if let _ = error { msg = "Failed to save the album!" } else { msg = "Save album success!" } toast(message: msg) } //删除文件,保证保存到相册里面的视频时间是更新的 func deleteFile(file: String) { let fm = FileManager.default if fm.fileExists(atPath: file) { try! fm.removeItem(atPath: file) } } override var shouldAutorotate: Bool{ layoutUI() return true } }
34.253363
176
0.538718
14091f8806afea3c61ebd1fa2736142af3a46d79
767
// // DogsHome+Coordinator.swift // Dogs We Love // // Created by Jesus Eduardo Santa Olalla Picazo (Vendor) on 1/28/20. // Copyright © 2020 Codikas. All rights reserved. // import UIKit public protocol DogsHomeCoordinatorType { func goToDetail(dog: Dog) func goToAnyOtherView() } final class DogsHomeCoordinator { var navigationController: UINavigationController? init() { let dogsHomeViewController = DogsHomeFactory.makeView(coordinator: self) self.navigationController = UINavigationController(rootViewController: dogsHomeViewController) } } extension DogsHomeCoordinator: DogsHomeCoordinatorType { func goToDetail(dog: Dog) { } func goToAnyOtherView() { } }
20.72973
102
0.688396
ab0401b95d19c85fe2dd85a55a29fa891cb17873
997
// // SVGCGFloat.swift // Plot // // Created by Klaus Kneupner on 10/04/2020. // import Foundation public extension Double { func asString(decimals: Int = 2) -> String { return String(format: "%.\(decimals)f", self) } } public extension CGFloat { func asString(decimals: Int = 2) -> String { return Double(self).asString(decimals: decimals) } } public extension NSPoint { func svg(adjustY: Double) -> String { let newY = adjustY - Double(self.y) return "\(x.asString()) \(newY.asString())" } } enum HasEndingResult { case no case remaining(String) } extension String { func hasEnding(_ ending: String) -> HasEndingResult { if let range = self.range(of: ending) { return .remaining(String(self.prefix(upTo: range.lowerBound)).trim()) } return .no } public func trim() -> String { return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } }
20.770833
81
0.617854
4a77e1ac96f94122bab13cc1041aac044e0a5c17
2,659
// // SceneDelegate.swift // Stocks // // Created by Juan Francisco Dorado Torres on 25/08/20. // Copyright © 2020 Juan Francisco Dorado Torres. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
44.316667
143
0.742384
d7bb278ceabab0267f0510686928b01a838e30e4
4,120
// The MIT License (MIT) // // Copyright (c) 2019 Lucas Nelaupe // // 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 XCTest @testable import SwiftQueue class ConstraintTestDeadline: XCTestCase { func testDeadlineWhenSchedule() { let (type, job) = (UUID().uuidString, TestJob()) let creator = TestCreator([type: job]) let manager = SwiftQueueManagerBuilder(creator: creator).set(persister: NoPersister.shared).build() JobBuilder(type: type) .deadline(date: Date(timeIntervalSinceNow: TimeInterval(-10))) .schedule(manager: manager) job.awaitForRemoval() job.assertRemovedBeforeRun(reason: .deadline) } func testDeadlineWhenRun() { let (type1, job1) = (UUID().uuidString, TestJob()) let (type2, job2) = (UUID().uuidString, TestJob()) let creator = TestCreator([type1: job1, type2: job2]) let manager = SwiftQueueManagerBuilder(creator: creator).set(persister: NoPersister.shared).build() JobBuilder(type: type1) .delay(time: Double.leastNonzeroMagnitude) .retry(limit: .limited(5)) .schedule(manager: manager) JobBuilder(type: type2) .deadline(date: Date()) // After 1 second should fail .retry(limit: .unlimited) .schedule(manager: manager) manager.waitUntilAllOperationsAreFinished() job1.awaitForRemoval() job1.assertSingleCompletion() job2.awaitForRemoval() job2.assertRemovedBeforeRun(reason: .deadline) } func testDeadlineWhenDeserialize() { let (type, job) = (UUID().uuidString, TestJob()) let creator = TestCreator([type: job]) let group = UUID().uuidString let json = JobBuilder(type: type) .parallel(queueName: group) .deadline(date: Date()) .build(job: job) .toJSONStringSafe() let persister = PersisterTracker(key: UUID().uuidString) persister.put(queueName: group, taskId: UUID().uuidString, data: json) let manager = SwiftQueueManagerBuilder(creator: creator).set(persister: persister).build() job.awaitForRemoval() job.assertRemovedBeforeRun(reason: .deadline) XCTAssertEqual(group, persister.restoreQueueName) manager.waitUntilAllOperationsAreFinished() } func testDeadlineAfterSchedule() { let (type, job) = (UUID().uuidString, TestJob()) let creator = TestCreator([type: job]) let manager = SwiftQueueManagerBuilder(creator: creator).set(persister: NoPersister.shared).build() JobBuilder(type: type) .delay(time: 60) .deadline(date: Date(timeIntervalSinceNow: Double.leastNonzeroMagnitude)) .retry(limit: .unlimited) .schedule(manager: manager) manager.waitUntilAllOperationsAreFinished() job.awaitForRemoval() job.assertRemovedBeforeRun(reason: .deadline) } }
36.140351
107
0.664078
eb3140885421a575bcc413b6b1ae8ae3a8f29fdd
32,409
// // Countraints.swift // chata // // Created by Vicente Rincon on 21/10/20. // import Foundation import UIKit public enum DViewSafeArea: String, CaseIterable { case topView, elementToRight, leading, trailing, bottomView, vertical, horizontal, all, none, noneLeft, widthLeft , widthRight, widthRightY, none2, full, fullStack, fullLimit, fullWidth, leftBottom, rightTop, rightBottom, fullStatePaddingAll, rightCenterY, safe , safeChat, safeChatLeft, safeChatTop, safeChatBottom, safeButtons, safeButtonsLeft, safeButtonsTop, safeButtonsBottom, safeFH, safeFHLeft, safeFHTop, safeFHBottom, leftCenterY, fullState, fullState2, bottomSize, center, leftAdjust, padding, paddingTop, rightMiddle = "right", leftMiddle = "left", topMiddle = "top", bottomMiddle = "bottom", fullBottom, fullBottomCenter, paddingTopLeft, paddingTopRight, modal, modal2, modal2Right, secondTop, bottomPaddingtoTop, bottomPaddingtoTopHalf, fullPadding, topHeight, topHeightPadding, fullStatePaddingTop, dropDownBottomHeight, dropDownBottomHeightLeft, topY, nonePadding, fullStackH, topPadding, fullStatePadding, bottomPadding, fullStackV, fullStackHH, dropDown, dropDownTop, dropDownTopView, dropDownTopHeight,dropDownTopHeightLeft, centerSize, bottomRight, centerSizeUp static func withLabel(_ str: String) -> DViewSafeArea? { return self.allCases.first { "\($0.description)" == str } } var description: String { return self.rawValue } } extension UIView { @discardableResult public func edgeTo(_ view: UIView, safeArea: DViewSafeArea = .none, height: CGFloat = 0, width: CGFloat = 0, _ top: UIView = UIView(), _ bottom: UIView = UIView(), padding: CGFloat = -8) -> UIView { translatesAutoresizingMaskIntoConstraints = false switch safeArea { case .topView: topConst(view: view.topAnchor) topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .topPadding: topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .elementToRight: topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: top.leadingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .bottomPaddingtoTop: bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true leadingAnchor.constraint(equalTo: top.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: top.trailingAnchor).isActive = true topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true case .bottomPaddingtoTopHalf: heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.38).isActive = true leadingAnchor.constraint(equalTo: top.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: top.trailingAnchor).isActive = true topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true case .bottomPadding: bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .bottomRight: bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: padding).isActive = true case .leading: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .trailing: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .bottomView: bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .bottomSize: bottomAnchor.constraint(equalTo: top.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .vertical: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .horizontal: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .all: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .none: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .noneLeft: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .widthLeft: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .widthRight: trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true case .widthRightY: trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -10).isActive = true case .safe: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .safeButtons: centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: top.leadingAnchor, constant: 1).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .safeButtonsLeft: centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true leadingAnchor.constraint(equalTo: top.trailingAnchor, constant: -1).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .safeButtonsTop: centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true topAnchor.constraint(equalTo: top.safeAreaLayoutGuide.bottomAnchor, constant: -1).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .safeButtonsBottom: centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true bottomAnchor.constraint(equalTo: top.topAnchor, constant: 1).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .safeFH: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: top.leadingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .safeFHLeft: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: top.trailingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .safeFHTop: topAnchor.constraint(equalTo: top.bottomAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .safeFHBottom: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: top.topAnchor).isActive = true case .safeChat: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .safeChatLeft: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .safeChatTop: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -padding).isActive = true case .safeChatBottom: topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true case .nonePadding: topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: height).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -height).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -height).isActive = true case .none2: topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .modal2: topAnchor.constraint(equalTo: top.topAnchor, constant: -20).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 5).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: padding).isActive = true //trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true //bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .modal2Right: topAnchor.constraint(equalTo: top.topAnchor, constant: -20).isActive = true rightAnchor.constraint(equalTo: top.rightAnchor, constant: 5).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: padding).isActive = true case .modal: leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 5).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true case .padding: centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 10).isActive = true trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -10).isActive = true if width > 0 { widthAnchor.constraint(equalToConstant: width).isActive = true } case .paddingTop: topAnchor.constraint(equalTo: view.topAnchor, constant: 40).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .paddingTopLeft: topAnchor.constraint(equalTo: view.topAnchor, constant: 25).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -10).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .paddingTopRight: topAnchor.constraint(equalTo: view.topAnchor, constant: 16).isActive = true leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 58).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .secondTop: topAnchor.constraint(equalTo: view.topAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height * 4).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true case .fullState: topAnchor.constraint(equalTo: top.bottomAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .fullStatePadding: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true case .fullStatePaddingAll: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true case .fullStatePaddingTop: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true case .fullState2: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true heightAnchor.constraint(equalToConstant: 300.0).isActive = true case .full: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: bottom.topAnchor).isActive = true case .fullStack: topAnchor.constraint(equalTo: view.topAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .fullPadding: topAnchor.constraint(equalTo: top.bottomAnchor).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: bottom.topAnchor).isActive = true case .fullLimit: topAnchor.constraint(equalTo: top.bottomAnchor).isActive = true leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor).isActive = true trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: bottom.topAnchor).isActive = true case .fullBottom: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20).isActive = true trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: width).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true case .fullBottomCenter: topAnchor.constraint(equalTo: top.bottomAnchor, constant: 10).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true case .topY: bottomAnchor.constraint(equalTo: top.topAnchor, constant: 0).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .topHeight: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .topHeightPadding: topAnchor.constraint(equalTo: top.bottomAnchor, constant: padding / 2).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .fullWidth: leadingAnchor.constraint(equalTo: top.trailingAnchor).isActive = true trailingAnchor.constraint(equalTo: bottom.leadingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .leftBottom: leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .leftCenterY: leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: -padding).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true heightAnchor.constraint(equalTo: top.heightAnchor).isActive = true trailingAnchor.constraint(equalTo: top.leadingAnchor, constant: padding).isActive = true case .rightCenterY: trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true case .rightBottom: trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .rightTop: trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .center: centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true case .centerSize: centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: padding).isActive = true case .centerSizeUp: centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -130).isActive = true centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: padding).isActive = true case .leftAdjust: centerYAnchor.constraint(equalTo: top.centerYAnchor).isActive = true trailingAnchor.constraint(equalTo: top.leadingAnchor, constant: -8).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true case .rightMiddle: self.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true self.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true self.heightAnchor.constraint(equalToConstant: 50).isActive = true self.widthAnchor.constraint(equalToConstant: 50).isActive = true case .leftMiddle: self.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true self.heightAnchor.constraint(equalToConstant: 50).isActive = true self.widthAnchor.constraint(equalToConstant: 50).isActive = true self.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true case .topMiddle: self.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true self.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true self.heightAnchor.constraint(equalToConstant: 50).isActive = true self.widthAnchor.constraint(equalToConstant: 50).isActive = true case .bottomMiddle: self.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true self.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true self.heightAnchor.constraint(equalToConstant: 50).isActive = true self.widthAnchor.constraint(equalToConstant: 50).isActive = true case .fullStackH: leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .fullStackHH: leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .fullStackV: topAnchor.constraint(equalTo: view.topAnchor, constant: padding).isActive = true bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: height).isActive = true centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true case .dropDown: topAnchor.constraint(equalTo: view.bottomAnchor, constant: padding).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: -padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownTop: topAnchor.constraint(equalTo: top.bottomAnchor, constant: 1).isActive = true leadingAnchor.constraint(equalTo: top.leadingAnchor, constant: -padding).isActive = true trailingAnchor.constraint(equalTo: top.trailingAnchor, constant: padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownTopView: topAnchor.constraint(equalTo: top.bottomAnchor, constant: 1).isActive = true leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: -padding).isActive = true trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: padding).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownTopHeight: topAnchor.constraint(equalTo: top.bottomAnchor, constant: 1).isActive = true trailingAnchor.constraint(equalTo: top.trailingAnchor, constant: padding).isActive = true widthAnchor.constraint(equalToConstant: 250).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownTopHeightLeft: topAnchor.constraint(equalTo: top.bottomAnchor, constant: 1).isActive = true leadingAnchor.constraint(equalTo: top.leadingAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: 250).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownBottomHeight: bottomAnchor.constraint(equalTo: top.topAnchor, constant: 1).isActive = true leadingAnchor.constraint(equalTo: top.leadingAnchor, constant: -padding).isActive = true widthAnchor.constraint(equalToConstant: 250).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true case .dropDownBottomHeightLeft: bottomAnchor.constraint(equalTo: top.topAnchor, constant: 1).isActive = true trailingAnchor.constraint(equalTo: top.trailingAnchor, constant: padding).isActive = true widthAnchor.constraint(equalToConstant: 250).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true } return self } private func topConst(view: NSLayoutYAxisAnchor){ topAnchor.constraint(equalTo: view).isActive = true } }
72.665919
864
0.70647
28031a61ff9aa29cd9805b058d79a324e4dda871
1,127
// // KeyboardArray.swift // SFSymbolCreator // // Created by Richard Witherspoon on 4/22/21. // import Foundation let keyboardArray = [ "command", "command.circle", "command.circle.fill", "command.square", "command.square.fill", "option", "alt", "delete.right", "delete.right.fill", "clear", "clear.fill", "delete.left", "delete.left.fill", "shift", "shift.fill", "capslock", "capslock.fill", "escape", "power", "globe", "sun.min", "sun.min.fill", "sun.max", "sun.max.fill", "light.min", "light.max", "keyboard", "keyboard.chevron.compact.down", "keyboard.chevron.compact.left", "keyboard.onehanded.left", "keyboard.onehanded.right", "eject", "eject.fill", "eject.circle", "eject.circle.fill", "mount", "mount.fill", "control", "projective", "arrow.left.to.line.alt", "arrow.left.to.line", "arrow.right.to.line.alt", "arrow.right.to.line", "arrow.up.to.line.alt", "arrow.up.to.line", "arrow.down.to.line.alt", "arrow.down.to.line" ]
19.101695
46
0.568767
21cedf042720ccce2039d128dd5242feb8054046
11,017
/* 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 XCTest @testable import SwiftLogFireCloud class CloudLogFileManagerTests: XCTestCase { var config: SwiftLogFireCloudConfig! var cloudManager: CloudLogFileManager! var fakeClientCloudUploader: FakeClientCloudUploader! var localLogFile: LocalLogFile! override func setUpWithError() throws { fakeClientCloudUploader = FakeClientCloudUploader() config = SwiftLogFireCloudConfig(logToCloud: false, localFileSizeThresholdToPushToCloud: 100, localFileBufferWriteInterval: 60, uniqueID: "SwiftLogFireCloud", minFileSystemFreeSpace: 20, logDirectoryName: "TestLogs", logToCloudOnSimulator: true, cloudUploader: fakeClientCloudUploader) cloudManager = CloudLogFileManager(label: "SwiftLogFireCloud", config: config) localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) } override func tearDownWithError() throws { cloudManager = nil } func testRightTimetoWriteToCloudWhenLogabilityNormalAndEnoughBytesWritten() { cloudManager.lastWriteSuccess = Date(timeIntervalSinceNow: -30) cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssert(result) } func testRightTimetoWriteToCloudWhenLogabilityNormalAndNotEnoughBytesWritten() { cloudManager.lastWriteSuccess = Date(timeIntervalSinceNow: -30) cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud - 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssertFalse(result) } func testRightTimeToWriteTOCloudWhenLogabilityImpairedAndOutsideRetryInterval() { cloudManager.lastWriteSuccess = Date() cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -190) let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssert(result) } func testRightTimeToWriteTOCloudWhenLogabilityImpairedAndInsideRetryInterval() { cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -10) cloudManager.successiveFails = 5 let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssertFalse(result) } func testRightTimeToWriteTOCloudWhenLogabilityUnfunctionalAndInsideRetryInterval() { cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -500) cloudManager.successiveFails = 12 let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssertFalse(result) } func testRightTimeToWriteTOCloudWhenLogabilityUnfunctionalAndOutsideRetryInterval() { cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -700) cloudManager.successiveFails = 12 let localLogFile = LocalLogFile(label: "SwiftLogFireCloud", config: config, queue: DispatchQueue(label: "TestQueue")) localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 let result = cloudManager.isNowTheRightTimeToWriteToCloud(localLogFile) XCTAssert(result) } func testWriteLogFileTCloudWithNoPendingWrites() { localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 localLogFile.pendingWriteCount = 0 cloudManager.writeLogFileToCloud(localLogFile: localLogFile) let expectation = XCTestExpectation(description: "Wait for async upload") DispatchQueue.main.asyncAfter(deadline: .now() + 2) { expectation.fulfill() } wait(for: [expectation], timeout: 3.0) XCTAssert(fakeClientCloudUploader.successUploadURLs.contains(localLogFile.fileURL)) } func testWriteLogFileToCloudWithResolvedPendingWrites() { localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 localLogFile.pendingWriteCount = 10 localLogFile.pendingWriteWaitCount = 0 cloudManager.writeLogFileToCloud(localLogFile: localLogFile) localLogFile.pendingWriteCount = 0 let expectation = XCTestExpectation(description: "Wait for async upload") DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { expectation.fulfill() } wait(for: [expectation], timeout: 4.0) XCTAssert(fakeClientCloudUploader.successUploadURLs.contains(localLogFile.fileURL)) } func testWriteLogFileToCloudAfterPendingWritesTimeout() { localLogFile.bytesWritten = config.localFileSizeThresholdToPushToCloud + 10 localLogFile.pendingWriteCount = 10 localLogFile.pendingWriteWaitCount = 0 cloudManager.writeLogFileToCloud(localLogFile: localLogFile) let expectation = XCTestExpectation(description: "Wait for async upload") DispatchQueue.main.asyncAfter(deadline: .now() + 6.0) { expectation.fulfill() } wait(for: [expectation], timeout: 7.0) XCTAssert(fakeClientCloudUploader.successUploadURLs.isEmpty) } func testAddingFirstFileToCloudPushQueue() { cloudManager.addFileToCloudPushQueue(localLogFile: localLogFile) let expectation = XCTestExpectation(description: "Wait for async timer start") DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { expectation.fulfill() } wait(for: [expectation], timeout: 0.5) XCTAssert(cloudManager.strandedFilesToPush?.count == 1) XCTAssert(cloudManager.strandedFileTimer!.isValid) } func testAddingAdditionalFilesToCloudPushQueue() { cloudManager.addFileToCloudPushQueue(localLogFile: localLogFile) cloudManager.addFileToCloudPushQueue(localLogFile: localLogFile) let expectation = XCTestExpectation(description: "Wait for async timer start") DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { expectation.fulfill() } wait(for: [expectation], timeout: 0.5) XCTAssert(cloudManager.strandedFilesToPush?.count == 2) XCTAssert(cloudManager.strandedFileTimer!.isValid) } func testReportUploadStatusOnSuccess() { XCTAssertNil(cloudManager.lastWriteSuccess) cloudManager.reportUploadStatus(.success(localLogFile)) let expectation = XCTestExpectation(description: "Wait for async timer start") DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { expectation.fulfill() } wait(for: [expectation], timeout: 0.5) XCTAssertNotNil(cloudManager.lastWriteSuccess) XCTAssert(cloudManager.successiveFails == 0) } func testReportUploadStatusOnFailure() { let previousSuccessiveFails = cloudManager.successiveFails cloudManager.reportUploadStatus(.failure(CloudUploadError.failedToUpload(localLogFile))) let expectation = XCTestExpectation(description: "Wait for async timer start") DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { expectation.fulfill() } wait(for: [expectation], timeout: 0.5) let strandedURLs = cloudManager.strandedFilesToPush!.map { $0.fileURL } XCTAssert(strandedURLs.contains(localLogFile.fileURL)) XCTAssert(cloudManager.successiveFails == previousSuccessiveFails + 1) } func testCloudLogabilityWhenNormalAndNoWritesAttempted() { cloudManager.successiveFails = 1 cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let logability = cloudManager.assessLogability() XCTAssert(logability == .normal) } func testCloudLogabilityWhenNormalAndWritesAttempted() { cloudManager.lastWriteSuccess = Date(timeIntervalSinceNow: -30) cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let logability = cloudManager.assessLogability() XCTAssert(logability == .normal) } func testCloudLogabilityWhenImpairedFromFailedWrite() { cloudManager.successiveFails = 5 cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let logability = cloudManager.assessLogability() XCTAssert(logability == .impaired) } func testCloudLogabilityWhenImpairedFromDelaysBetweenAttemptAndSucces() { cloudManager.lastWriteSuccess = Date() cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -190) let logability = cloudManager.assessLogability() XCTAssert(logability == .impaired) } func testCloudLogabilityWhenUnfunctionalFromDelayBetweenAttempAndSuccess() { cloudManager.lastWriteSuccess = Date() cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -900) let logability = cloudManager.assessLogability() XCTAssert(logability == .unfunctional) } func testCloudLogabilityWhenUnfunctionalFromFailedWrites() { cloudManager.successiveFails = 12 cloudManager.lastWriteAttempt = Date(timeIntervalSinceNow: -31) let logability = cloudManager.assessLogability() XCTAssert(logability == .unfunctional) } }
40.355311
92
0.713987
e46f46a0e7cf74f8934c04139713d28715740327
872
/* Copyright 2017 Urban Airship and Contributors */ import UIKit import AirshipKit class AddTagsTableViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var addCustomTagTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.addCustomTagTextField.delegate = self } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return false } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) if ((textField.text?.characters.count)! > 0){ UAirship.push().addTag(textField.text!) } else { return false } UAirship.push().updateRegistration() _ = navigationController?.popViewController(animated: true) return true } }
24.914286
98
0.668578
bb923e802a0d425777a67aba0480aa017e53c9d3
5,343
// // LoginViewController.swift // SwiftUIKit_Example // // Created by Quang Tran on 31/12/2021. // Copyright © 2021 CocoaPods. All rights reserved. // import DeclarativeUI import SwiftUI class LoginViewController: LoginBaseViewController { override func viewDidLoad() { super.viewDidLoad() view.body { SafeArea(edges: [.bottom, .right, .left]) { Stack(axis: .vertical) { Padding(padding: .left(10)) { Stack(axis: .vertical) { UILabel("Login").with .textColor(.tintColor) .font(.systemFont(ofSize: 36, weight: .bold)) UILabel("Email").with .textColor(.tintColor) .font(.systemFont(ofSize: 14)) UITextField().with .borderStyle(.roundedRect) .borderColor(UIColor.tintColor.cgColor) .cornerRadius(10) .borderWidth(1) .backgroundColor(.white) .width(to: .width) UILabel("Password").with .textColor(.tintColor) .font(.systemFont(ofSize: 14)) UITextField().with .borderStyle(.roundedRect) .borderColor(UIColor.tintColor.cgColor) .cornerRadius(10) .borderWidth(1) .backgroundColor(.white) .width(to: .width) UIView { UIButton(type: .system).with .title("Forgot Passwords?", for: .normal) .font(.systemFont(ofSize: 16, weight: .bold), for: .normal) .titleColor(.tintColor, for: .normal) .trailing(to: .trailing) .height(to: .height) }.with .trailing(0) }.with .spacing(10) }.with .width(to: .width, -30) Stack(axis: .horizontal) { UIButton(type: .system).with .image(UIImage(named: "apple logo")?.withRenderingMode(.alwaysOriginal), for: .normal) .width(to: .height) UIButton(type: .system).with .image(UIImage(named: "fb logo")?.withRenderingMode(.alwaysOriginal), for: .normal) .width(to: .height) UIButton(type: .system).with .image(UIImage(named: "google logo")?.withRenderingMode(.alwaysOriginal), for: .normal) .width(to: .height) }.with .leading(0) .height(60) Spacer(height: 100) UIView { UIButton.actionButton .height(to: .height) .trailing(0) .bottom(0) .title("Login", for: .normal) .onTap(self, action: #selector(buttonAction)) Stack(axis: .horizontal) { UILabel("New here?").with .textColor(.white) .font(.systemFont(ofSize: 16)) Spacer(width: 10) UIButton(type: .system).with .title("Register", for: .normal) .tintColor(.white) .font(.systemFont(ofSize: 16, weight: .bold), for: .normal) }.with .height(22) .bottom(0) .leading(0) }.with .bottom(20) .leading(25) .trailing(30) }.with .alignment(.leading) }.with .bottom(10) .leading(0) .trailing(0) } } @objc func buttonAction() { navigationController?.popViewController(animated: true) } }
40.172932
115
0.333895
14b289f39f9f097b2a1f7c47433b7a7a789ddf7c
5,362
// // SceneDelegate.swift // Neebla // // Created by Christopher G Prince on 11/10/20. // import UIKit import SwiftUI import iOSShared // Adapted from https://stackoverflow.com/questions/57441654/swiftui-repaint-view-components-on-device-rotation class AppEnv: ObservableObject { @Published var isLandScape: Bool = false } class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? var appEnv = AppEnv() func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = MainView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView.environmentObject(appEnv)) self.window = window window.makeKeyAndVisible() } // Because on an app launch when tapping on a sharing invitation, I don't get the `openURLContexts` method called. See also https://stackoverflow.com/questions/58973143 let urlinfo = connectionOptions.urlContexts if let url = urlinfo.first?.url { _ = Services.session.application(UIApplication.shared, open: url) } } // See https://github.com/dropbox/SwiftyDropbox/issues/259 // Also relevant: I first tried to use the SwiftUI life cycle management-- without a SceneDelegate, but I wasn't able to get an equivalent method to this called. Even using https://stackoverflow.com/questions/62538110 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { if let url = URLContexts.first?.url { _ = Services.session.application(UIApplication.shared, open: url) } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. logger.debug("sceneDidBecomeActive") AppState.session.postUpdate(.foreground) } 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). logger.debug("sceneWillResignActive") debugBackground() AppState.session.postUpdate(.background) } func sceneWillEnterForeground(_ scene: UIScene) { } 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. } func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) { appEnv.isLandScape = windowScene.interfaceOrientation.isLandscape } } extension SceneDelegate { func debugBackground() { logger.debug("openFilePaths: \(openFilePaths())") } // From https://developer.apple.com/forums/thread/655225 func openFilePaths() -> [String] { let result = (0..<getdtablesize()).map { fd -> (String?) in var flags: CInt = 0 guard fcntl(fd, F_GETFL, &flags) >= 0 else { return nil } // Return "?" for file descriptors not associated with a path, for // example, a socket. var path = [CChar](repeating: 0, count: Int(MAXPATHLEN)) guard fcntl(fd, F_GETPATH, &path) >= 0 else { return "?" } // https://stackoverflow.com/questions/11737819 var flockValue:flock = flock() if fcntl(fd, F_GETLK, &flockValue) >= 0 && flockValue.l_type == F_WRLCK { return String(cString: path) + "; flock.l_type: F_WRLCK (exclusive or write lock)" } return String(cString: path) } return result.compactMap {$0} } }
44.683333
241
0.675494
1a84973de1a9b3401da454017a07cdd1e1f4c5d6
758
// // ConnectCommands.swift // LiveFlight // // Created by Cameron Carmichael Alonso on 10/08/2018. // Copyright © 2018 LiveFlight. All rights reserved. // public enum ConnectCommand:String { // Autopilot case SetHeading = "Commands.Autopilot.SetHeading" case SetAltitude = "Commands.Autopilot.SetAltitude" case SetVS = "Commands.Autopilot.SetVS" case SetSpeed = "Commands.Autopilot.SetSpeed" case AutopilotState = "Autopilot.GetState" // Cameras case PreviousCamera = "Commands.PrevCamera" case NextCamera = "Commands.NextCamera" // Status case Status = "InfiniteFlight.GetStatus" // Aircraft case AircraftState = "Airplane.GetState" case AircraftInfo = "Airplane.GetInfo" }
24.451613
55
0.691293
61ec1465ad10b3a3bc0d9b92cc1cdb8f8a093f49
2,755
import Foundation /** * Class that should be extende by all implementations that want to provide logging functionality * Note: This class is moved from protocol because * logger interface requires to provide default values for line numbers etc. * Class can be also used to disable SDK logging */ open class AgsLoggable { /** * Log something at the verbose log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func verbose(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } /** * Log something at the debug log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func debug(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } /** * Log something at the info log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func info(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } /** * Log something at the warning log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func warning(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } /** * Log something at the error log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func error(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } /** * Log something at the severe log level. * * @param closure A closure that returns the object to be logged. * It can be any object like string, array etc. */ open func severe(functionName _: StaticString = #function, fileName _: StaticString = #file, lineNumber _: Int = #line, _: @autoclosure () -> Any?) { // Intentionally empty. See implementations } }
38.802817
154
0.648639
87450b69adde08ef3b0d8b9155819276f002e9ac
1,259
// // Extensions.swift // TigerHacks-App // // Created by Evan Teters on 4/19/18. // Copyright © 2018 Zukosky, Jonah. All rights reserved. // import Foundation import UIKit extension UIImage { class func convertGradientToImage(colors: [UIColor], frame: CGRect, locations: [Double]) -> UIImage { // start with a CAGradientLayer let gradientLayer = CAGradientLayer() gradientLayer.frame = frame // add colors as CGCologRef to a new array and calculate the distances var colorsRef = [CGColor]() //let locations = [0,1] for index in 0 ... colors.count-1 { colorsRef.append(colors[index].cgColor as CGColor) //locations.append(Float(i)/Float(colors.count-1)) } gradientLayer.colors = colorsRef gradientLayer.locations = locations as [NSNumber]? // now build a UIImage from the gradient UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // return the gradient image return gradientImage! } }
29.27907
78
0.641779
8f376745faa11810fd3500fb98733902038b82fc
653
// // CategoryEntity.swift // Hana // // Created by ccsuser02 on 2018/07/23. // import UIKit import Parse enum CategoryType: Int { case wantTodo = 0 case event } class CategoryEntity: PFObject, PFSubclassing { static func parseClassName() -> String { return CategoryClassName } var type: CategoryType { set { self["type"] = newValue.rawValue } get { let type = self["type"] let typeInt = type as? Int return CategoryType(rawValue: typeInt ?? 0)! } } @NSManaged var name: String! @NSManaged var image: PFFile! }
17.648649
56
0.565084
f46f42bbfe48bed24ca7521564a17a1df875f1bb
561
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func som<T>: NSObject { var fostruct B : A { } struct C<D, E: A where D.C => String { { } { g) { h } } protocol f { class func i() } class d: f{ class func i {}
24.391304
79
0.69697
206b38fa0158917ba62509e395d51dcead76b937
1,875
import FioriSwiftUICore import SwiftUI class ActivationScreenDataModel: ActivationScreenModel, ObservableObject { @Published var textInputValue_: String = "" var title_: String = "Activation" var descriptionText_: String? = "If you received a welcome email, follow the activation link in the email.Otherwise, enter your email address or scan the QR code to start onboarding. " var actionText_: String? = "Next" var footnote_: String? = "Or" var secondaryActionText_: String? = "Scan" func didSelectAction() { print("ActivationScreen Primary button clicked, email:", self.textInputValue_) } func didSelectSecondaryAction() { print("call barcode scanner") } func onCommit() { print("TextField commit: ", self.textInputValue_) } } struct ActivationScreenSample: View { @ObservedObject var model = ActivationScreenDataModel() public init() {} var body: some View { VStack { ActivationScreen(model: model) .actionTextModifier { $0.disabled(model.textInputValue_.isEmpty) } .textInputValueModifier { $0.autocapitalization(.none) } } } } struct ActivationScreenCustomizedSample: View { @ObservedObject var model = ActivationScreenDataModel() public init() {} var body: some View { VStack { ActivationScreen(model: model) .footnoteModifier { $0.font(.headline).foregroundColor(.green) } .actionTextModifier { $0.disabled(model.textInputValue_.isEmpty) } .textInputValueModifier { $0.padding(.top, 8) .border(Color(UIColor.separator)) } } } } struct ActivationScreenSample_Previews: PreviewProvider { static var previews: some View { ActivationScreenSample() } }
31.779661
188
0.646933
0a3149769bd5ad599323b6e4f1d011721e44db69
4,976
// // KeychainProtocolType.swift // Pods // // Created by Ardalan Samimi on 24/05/16. // // import Foundation public enum KeychainProtocolType: Int { case FTP case FTPS case FTPProxy case FTPAccount case HTTP case HTTPS case HTTPProxy case HTTPSProxy case IRC case IRCS case NNTP case NNTPS case POP3 case POP3S case SMTP case SOCKS case IMAP case IMAPS case LDAP case LDAPS case AppleTalk case AFP case Telnet case TelnetS case SSH case SMB case RTSP case RTSPProxy case DAAP case DAAPS case EPPC case IPP public init(rawValue: String) { switch rawValue ?? "" { case kSecAttrProtocolFTP as String as String: self = .FTP case kSecAttrProtocolFTPS as String as String: self = .FTPS case kSecAttrProtocolFTPProxy as String as String: self = .FTPProxy case kSecAttrProtocolFTPAccount as String as String: self = .FTPAccount case kSecAttrProtocolHTTP as String as String: self = .HTTP case kSecAttrProtocolHTTPS as String as String: self = .HTTPS case kSecAttrProtocolHTTPProxy as String as String: self = .HTTPProxy case kSecAttrProtocolIRC as String as String: self = .IRC case kSecAttrProtocolIRCS as String as String: self = .IRCS case kSecAttrProtocolNNTP as String as String: self = .NNTP case kSecAttrProtocolNNTPS as String as String: self = .NNTPS case kSecAttrProtocolPOP3 as String as String: self = .POP3 case kSecAttrProtocolPOP3S as String as String: self = .POP3S case kSecAttrProtocolSMTP as String as String: self = .SMTP case kSecAttrProtocolSOCKS as String as String: self = .SOCKS case kSecAttrProtocolIMAP as String as String: self = .IMAP case kSecAttrProtocolIMAPS as String as String: self = .IMAPS case kSecAttrProtocolLDAP as String as String: self = .LDAP case kSecAttrProtocolLDAPS as String as String: self = .LDAPS case kSecAttrProtocolAppleTalk as String as String: self = .AppleTalk case kSecAttrProtocolAFP as String as String: self = .AFP case kSecAttrProtocolTelnet as String as String: self = .Telnet case kSecAttrProtocolTelnetS as String as String: self = .TelnetS case kSecAttrProtocolSSH as String as String: self = .SSH case kSecAttrProtocolSMB as String as String: self = .SMB case kSecAttrProtocolRTSP as String as String: self = .RTSP case kSecAttrProtocolRTSPProxy as String as String: self = .RTSPProxy case kSecAttrProtocolDAAP as String as String: self = .DAAP case kSecAttrProtocolLDAPS as String as String: self = .DAAPS case kSecAttrProtocolEPPC as String as String: self = .EPPC case kSecAttrProtocolIPP as String as String: self = .IPP default: self = .HTTP } } public var rawValue: String { switch self { case .FTP: return kSecAttrProtocolFTP as String case .FTPS: return kSecAttrProtocolFTPS as String case .FTPProxy: return kSecAttrProtocolFTPProxy as String case .FTPAccount: return kSecAttrProtocolFTPAccount as String case .HTTP: return kSecAttrProtocolHTTP as String case .HTTPS: return kSecAttrProtocolHTTPS as String case .HTTPProxy: return kSecAttrProtocolHTTPProxy as String case .HTTPSProxy: return kSecAttrProtocolHTTPSProxy as String case .IRC: return kSecAttrProtocolIRC as String case .IRCS: return kSecAttrProtocolIRCS as String case .NNTP: return kSecAttrProtocolNNTP as String case .NNTPS: return kSecAttrProtocolNNTPS as String case .POP3: return kSecAttrProtocolPOP3 as String case .POP3S: return kSecAttrProtocolPOP3S as String case .SMTP: return kSecAttrProtocolSMTP as String case .SOCKS: return kSecAttrProtocolSOCKS as String case .IMAP: return kSecAttrProtocolIMAP as String case .IMAPS: return kSecAttrProtocolIMAPS as String case .LDAP: return kSecAttrProtocolLDAP as String case .LDAPS: return kSecAttrProtocolLDAPS as String case .AppleTalk: return kSecAttrProtocolAppleTalk as String case .AFP: return kSecAttrProtocolAFP as String case .Telnet: return kSecAttrProtocolTelnet as String case .TelnetS: return kSecAttrProtocolTelnetS as String case .SSH: return kSecAttrProtocolSSH as String case .SMB: return kSecAttrProtocolSMB as String case .RTSP: return kSecAttrProtocolRTSP as String case .RTSPProxy: return kSecAttrProtocolRTSPProxy as String case .DAAP: return kSecAttrProtocolDAAP as String case .DAAPS: return kSecAttrProtocolLDAPS as String case .EPPC: return kSecAttrProtocolEPPC as String case .IPP: return kSecAttrProtocolIPP as String } } }
27.191257
56
0.694333
286a3f1d2307100d4f3f264af6be70ddceb5e3bb
250
import Foundation import CoreData public extension NSManagedObjectContext { func get<T: NSManagedObject>(_ object: T?) -> T? { guard let object = object else { return nil } return self.object(with: object.objectID) as? T } }
25
55
0.676
204a3e2a4465b027bd7831ff12e240a1529cdb1a
746
import XCTest import SignalBox class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.724138
111
0.600536
bfd153119f9a3a2535c333849d4a3436d00fc171
3,575
// // UIDeviceExtensions.swift // PhotoZnapp // // Created by Behran Kankul on 31.08.2018. // Copyright © 2018 Be Mobile. All rights reserved. // import UIKit public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS")" default: return identifier } } }
55.859375
142
0.464615
8f00093029273c11756713bcc21303e255edad13
1,088
// // Movie.swift // MovieBrowser // // Created by Mark Struzinski on 11/7/17. // Copyright © 2017 BobStruz Software. All rights reserved. // import Foundation struct Movie: Codable { let title: String let voteAverage: Double let overview: String let posterURLString: String? let releaseDate: String enum CodingKeys: String, CodingKey { case title case voteAverage = "vote_average" case overview case posterURLString = "poster_path" case releaseDate = "release_date" } static func from(jsonData: Data) -> Movie? { let decoder = JSONDecoder() let movie = try? decoder.decode(Movie.self, from: jsonData) return movie } } extension Movie: CustomStringConvertible { var description: String { let descriptionString = """ ################\n Movie( title: \(title) posterURLString: \(posterURLString ?? "") releaseDate: \(releaseDate) ################\n\n """ return descriptionString } }
23.148936
67
0.587316
01d44b7ed5f9d5a092a525d300e5a79ffc004346
1,808
// // NT+TitledDetail.swift // NomadTools // // Created by Justin Ackermann on 3/26/22. // // Core iOS import UIKit // Utilities import Cartography // TODO: Implement Attributes open class TitleDetail: UIView { lazy var column: Column = Column([ .alignment(.fill), .distribution(.fill), .spacing(5) ]) public lazy var _title: Header = Header(style: .H5, alignment: .center) public lazy var _detail: Header = Header(style: .H3, alignment: .center) public var title: String? { get { _title.text } set { _title.text = newValue } } public var detail: String? { get { _detail.text } set { _detail.text = newValue } } public init(_ style: TitleDetailStyle! = .TopBottom, title: String? = nil, detail: String? = nil) { super.init(frame: .zero) self.title = title self.detail = detail switch style { case .TopBottom: column.addArrangedSubview(_title) column.addArrangedSubview(_detail) case .BottomTop: column.addArrangedSubview(_detail) column.addArrangedSubview(_title) case .none: break } add(column) constrain(column, _title, _detail) { column, title, detail in let superview = column.superview! column.top == superview.top column.left == superview.left column.right == superview.right column.bottom == superview.bottom } } public enum TitleDetailStyle { case TopBottom case BottomTop } required public init?(coder: NSCoder) { super.init(coder: coder) } }
23.179487
76
0.554757
7556aad0a74d4969870015f8d6c3eb02444cb6d8
1,326
import XCTest import Prelude class FreeNearSemiringTests: XCTestCase { func testOp() { let xss = FreeNearSemiring([[1, 2], [3]]) let yss = FreeNearSemiring([[1], [2]]) let zss = FreeNearSemiring([[1, 2, 3]]) // Basic operators XCTAssert(FreeNearSemiring([[1, 2], [3], [1], [2]]) == xss + yss) XCTAssert(FreeNearSemiring([[1, 2, 1], [1, 2, 2], [3, 1], [3, 2]]) == xss * yss) // Associativity var lhs: FreeNearSemiring<Int> var rhs: FreeNearSemiring<Int> lhs = xss + (yss + zss) rhs = (xss + yss) + zss XCTAssert(lhs == rhs) lhs = xss * (yss * zss) rhs = (xss * yss) * zss XCTAssert(lhs == rhs) // Distributivity lhs = (yss + zss) * xss rhs = (yss * xss) + (zss * xss) XCTAssert(lhs == rhs) // Identity zip(["xss", "yss", "zss"], [xss, yss, zss]).forEach { let (name, s) = $0 XCTAssert((s * .one) == s, "Right multiplicative identity: \(name)") XCTAssert((.one * s) == s, "Left multiplicative identity: \(name)") XCTAssert((s + .zero) == s, "Right additive identity: \(name)") XCTAssert((.zero + s) == s, "Left additive identity: \(name)") XCTAssert((s * .zero) == .zero, "Right annihilation by zero: \(name)") XCTAssert((.zero * s) == .zero, "Left annihilation by zero: \(name)") } } }
30.837209
84
0.554299
5668739cc61b032e7735efcc7f284564e7b4fbc8
309
// // UIColor.swift // Demo2 // // Created by Łukasz Mróz on 27/06/2020. // Copyright © 2020 Sunshinejr. All rights reserved. // import UIKit extension UIColor { static var demoGray: UIColor { return UIColor(red: 230.0 / 255.0, green: 230.0 / 255.0, blue: 230.0 / 255.0, alpha: 1.0) } }
19.3125
97
0.624595
21ca49cc77ce2ca447be2337cade2d739c4cf7f6
3,326
// RUN: %target-typecheck-verify-swift -enable-library-evolution -warn-concurrency // REQUIRES: concurrency class C1 { } // expected-note{{class 'C1' does not conform to the 'Sendable' protocol}} final class C2: Sendable { } struct S1 { var x: Int var s: String var c: C2 } enum E1 { // expected-note {{consider making enum 'E1' conform to the 'Sendable' protocol}}{{9-9=: Sendable}} case base indirect case nested(E1) } enum E2 { case s1(S1) case c2(C2) } struct GS1<T> { } struct GS2<T> { // expected-note{{consider making generic struct 'GS2' conform to the 'Sendable' protocol}} var storage: T } func acceptCV<T: Sendable>(_: T) { } // Example that was triggering circular dependencies. struct Signature { } struct Data { } struct BlockInfo { } struct Bitcode { // expected-note{{consider making struct 'Bitcode' conform to the 'Sendable' protocol}} let signature: Signature let elements: [BitcodeElement] let blockInfo: [UInt64: BlockInfo] } enum BitcodeElement { struct Block { var id: UInt64 var elements: [BitcodeElement] } struct Record { enum Payload { case none case array([UInt64]) case char6String(String) case blob(Data) } var id: UInt64 var fields: [UInt64] var payload: Payload } case block(Block) case record(Record) } // Public structs and enums do not get implicit Sendable unless they // are frozen. public struct PublicStruct { // expected-note{{consider making struct 'PublicStruct' conform to the 'Sendable' protocol}} var i: Int } public enum PublicEnum { // expected-note{{consider making enum 'PublicEnum' conform to the 'Sendable' protocol}} case some } @frozen public struct FrozenPublicStruct { var i: Int } @frozen public enum FrozenPublicEnum { case some } struct HasFunctions { var tfp: @convention(thin) () -> Void var cfp: @convention(c) () -> Void } @available(SwiftStdlib 5.1, *) @globalActor actor MyGlobalActor { static let shared = MyGlobalActor() } @MyGlobalActor class C3 { } class C4: C3 { } // Make Sendable unavailable, but be sure not to diagnose it. struct S2 { var c1: C1 } @available(*, unavailable) extension S2: Sendable { } func testCV( c1: C1, c2: C2, c3: C3, c4: C4, s1: S1, e1: E1, e2: E2, gs1: GS1<Int>, gs2: GS2<Int>, bc: Bitcode, ps: PublicStruct, pe: PublicEnum, fps: FrozenPublicStruct, fpe: FrozenPublicEnum, hf: HasFunctions ) { acceptCV(c1) // expected-warning{{type 'C1' does not conform to the 'Sendable' protocol}} acceptCV(c2) acceptCV(c3) acceptCV(c4) acceptCV(s1) acceptCV(e1) // expected-warning{{type 'E1' does not conform to the 'Sendable'}} acceptCV(e2) acceptCV(gs1) acceptCV(gs2) // expected-warning{{type 'GS2<Int>' does not conform to the 'Sendable' protocol}} // Not available due to recursive conformance dependencies. acceptCV(bc) // expected-warning{{type 'Bitcode' does not conform to the 'Sendable' protocol}} // Not available due to "public". acceptCV(ps) // expected-warning{{type 'PublicStruct' does not conform to the 'Sendable' protocol}} acceptCV(pe) // expected-warning{{type 'PublicEnum' does not conform to the 'Sendable' protocol}} // Public is okay when also @frozen. acceptCV(fps) acceptCV(fpe) // Thin and C function types are Sendable. acceptCV(hf) }
24.101449
121
0.692423
1de88eb9f1f4322e75cfa7cc51600987032d34b8
7,090
// // TSChatEmotionScollView.swift // YBIMSDK // // Created by apolla on 2020/1/19. // Copyright © 2016 Hilen. All rights reserved. // import Foundation class TSChatEmotionScollView: UICollectionView { fileprivate var touchBeganTime: TimeInterval = 0 fileprivate var touchMoved: Bool = false fileprivate var magnifierImageView: UIImageView! fileprivate var magnifierContentImageView: UIImageView! fileprivate var backspaceTimer: Timer! fileprivate weak var currentMagnifierCell: TSChatEmotionCell? weak var emotionScrollDelegate: ChatEmotionScollViewDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initialize() } func initialize() { self.magnifierImageView = UIImageView(image: TSAsset.Emoticon_keyboard_magnifier.image) self.magnifierContentImageView = UIImageView() self.magnifierContentImageView.size = CGSize(width: 40, height: 40) self.magnifierContentImageView.centerX = self.magnifierImageView.width / 2 self.magnifierImageView.addSubview(self.magnifierContentImageView) self.magnifierImageView.isHidden = true self.addSubview(self.magnifierImageView) } override func awakeFromNib() { self.clipsToBounds = false self.showsHorizontalScrollIndicator = false self.isUserInteractionEnabled = true self.canCancelContentTouches = false self.isMultipleTouchEnabled = false self.scrollsToTop = false } deinit { self.endBackspaceTimer() } /** 按住删除不动,触发 timer */ @objc func startBackspaceTimer() { self.endBackspaceTimer() self.backspaceTimer = Timer.ts_every(0.1, {[weak self] in if self!.currentMagnifierCell!.isDelete { UIDevice.current.playInputClick() self!.emotionScrollDelegate?.emoticonScrollViewDidTapCell(self!.currentMagnifierCell!) } }) RunLoop.main.add(self.backspaceTimer, forMode: RunLoop.Mode.common) } /** 停止 timmer */ func endBackspaceTimer() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(TSChatEmotionScollView.startBackspaceTimer), object: nil) if self.backspaceTimer != nil { self.backspaceTimer.invalidate() self.backspaceTimer = nil } } /** 根据 touch point 获取 Cell - parameter touches: touches - returns: 表情 Cell */ func cellForTouches(_ touches: Set<UITouch>) -> TSChatEmotionCell? { let touch = touches.first as UITouch? let point = touch?.location(in: self) let indexPath = self.indexPathForItem(at: point!) guard let newIndexPath = indexPath else { return nil } let cell: TSChatEmotionCell = self.cellForItem(at: newIndexPath) as! TSChatEmotionCell return cell } /** 隐藏放大镜 */ func hideMagnifierView() { self.magnifierImageView.isHidden = true } /** 显示放大镜 - parameter cell: 将要显示的 cell */ func showMagnifierForCell(_ cell: TSChatEmotionCell) { if cell.isDelete || cell.emotionImageView.image == nil { self.hideMagnifierView() return } let rect: CGRect = cell.convert(cell.bounds, to: self) self.magnifierImageView.center = CGPoint(x: rect.midX, y: self.magnifierImageView.center.y) self.magnifierImageView.bottom = rect.maxY - 6 self.magnifierImageView.isHidden = false self.magnifierContentImageView.image = cell.emotionImageView.image self.magnifierContentImageView.top = 20 self.magnifierContentImageView.layer.removeAllAnimations() let duration: TimeInterval = 0.1 UIView.animate(withDuration: duration, delay: 0, options: .curveEaseIn, animations: { self.magnifierContentImageView.top = 3 }, completion: {finished in UIView.animate(withDuration: duration, delay: 0, options: .curveEaseIn, animations: { self.magnifierContentImageView.top = 6 }, completion: {finished in UIView.animate(withDuration: duration, delay: 0, options: .curveEaseIn, animations: { self.magnifierContentImageView.top = 5 }, completion:nil) }) }) } } // MARK: - @extension TSChatEmotionScollView extension TSChatEmotionScollView { /** touch 响应链 touchesBegan */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchMoved = false // let cell = self.cellForTouches(touches) guard let cell = self.cellForTouches(touches) else { return } self.currentMagnifierCell = cell self.showMagnifierForCell(self.currentMagnifierCell!) if !cell.isDelete && cell.emotionImageView.image != nil { UIDevice.current.playInputClick() } if cell.isDelete { self.endBackspaceTimer() self.perform(#selector(TSChatEmotionScollView.startBackspaceTimer), with: nil, afterDelay: 0.5) } } /** touch 响应链 touchesMoved */ override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchMoved = true if self.currentMagnifierCell != nil && self.currentMagnifierCell!.isDelete { return } guard let cell = self.cellForTouches(touches) else { return } if cell != self.currentMagnifierCell { if !self.currentMagnifierCell!.isDelete && !cell.isDelete { self.currentMagnifierCell = cell } self.showMagnifierForCell(cell) } } /** touch 响应链 touchesEnded */ override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let cell = self.cellForTouches(touches) else { self.endBackspaceTimer() return } let checkCell = !self.currentMagnifierCell!.isDelete && cell.emotionImageView.image != nil let checkMove = !self.touchMoved && cell.isDelete if checkCell || checkMove { self.emotionScrollDelegate?.emoticonScrollViewDidTapCell(self.currentMagnifierCell!) } self.endBackspaceTimer() self.hideMagnifierView() } /** touch 响应链 touchesCancelled */ override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { self.hideMagnifierView() self.endBackspaceTimer() } } /** * 仅供 TSChatEmotionInputView 使用 */ // MARK: - @delgate ChatEmotionScollViewDelegate protocol ChatEmotionScollViewDelegate: class { /** 点击表情 Cell 或者 delete Cell - parameter cell: 表情 cell */ func emoticonScrollViewDidTapCell(_ cell: TSChatEmotionCell) }
32.374429
142
0.629337
2f077ceac9ab57631862cbac7774adb820fe9447
650
// // TrackKit // // Created by Jelle Vandebeeck on 15/03/16. // extension File { convenience init(nmea rawData: [[String]]) throws { // Fetch the type version. let version = try TrackTypeVersion(type: .nmea, version: "NMEA-0183") self.init(type: .nmea, version: version) let points = rawData.compactMap { Point(nmea: $0) } let waypoints = points.filter { $0.recordType?.isWaypoint ?? false } let records = points.filter { !($0.recordType?.isWaypoint ?? false) } self.records = records.count > 0 ? records : nil self.waypoints = waypoints.count > 0 ? waypoints : nil } }
28.26087
77
0.615385
f9062b3570bc88d5471485ddac3b6967a31bd435
1,497
// // UIAlertExtension.swift // CETCPartyBuilding // // Created by gao on 2017/11/30. // Copyright © 2017年 Aaron Yu. All rights reserved. // import Foundation import UIKit extension UIAlertController { //在根视图控制器上弹出普通消息提示框 static func showAlert(message: String) { if let vc = UIApplication.shared.keyWindow?.rootViewController { showAlert(message: message, in: vc) } } //在指定视图控制器上弹出普通消息提示框 static func showAlert(message: String, in viewController: UIViewController) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "确定", style: .cancel)) viewController.present(alert, animated: true) } //在指定视图控制器上弹出确认框 static func showConfirm(message: String, in viewController: UIViewController, confirm: ((UIAlertAction)->Void)?) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "取消", style: .cancel)) alert.addAction(UIAlertAction(title: "确定", style: .default, handler: confirm)) viewController.present(alert, animated: true) } //在根视图控制器上弹出确认框 static func showConfirm(message: String, confirm: ((UIAlertAction)->Void)?) { if let vc = UIApplication.shared.keyWindow?.rootViewController { showConfirm(message: message, in: vc, confirm: confirm) } } }
34.022727
91
0.661991
efd959ed5efcf662fe91ec7d78c4d89f87667f72
545
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck ere T: a : T>(range: Sequence, range.E ") class A { protocol e : start, a(A.b print("A> { struct c, () -> { protocol P { } } func a<h: b var b = a
27.25
79
0.702752
3af0252fca89eaf3a507025772dd6a11610b72e7
157
// // CommonAPI.swift // TodayHeadline // // Created by StevenWu on 2019/11/26. // Copyright © 2019 StevenWu. All rights reserved. // import Foundation
15.7
51
0.687898
08f225904e778f41559d0edbbfc67e94e2affe78
4,740
// // HitsTrackerTests.swift // InstantSearchCore // // Created by Vladislav Fitc on 20/12/2019. // Copyright © 2019 Algolia. All rights reserved. // import Foundation import XCTest @testable import InstantSearchCore class HitsTrackerTests: XCTestCase { struct Constants { static let appID: ApplicationID = "test_app_id" static let apiKey: APIKey = "test_api_key" static let indexName: IndexName = "test index name" static let objectID: ObjectID = "test object id" static let eventName: EventName = "event name" static let customEventName: EventName = "custom event name" static let position = 10 static let queryID: QueryID = "test query id" static let object: [String: JSON] = ["field": "value"] } let searcher = SingleIndexSearcher(appID: Constants.appID, apiKey: Constants.apiKey, indexName: Constants.indexName) let testTracker = TestHitsTracker() lazy var tracker: HitsTracker = { let tracker = HitsTracker(eventName: Constants.eventName, searcher: .singleIndex(searcher), tracker: testTracker) tracker.queryID = Constants.queryID return tracker }() let hit = Hit<[String: JSON]>(object: Constants.object, objectID: Constants.objectID) func testClick() { let clickExpectation = expectation(description: #function) testTracker.didClick = { arg in XCTAssertEqual(arg.eventName, Constants.eventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDsWithPositions.first!.0, Constants.objectID) XCTAssertEqual(arg.objectIDsWithPositions.first!.1, Constants.position) XCTAssertEqual(arg.queryID, Constants.queryID) XCTAssertEqual(arg.userToken, nil) clickExpectation.fulfill() } tracker.trackClick(for: hit, position: Constants.position) waitForExpectations(timeout: 5, handler: .none) } func testClickCustomEventName() { let clickCustomEventExpectation = expectation(description: #function) testTracker.didClick = { arg in XCTAssertEqual(arg.eventName, Constants.customEventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDsWithPositions.first!.0, Constants.objectID) XCTAssertEqual(arg.objectIDsWithPositions.first!.1, Constants.position) XCTAssertEqual(arg.queryID, Constants.queryID) XCTAssertEqual(arg.userToken, nil) clickCustomEventExpectation.fulfill() } tracker.trackClick(for: hit, position: Constants.position, eventName: Constants.customEventName) waitForExpectations(timeout: 5, handler: .none) } func testView() { let viewExpectation = expectation(description: #function) testTracker.didView = { arg in XCTAssertEqual(arg.eventName, Constants.eventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDs.first, Constants.objectID) XCTAssertEqual(arg.userToken, nil) viewExpectation.fulfill() } tracker.trackView(for: hit) waitForExpectations(timeout: 5, handler: .none) } func testViewCustomEventName() { let viewCustomEventExpectation = expectation(description: #function) testTracker.didView = { arg in XCTAssertEqual(arg.eventName, Constants.customEventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDs.first, Constants.objectID) XCTAssertEqual(arg.userToken, nil) viewCustomEventExpectation.fulfill() } tracker.trackView(for: hit, eventName: Constants.customEventName) waitForExpectations(timeout: 5, handler: .none) } func testConvert() { let convertExpectation = expectation(description: #function) testTracker.didConvert = { arg in XCTAssertEqual(arg.eventName, Constants.eventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDs.first, Constants.objectID) XCTAssertEqual(arg.queryID, Constants.queryID) XCTAssertEqual(arg.userToken, nil) convertExpectation.fulfill() } tracker.trackConvert(for: hit) waitForExpectations(timeout: 5, handler: .none) } func textConvertCustomEventName() { let convertCustomEventExpectation = expectation(description: #function) testTracker.didConvert = { arg in XCTAssertEqual(arg.eventName, Constants.customEventName) XCTAssertEqual(arg.indexName, Constants.indexName) XCTAssertEqual(arg.objectIDs.first!, Constants.objectID) XCTAssertEqual(arg.queryID, Constants.queryID) XCTAssertEqual(arg.userToken, nil) convertCustomEventExpectation.fulfill() } tracker.trackConvert(for: hit, eventName: Constants.customEventName) waitForExpectations(timeout: 5, handler: .none) } }
34.852941
118
0.737131
e9ec3d1a9dead43c4d248509a58d5ca5c21d2588
1,235
// // TipsUITests.swift // TipsUITests // // Created by Yuting Zhang on 12/15/15. // Copyright © 2015 Yuting Zhang. All rights reserved. // import XCTest class TipsUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.378378
182
0.659919
d6187c24c403c6d8ee131e8a69724855bb8587b8
399
// // BubbleRocketGame.swift // Swift Alps Game Jam // // Created by Danielle Tomlinson on 23/11/2017. // import Foundation import SpriteKit final class BubbleRocketGame: Game { var name: String { return "Bubble Rocket Game" } var authors: [String] { return ["Dani & Tommy"] } func makeScene() -> SKScene { return BubbleRocketScene(size: UIScreen.main.bounds.size) } }
21
65
0.674185
0a32380e6a858e07cbe71c702efd5db1426f8e9e
20,658
// // RNChartViewBase.swift // reactNativeCharts // // Created by xudong wu on 25/02/2017. // Copyright wuxudong // import UIKit import Charts import SwiftyJSON // In react native, because object-c is unaware of swift protocol extension. use baseClass as workaround @objcMembers open class RNChartViewBase: UIView, ChartViewDelegate { open var onSelect:RCTBubblingEventBlock? open var onChange:RCTBubblingEventBlock? private var group: String? private var identifier: String? private var syncX = true private var syncY = false override public func reactSetFrame(_ frame: CGRect) { super.reactSetFrame(frame); let chartFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) chart.reactSetFrame(chartFrame) } var chart: ChartViewBase { fatalError("subclass should override this function.") } var dataExtract : DataExtract { fatalError("subclass should override this function.") } func setData(_ data: NSDictionary) { let json = BridgeUtils.toJson(data) chart.data = dataExtract.extract(json) } func setLegend(_ config: NSDictionary) { let json = BridgeUtils.toJson(config) let legend = chart.legend; if json["enabled"].bool != nil { legend.enabled = json["enabled"].boolValue; } if json["textColor"].int != nil { legend.textColor = RCTConvert.uiColor(json["textColor"].intValue); } if json["textSize"].number != nil { legend.font = legend.font.withSize(CGFloat(truncating: json["textSize"].numberValue)) } // Wrapping / clipping avoidance if json["wordWrapEnabled"].bool != nil { legend.wordWrapEnabled = json["wordWrapEnabled"].boolValue } if json["maxSizePercent"].number != nil { legend.maxSizePercent = CGFloat(truncating: json["maxSizePercent"].numberValue) } if json["horizontalAlignment"].string != nil { legend.horizontalAlignment = BridgeUtils.parseLegendHorizontalAlignment(json["horizontalAlignment"].stringValue) } if json["verticalAlignment"].string != nil { legend.verticalAlignment = BridgeUtils.parseLegendVerticalAlignment(json["verticalAlignment"].stringValue) } if json["orientation"].string != nil { legend.orientation = BridgeUtils.parseLegendOrientation(json["orientation"].stringValue) } if json["drawInside"].bool != nil { legend.drawInside = json["drawInside"].boolValue } if json["direction"].string != nil { legend.direction = BridgeUtils.parseLegendDirection(json["direction"].stringValue) } if let font = FontUtils.getFont(json) { legend.font = font } if json["form"].string != nil { legend.form = BridgeUtils.parseLegendForm(json["form"].stringValue) } if json["formSize"].number != nil { legend.formSize = CGFloat(truncating: json["formSize"].numberValue) } if json["xEntrySpace"].number != nil { legend.xEntrySpace = CGFloat(truncating: json["xEntrySpace"].numberValue) } if json["yEntrySpace"].number != nil { legend.yEntrySpace = CGFloat(truncating: json["yEntrySpace"].numberValue) } if json["formToTextSpace"].number != nil { legend.formToTextSpace = CGFloat(truncating: json["formToTextSpace"].numberValue) } // Custom labels & colors if json["custom"].exists() { let customMap = json["custom"] if customMap["colors"].exists() && customMap["labels"].exists() { let colorsArray = customMap["colors"].arrayValue let labelsArray = customMap["labels"].arrayValue if colorsArray.count == labelsArray.count { // TODO null label should start a group // TODO -2 color should avoid drawing a form var legendEntries = [LegendEntry](); for i in 0..<labelsArray.count { let legendEntry = LegendEntry() legendEntry.formColor = RCTConvert.uiColor(colorsArray[i].intValue); legendEntry.label = labelsArray[i].stringValue; legendEntries.append(legendEntry) } legend.setCustom(entries: legendEntries) } } } // TODO extra } func setChartBackgroundColor(_ backgroundColor: Int) { chart.backgroundColor = RCTConvert.uiColor(backgroundColor) } func setChartDescription(_ config: NSDictionary) { let json = BridgeUtils.toJson(config) let chartDescription = Description() if json["text"].string != nil { chartDescription.text = json["text"].stringValue } if json["textColor"].int != nil { chartDescription.textColor = RCTConvert.uiColor(json["textColor"].intValue) } if json["textSize"].float != nil { chartDescription.font = chartDescription.font.withSize(CGFloat(json["textSize"].floatValue)) } if json["positionX"].number != nil && json["positionY"].number != nil { chartDescription.position = CGPoint(x: CGFloat(truncating: json["positionX"].numberValue), y: CGFloat(truncating: json["positionY"].numberValue)) } chart.chartDescription = chartDescription } func setNoDataText(_ noDataText: String) { chart.noDataText = noDataText } func setTouchEnabled(_ touchEnabled: Bool) { chart.isUserInteractionEnabled = touchEnabled } func setHighlightPerTapEnabled(_ enabled: Bool) { chart.highlightPerTapEnabled = enabled } func setDragDecelerationEnabled(_ dragDecelerationEnabled: Bool) { chart.dragDecelerationEnabled = dragDecelerationEnabled } func setDragDecelerationFrictionCoef(_ dragDecelerationFrictionCoef: NSNumber) { chart.dragDecelerationFrictionCoef = CGFloat(truncating: dragDecelerationFrictionCoef) } func setAnimation(_ config: NSDictionary) { let json = BridgeUtils.toJson(config) let durationX = json["durationX"].double != nil ? json["durationX"].doubleValue / 1000.0 : 0 let durationY = json["durationY"].double != nil ? json["durationY"].doubleValue / 1000.0 : 0 var easingX: ChartEasingOption = .linear var easingY: ChartEasingOption = .linear if json["easingX"].string != nil { easingX = BridgeUtils.parseEasingOption(json["easingX"].stringValue) } if json["easingY"].string != nil { easingY = BridgeUtils.parseEasingOption(json["easingY"].stringValue) } if durationX != 0 && durationY != 0 { chart.animate(xAxisDuration: durationX, yAxisDuration: durationY, easingOptionX: easingX, easingOptionY: easingY) } else if (durationX != 0) { chart.animate(xAxisDuration: durationX, easingOption: easingX) } else if (durationY != 0) { chart.animate(yAxisDuration: durationY, easingOption: easingY) } } func setXAxis(_ config: NSDictionary) { let json = BridgeUtils.toJson(config) let xAxis = chart.xAxis; setCommonAxisConfig(xAxis, config: json) if json["labelRotationAngle"].number != nil { xAxis.labelRotationAngle = CGFloat(truncating: json["labelRotationAngle"].numberValue) } if json["avoidFirstLastClipping"].bool != nil { xAxis.avoidFirstLastClippingEnabled = json["avoidFirstLastClipping"].boolValue } if json["position"].string != nil { xAxis.labelPosition = BridgeUtils.parseXAxisLabelPosition(json["position"].stringValue) } if json["yOffset"].number != nil { xAxis.yOffset = CGFloat(truncating: json["yOffset"].numberValue) } } func setCommonAxisConfig(_ axis: AxisBase, config: JSON) { // what is drawn if config["enabled"].bool != nil { axis.enabled = config["enabled"].boolValue } if config["drawLabels"].bool != nil { axis.drawLabelsEnabled = config["drawLabels"].boolValue } if config["drawAxisLine"].bool != nil { axis.drawAxisLineEnabled = config["drawAxisLine"].boolValue } if config["drawGridLines"].bool != nil { axis.drawGridLinesEnabled = config["drawGridLines"].boolValue } // style if let font = FontUtils.getFont(config) { axis.labelFont = font } if config["textColor"].int != nil { axis.labelTextColor = RCTConvert.uiColor(config["textColor"].intValue) } if config["textSize"].float != nil { axis.labelFont = axis.labelFont.withSize(CGFloat(config["textSize"].floatValue)) } if config["gridColor"].int != nil { axis.gridColor = RCTConvert.uiColor(config["gridColor"].intValue) } if config["gridLineWidth"].number != nil { axis.gridLineWidth = CGFloat(truncating: config["gridLineWidth"].numberValue) } if config["axisLineColor"].int != nil { axis.axisLineColor = RCTConvert.uiColor(config["axisLineColor"].intValue) } if config["axisLineWidth"].number != nil { axis.axisLineWidth = CGFloat(truncating: config["axisLineWidth"].numberValue) } if config["gridDashedLine"].exists() { let gridDashedLine = config["gridDashedLine"] var lineLength = CGFloat(0) var spaceLength = CGFloat(0) if gridDashedLine["lineLength"].number != nil { lineLength = CGFloat(truncating: gridDashedLine["lineLength"].numberValue) } if gridDashedLine["spaceLength"].number != nil { spaceLength = CGFloat(truncating: gridDashedLine["spaceLength"].numberValue) } if gridDashedLine["phase"].number != nil { axis.gridLineDashPhase = CGFloat(truncating: gridDashedLine["phase"].numberValue) } axis.gridLineDashLengths = [lineLength, spaceLength] } // limit lines if config["limitLines"].array != nil { let limitLinesConfig = config["limitLines"].arrayValue axis.removeAllLimitLines() for limitLineConfig in limitLinesConfig { if limitLineConfig["limit"].double != nil { let limitLine = ChartLimitLine(limit: limitLineConfig["limit"].doubleValue) if limitLineConfig["label"].string != nil { limitLine.label = limitLineConfig["label"].stringValue } if (limitLineConfig["lineColor"].int != nil) { limitLine.lineColor = RCTConvert.uiColor(limitLineConfig["lineColor"].intValue) } if (limitLineConfig["valueTextColor"].int != nil) { limitLine.valueTextColor = RCTConvert.uiColor(limitLineConfig["valueTextColor"].intValue) } if (limitLineConfig["valueFont"].int != nil) { limitLine.valueFont = NSUIFont.systemFont(ofSize: CGFloat(limitLineConfig["valueFont"].intValue)) } if limitLineConfig["lineWidth"].number != nil { limitLine.lineWidth = CGFloat(truncating: limitLineConfig["lineWidth"].numberValue) } if limitLineConfig["labelPosition"].string != nil { limitLine.labelPosition = BridgeUtils.parseLimitlineLabelPosition(limitLineConfig["labelPosition"].stringValue); } if limitLineConfig["lineDashPhase"].float != nil { limitLine.lineDashPhase = CGFloat(limitLineConfig["lineDashPhase"].floatValue); } if limitLineConfig["lineDashLengths"].arrayObject != nil { limitLine.lineDashLengths = limitLineConfig["lineDashLengths"].arrayObject as? [CGFloat]; } axis.addLimitLine(limitLine) } } } if config["drawLimitLinesBehindData"].bool != nil { axis.drawLimitLinesBehindDataEnabled = config["drawLimitLinesBehindData"].boolValue } if config["axisMaximum"].double != nil { axis.axisMaximum = config["axisMaximum"].doubleValue } if config["axisMinimum"].double != nil { axis.axisMinimum = config["axisMinimum"].doubleValue } if config["granularity"].double != nil { axis.granularity = config["granularity"].doubleValue } if config["granularityEnabled"].bool != nil { axis.granularityEnabled = config["granularityEnabled"].boolValue } if config["labelCount"].int != nil { var labelCountForce = false if config["labelCountForce"].bool != nil { labelCountForce = config["labelCountForce"].boolValue } axis.setLabelCount(config["labelCount"].intValue, force: labelCountForce) } // formatting // TODO: other formatting options let valueFormatter = config["valueFormatter"]; if valueFormatter.array != nil { axis.valueFormatter = IndexAxisValueFormatter(values: valueFormatter.arrayValue.map({ $0.stringValue })) } else if valueFormatter.string != nil { if "largeValue" == valueFormatter.stringValue { axis.valueFormatter = LargeValueFormatter(); } else if "percent" == valueFormatter.stringValue { let percentFormatter = NumberFormatter() percentFormatter.numberStyle = .percent axis.valueFormatter = DefaultAxisValueFormatter(formatter: percentFormatter); } else if "date" == valueFormatter.stringValue { let valueFormatterPattern = config["valueFormatterPattern"].stringValue; let since = config["since"].double != nil ? config["since"].doubleValue : 0 let timeUnit = config["timeUnit"].string != nil ? config["timeUnit"].stringValue : "MILLISECONDS" let locale = config["locale"].string; axis.valueFormatter = CustomChartDateFormatter(pattern: valueFormatterPattern, since: since, timeUnit: timeUnit, locale: locale); } else { let customFormatter = NumberFormatter() customFormatter.positiveFormat = valueFormatter.stringValue customFormatter.negativeFormat = valueFormatter.stringValue axis.valueFormatter = DefaultAxisValueFormatter(formatter: customFormatter); } } if config["centerAxisLabels"].bool != nil { axis.centerAxisLabelsEnabled = config["centerAxisLabels"].boolValue } } func setMarker(_ config: NSDictionary) { let json = BridgeUtils.toJson(config) if json["enabled"].exists() && !json["enabled"].boolValue { chart.marker = nil return } var markerFont = UIFont.systemFont(ofSize: 12.0) if json["textSize"].float != nil { markerFont = markerFont.withSize(CGFloat(json["textSize"].floatValue)) } // TODO fontFamily, fontStyle let balloonMarker = BalloonMarker( color: RCTConvert.uiColor(json["markerColor"].intValue), font: markerFont, textColor: RCTConvert.uiColor(json["textColor"].intValue)) chart.marker = balloonMarker balloonMarker.chartView = chart } func setHighlights(_ config: NSArray) { chart.highlightValues(HighlightUtils.getHighlights(config)) } @objc public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { if self.onSelect == nil { return } else { self.onSelect!(EntryToDictionaryUtils.entryToDictionary(entry)) } } @objc public func chartValueNothingSelected(_ chartView: ChartViewBase) { if self.onSelect == nil { return } else { self.onSelect!(nil) } } @objc public func chartScaled(_ chartView: ChartViewBase, scaleX: CoreGraphics.CGFloat, scaleY: CoreGraphics.CGFloat) { sendEvent("chartScaled") } @objc public func chartTranslated(_ chartView: ChartViewBase, dX: CoreGraphics.CGFloat, dY: CoreGraphics.CGFloat) { sendEvent("chartTranslated") } func sendEvent(_ action:String) { var dict = [AnyHashable: Any]() dict["action"] = action if chart is BarLineChartViewBase { let viewPortHandler = chart.viewPortHandler let barLineChart = chart as! BarLineChartViewBase dict["scaleX"] = barLineChart.scaleX dict["scaleY"] = barLineChart.scaleY if let handler = viewPortHandler { let center = barLineChart.valueForTouchPoint(point: handler.contentCenter, axis: YAxis.AxisDependency.left) dict["centerX"] = center.x dict["centerY"] = center.y let leftBottom = barLineChart.valueForTouchPoint(point: CGPoint(x: handler.contentLeft, y: handler.contentBottom), axis: YAxis.AxisDependency.left) let rightTop = barLineChart.valueForTouchPoint(point: CGPoint(x: handler.contentRight, y: handler.contentTop), axis: YAxis.AxisDependency.left) dict["left"] = leftBottom.x dict["bottom"] = leftBottom.y dict["right"] = rightTop.x dict["top"] = rightTop.y if self.group != nil && self.identifier != nil { ChartGroupHolder.sync(group: self.group!, identifier: self.identifier!, scaleX: barLineChart.scaleX, scaleY: barLineChart.scaleY, centerX: center.x, centerY: center.y, performImmediately: true) } } } if self.onChange == nil { return } else { self.onChange!(dict) } } func setGroup(_ group: String) { self.group = group } func setIdentifier(_ identifier: String) { self.identifier = identifier } func setSyncX(_ syncX: Bool) { self.syncX = syncX } func setSyncY(_ syncY: Bool) { self.syncY = syncY } func onAfterDataSetChanged() { } override public func didSetProps(_ changedProps: [String]!) { super.didSetProps(changedProps) chart.notifyDataSetChanged() onAfterDataSetChanged() if self.group != nil && self.identifier != nil && chart is BarLineChartViewBase { ChartGroupHolder.addChart(group: self.group!, identifier: self.identifier!, chart: chart as! BarLineChartViewBase, syncX: syncX, syncY: syncY); } } }
37.021505
213
0.567722
75bbb379f6e7ceedabdca5641575cba7b273dad5
4,262
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="CopyFolderRequest.swift"> * Copyright (c) 2020 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // Request model for copyFolder operation. public class CopyFolderRequest : WordsApiRequest { private let destPath : String; private let srcPath : String; private let srcStorageName : String?; private let destStorageName : String?; private enum CodingKeys: String, CodingKey { case destPath; case srcPath; case srcStorageName; case destStorageName; case invalidCodingKey; } // Initializes a new instance of the CopyFolderRequest class. public init(destPath : String, srcPath : String, srcStorageName : String? = nil, destStorageName : String? = nil) { self.destPath = destPath; self.srcPath = srcPath; self.srcStorageName = srcStorageName; self.destStorageName = destStorageName; } // Destination folder path e.g. '/dst'. public func getDestPath() -> String { return self.destPath; } // Source folder path e.g. /Folder1. public func getSrcPath() -> String { return self.srcPath; } // Source storage name. public func getSrcStorageName() -> String? { return self.srcStorageName; } // Destination storage name. public func getDestStorageName() -> String? { return self.destStorageName; } // Creates the api request data public func createApiRequestData(configuration : Configuration) throws -> WordsApiRequestData { var rawPath = "/words/storage/folder/copy/{srcPath}"; rawPath = rawPath.replacingOccurrences(of: "{srcPath}", with: try ObjectSerializer.serializeToString(value: self.getSrcPath())); rawPath = rawPath.replacingOccurrences(of: "//", with: "/"); let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath); var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!; var queryItems : [URLQueryItem] = []; queryItems.append(URLQueryItem(name: "destPath", value: try ObjectSerializer.serializeToString(value: self.getDestPath()))); if (self.getSrcStorageName() != nil) { queryItems.append(URLQueryItem(name: "srcStorageName", value: try ObjectSerializer.serializeToString(value: self.getSrcStorageName()!))); } if (self.getDestStorageName() != nil) { queryItems.append(URLQueryItem(name: "destStorageName", value: try ObjectSerializer.serializeToString(value: self.getDestStorageName()!))); } if (queryItems.count > 0) { urlBuilder.queryItems = queryItems; } let result = WordsApiRequestData(url: urlBuilder.url!, method: "PUT"); return result; } // Deserialize response of this request public func deserializeResponse(data : Data) throws -> Any? { return nil; } }
40.207547
152
0.657907
e0c1bfb13ece76019117d0f715d87da58b2d6b30
12,804
// // COINSettingInfoTableViewCell.swift // Coin // // Created by gm on 2018/11/27. // Copyright © 2018年 COIN. All rights reserved. // import UIKit class COINSettingInfoModel: COINBaseModel { /// 图片名字 rootsymbol var imageName: String = "" /// 合约名称 var symbol: String = "" /// 权益保证金 var marginBalance: Float = 1.0 /// 委托保证金 var initMargin: Float = 0 /// 仓位保证金 var maintMargin: Float = 0 ///已实现盈亏 var realisedPnl: Float = 0 /// 为实现盈亏 var unrealisedPnl: Float = 0 /// 可用保证金 var availableMargin: Float = 0 } class COINSettingInfoTableViewCell: UITableViewCell { lazy var currencyImageView: UIImageView = { let currencyImageView = UIImageView() currencyImageView.contentMode = .left return currencyImageView }() lazy var symbolLabel: UILabel = { let symbolLabel = UILabel() symbolLabel.text = "XBT" return symbolLabel }() ///"总权益" lazy var totalEquityValueLabel: UILabel = { let totalEquityLabel = UILabel() totalEquityLabel.textAlignment = .right totalEquityLabel.text = "6500.00" totalEquityLabel.font = font12 return totalEquityLabel }() private lazy var totalEquityLabel: UILabel = { let totalEquityLabel = UILabel() totalEquityLabel.text = "总权益" totalEquityLabel.textAlignment = .right totalEquityLabel.textColor = titleGrayColor totalEquityLabel.font = font12 return totalEquityLabel }() ///保证进率(%) lazy var progressValueLabel: UILabel = { let progressLabel = UILabel() progressLabel.text = "50%" progressLabel.textAlignment = .left progressLabel.font = font12 return progressLabel }() private lazy var progressLabel: UILabel = { let progressLabel = UILabel() progressLabel.textAlignment = .left progressLabel.textColor = titleGrayColor progressLabel.text = "保证进率(%)" progressLabel.font = font12 return progressLabel }() /// 已用保证金(BTC) lazy var marginPaidValueLabel: UILabel = { let marginPaidLabel = UILabel() marginPaidLabel.text = "0.004BTC" marginPaidLabel.font = font12 return marginPaidLabel }() private lazy var marginPaidLabel: UILabel = { let marginPaidLabel = UILabel() marginPaidLabel.text = "已用保证金" marginPaidLabel.textColor = titleGrayColor marginPaidLabel.font = font12 return marginPaidLabel }() /// 已实现盈亏 lazy var realisedPnlValueLabel: UILabel = { let profitAndLossLabel = UILabel() profitAndLossLabel.text = "0.005BTC" profitAndLossLabel.textAlignment = .right profitAndLossLabel.font = font12 return profitAndLossLabel }() private lazy var realisedPnlLabel: UILabel = { let profitAndLossLabel = UILabel() profitAndLossLabel.text = "已实现盈亏" profitAndLossLabel.textAlignment = .right profitAndLossLabel.textColor = titleGrayColor profitAndLossLabel.font = font12 return profitAndLossLabel }() /// 未实现盈亏 lazy var unrealisedPnlValueLabel: UILabel = { let unrealisedPnlLabel = UILabel() unrealisedPnlLabel.text = "0.006BTC" unrealisedPnlLabel.textAlignment = .right unrealisedPnlLabel.font = font12 return unrealisedPnlLabel }() private lazy var unrealisedPnlLabel: UILabel = { let unrealisedPnlLabel = UILabel() unrealisedPnlLabel.text = "未实现盈亏" unrealisedPnlLabel.textAlignment = .right unrealisedPnlLabel.textColor = titleGrayColor unrealisedPnlLabel.font = font12 return unrealisedPnlLabel }() /// 可用保证金lablel lazy var availableMarginValueLabel: UILabel = { let availableMarginValueLabel = UILabel() availableMarginValueLabel.text = "0.006BTC" availableMarginValueLabel.textAlignment = .right availableMarginValueLabel.font = font12 return availableMarginValueLabel }() private lazy var availableMarginLabel: UILabel = { let availableMarginLabel = UILabel() availableMarginLabel.text = "可用保证金" availableMarginLabel.textAlignment = .right availableMarginLabel.textColor = titleGrayColor availableMarginLabel.font = font12 return availableMarginLabel }() /// 冻结保证金lablel lazy var freezeMarginValueLabel: UILabel = { let freezeMarginValueLabel = UILabel() freezeMarginValueLabel.text = "0.006BTC" freezeMarginValueLabel.textAlignment = .right freezeMarginValueLabel.font = font12 return freezeMarginValueLabel }() private lazy var freezeMarginLabel: UILabel = { let freezeMarginLabel = UILabel() freezeMarginLabel.text = "冻结保证金" freezeMarginLabel.textAlignment = .right freezeMarginLabel.textColor = titleGrayColor freezeMarginLabel.font = font12 return freezeMarginLabel }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none addSubviews() } func addSubviews(){ self.addSubview(self.currencyImageView) self.addSubview(self.symbolLabel) self.addSubview(self.totalEquityLabel) self.addSubview(self.totalEquityValueLabel) // self.addSubview(self.progressLabel) // self.addSubview(self.progressValueLabel) self.addSubview(self.marginPaidLabel) self.addSubview(self.marginPaidValueLabel) self.addSubview(self.realisedPnlLabel) self.addSubview(self.realisedPnlValueLabel) // self.addSubview(self.unrealisedPnlLabel) // self.addSubview(self.unrealisedPnlValueLabel) self.addSubview(self.availableMarginLabel) self.addSubview(self.availableMarginValueLabel) self.addSubview(self.freezeMarginLabel) self.addSubview(self.freezeMarginValueLabel) } override func layoutSubviews() { super.layoutSubviews() let hSpeing: CGFloat = 20 let labelH : CGFloat = 20 let width = UIScreen.main.bounds.size.width currencyImageView.snp.makeConstraints { (maker) in maker.top.equalToSuperview().offset(hSpeing) maker.left.equalToSuperview().offset(hSpeing) maker.width.equalTo(20) maker.height.equalTo(20) } let symbolLabelOffset = width * 2 / 3 * -1 symbolLabel.snp.makeConstraints { (maker) in maker.left.equalTo(currencyImageView.snp.right).offset(10) maker.centerY.equalTo(currencyImageView.snp.centerY) maker.right.equalTo(self.snp.right).offset(symbolLabelOffset) maker.height.equalTo(labelH) } let middleOffset = width / 3 * -1 realisedPnlLabel.snp.makeConstraints { (maker) in maker.left.equalTo(symbolLabel.snp.left) maker.top.equalTo(symbolLabel.snp.top) maker.right.equalTo(self.snp.right).offset(middleOffset) maker.height.equalTo(labelH) } realisedPnlValueLabel.snp.makeConstraints { (maker) in maker.left.equalTo(realisedPnlLabel.snp.left) maker.top.equalTo(realisedPnlLabel.snp.bottom).offset(-3) maker.right.equalTo(realisedPnlLabel.snp.right) maker.height.equalTo(labelH) } totalEquityLabel.snp.makeConstraints { (maker) in maker.right.equalToSuperview().offset(hSpeing * -1) maker.centerY.equalTo(currencyImageView.snp.centerY) maker.height.equalTo(labelH) } totalEquityValueLabel.snp.makeConstraints { (maker) in maker.right.equalTo(totalEquityLabel.snp.right) maker.top.equalTo(totalEquityLabel.snp.bottom).offset(-3) maker.height.equalTo(labelH) } // unrealisedPnlLabel.snp.makeConstraints { (maker) in // maker.top.equalTo(totalEquityValueLabel.snp.bottom).offset(v) // maker.right.equalTo(totalEquityValueLabel.snp.right) // maker.height.equalTo(labelH) // } // unrealisedPnlValueLabel.snp.makeConstraints { (maker) in // maker.top.equalTo(marginPaidValueLabel.snp.top) // maker.right.equalTo(unrealisedPnlLabel.snp.right) // maker.height.equalTo(labelH) // } freezeMarginLabel.snp.makeConstraints { (maker) in maker.right.equalTo(totalEquityValueLabel.snp.right) maker.top.equalTo(totalEquityValueLabel.snp.bottom).offset(hSpeing * 0.5) maker.height.equalTo(labelH) } freezeMarginValueLabel.snp.makeConstraints { (maker) in maker.right.equalTo(freezeMarginLabel.snp.right) maker.top.equalTo(marginPaidValueLabel.snp.top) maker.height.equalTo(labelH) } marginPaidLabel.snp.makeConstraints { (maker) in maker.left.equalTo(currencyImageView.snp.left) maker.top.equalTo(freezeMarginLabel.snp.top) maker.right.equalTo(symbolLabel.snp.right) maker.height.equalTo(labelH) } marginPaidValueLabel.snp.makeConstraints { (maker) in maker.left.equalTo(marginPaidLabel.snp.left) maker.top.equalTo(marginPaidLabel.snp.bottom).offset(-3) maker.right.equalTo(marginPaidLabel.snp.right) maker.height.equalTo(labelH) } // progressLabel.snp.makeConstraints { (maker) in // maker.top.equalTo(marginPaidValueLabel.snp.bottom).offset(hSpeing) // maker.left.equalTo(marginPaidValueLabel.snp.left) // maker.width.equalTo(marginPaidValueLabel.snp.width) // maker.height.equalTo(labelH) // } // progressValueLabel.snp.makeConstraints { (maker) in // maker.right.equalTo(progressLabel.snp.right) // maker.top.equalTo(progressLabel.snp.bottom).offset(-3) // maker.width.equalTo(progressLabel.snp.width) // maker.height.equalTo(labelH) // } availableMarginLabel.snp.makeConstraints { (maker) in maker.right.equalTo(realisedPnlValueLabel.snp.right) maker.top.equalTo(marginPaidLabel.snp.top) maker.width.equalTo(realisedPnlValueLabel.snp.width) maker.height.equalTo(labelH) } availableMarginValueLabel.snp.makeConstraints { (maker) in maker.right.equalTo(availableMarginLabel.snp.right) maker.top.equalTo(marginPaidValueLabel.snp.top) maker.width.equalTo(availableMarginLabel.snp.width) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 给COINSettingInfoTableViewCell赋值 var model: COINSettingInfoModel? { didSet{ self.currencyImageView.image = UIImage.init(named:"currency_\(model?.imageName.lowercased() ?? "")") self.symbolLabel.text = model?.symbol //保证金余额 let marginBalance: Float = model?.marginBalance ?? 0.0 //MARK: 计算保证进率 //委托保证金 let initMargin: Float = model?.initMargin ?? 0.0 //仓位保证金 let maintMargin: Float = model?.maintMargin ?? 0.0 //已实现盈亏 let realisedPnl: Float = model?.realisedPnl ?? 0.0 //未实现盈亏 let unrealisedPnl: Float = model?.unrealisedPnl ?? 0.0 //计算保证进率 =(可用保证金) / 保证金余额 // let progressValue = (maintMargin + initMargin) / marginBalance // self.progressValueLabel.text = progressValue.pecnStr() self.totalEquityValueLabel.text = marginBalance.eightDecimalPlacesWithUnits() self.marginPaidValueLabel.text = (maintMargin + initMargin).eightDecimalPlacesWithUnits() self.availableMarginValueLabel.text = model?.availableMargin.eightDecimalPlacesWithUnits() self.freezeMarginValueLabel.text = initMargin.eightDecimalPlacesWithUnits() self.unrealisedPnlValueLabel.text = unrealisedPnl.eightDecimalPlacesWithUnits() self.realisedPnlValueLabel.text = realisedPnl.eightDecimalPlacesWithUnits() } } }
36.687679
112
0.631756
1c2d9520d6d238e6fe36206c10e3764accaf6bbe
1,214
// // appUITests.swift // appUITests // // Created by 单琦 on 2018/5/31. // Copyright © 2018年 单琦. All rights reserved. // import XCTest class appUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
32.810811
182
0.655684
03c5dc35f2bb8d85e74590a49a822c85cb00472a
887
// // NilFactory.swift // RouteComposer // // Created by Eugene Kazaev on 08/02/2018. // import Foundation import UIKit /// Dummy struct to be provided to an assembly to show that this step should not have any factories /// The only purpose it exists is to provide type safety checks for `StepAssembly`. /// /// For example, `UIViewController` of this step was already loaded and integrated into a stack by a /// storyboard. public struct NilFactory<VC: UIViewController, C>: Factory, NilEntity { public typealias ViewController = VC public typealias Context = C public let action: Action /// Constructor public init(action: Action = GeneralAction.NilAction()) { self.action = action } public func build(with context: Context) throws -> ViewController { throw RoutingError.message("This factory should never reach router.") } }
26.088235
100
0.709132
8f93d6f68caf6945bdcbdf33bbafe0151a68cb9d
3,571
// // personalData.swift // CalorieCounterApp // // Created by Timal Pathirana on 27/8/20. //E29E4D import UIKit import Foundation enum Colors { static let orangeColour = UIColor(red: 238/255, green: 154/255, blue: 57/255, alpha: 1.0) static let blueColour = UIColor(red: 78/255, green: 85/255, blue: 116/255, alpha: 1.0) static let redColour = UIColor(red: 255/255, green: 44/255, blue: 85/255, alpha: 1.0) } enum Gender { case Male , Female } enum Goal :String{ case loseWeight = "Loss Weight", gainWeight = "Gain Weight", maintainWeight = "Maintain Weight" } enum ActivityLevel:String { case sedentary = "Sedentary", lightlyActive = "lightly Active", active = "Active", veryActive = "Very Active" } struct personalInfoSet { private var name: String private var currentWeight:Double private var currentHeight:Double private var genderType:Gender? private var userGoal:Goal? private var userActive:ActivityLevel? init(name:String, currentWeight:Double, currentHeight:Double, genderType: Gender? , userGoal:Goal?, userActive:ActivityLevel?) { self.name = name self.currentHeight = currentHeight self.currentWeight = currentWeight self.genderType = genderType self.userGoal = userGoal self.userActive = userActive } var getName: String { get { return name } } func calculateBMI() -> Int { let bmi = (Int(currentWeight/(currentHeight)) ^ 2) * 703 return bmi } func getCalories() -> Int { let bmicount = calculateBMI() if bmicount < Int(18.5) { return 1 } else if bmicount < Int(24.5) && bmicount >= Int(18.5) { return 2 } else if bmicount < Int(29) && bmicount >= Int(24.5) { return 3 } else if bmicount >= Int(29) { return 4 } return 0 } func printCalorie() -> String{ if getCalories() == 1 { return "Nice" } else { return "Bad" } } //var clientData = personalInfoSet(name: "David", currentWeight: 80, currentHeight: 178, genderType: Gender.Male, userGoal: Goal.gainWeight, userActive: ActivityLevel.active) /* ------------------------------------------------------------------------------------------------------------*/ struct CustomDate{ // Marked as optional as invalid construction data will produce a nil value private var date:Date? init(day:Int, month:Int, year:Int, timeZone:TimeZone = .current){ var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month dateComponents.timeZone = timeZone let userCalendar = Calendar.current // Swift API here can return an Optional Value date = userCalendar.date(from: dateComponents) } // Default value if the user does not provide a format func formatted(as format: String = "dd-MM-yyyy") -> String? { // Early termination if date has not been initialised guard let date = self.date else {return nil} let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: date) } } }
26.849624
178
0.561187
145015c3b16c81cfa31b85da3efac7f1839d772e
544
// // EventRating+CoreDataProperties.swift // Signal GH // // Created by Glenn Howes on 4/7/17. // Copyright © 2017 Generally Helpful Software. All rights reserved. // import Foundation import CoreData extension EventRating { @nonobjc public class func fetchRequest() -> NSFetchRequest<EventRating> { return NSFetchRequest<EventRating>(entityName: "EventRating") } @NSManaged public var ratingIndex: NSNumber? @NSManaged public var ratingValue: NSNumber? @NSManaged public var advisory: ContentAdvisory? }
22.666667
78
0.729779
9cd7923db929e636bad8583ed15324bebb6eb3aa
793
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "helloworld", dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "helloworld", dependencies: []), .testTarget( name: "helloworldTests", dependencies: ["helloworld"]), ] )
34.478261
116
0.630517
3336d7bbeea43ecea2d9932512d84d3f00dbda45
1,571
// The MIT License (MIT) // Copyright © 2022 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. extension SFSymbol { public static var r1: R1 { .init(name: "r1") } open class R1: SFSymbol { @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var rectangleRoundedbottom: SFSymbol { ext(.start.rectangle + ".roundedbottom") } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) open var rectangleRoundedbottomFill: SFSymbol { ext(.start.rectangle + ".roundedbottom".fill) } } }
47.606061
97
0.744112
d67ec719db439fa1b9c79bdf7c8d002cbd191aae
21,607
// // ZIPFoundationTests.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import XCTest @testable import ZIPFoundation enum AdditionalDataError: Error { case encodingError case invalidDataError } class ZIPFoundationTests: XCTestCase { class var testBundle: Bundle { return Bundle(for: self) } static var tempZipDirectoryURL: URL = { let processInfo = ProcessInfo.processInfo var tempZipDirectory = URL(fileURLWithPath: NSTemporaryDirectory()) tempZipDirectory.appendPathComponent("ZipTempDirectory") // We use a unique path to support parallel test runs via // "swift test --parallel" // When using --parallel, setUp() and tearDown() are called // multiple times. tempZipDirectory.appendPathComponent(processInfo.globallyUniqueString) return tempZipDirectory }() static var resourceDirectoryURL: URL { var resourceDirectoryURL = URL(fileURLWithPath: #file) resourceDirectoryURL.deleteLastPathComponent() resourceDirectoryURL.appendPathComponent("Resources") return resourceDirectoryURL } override class func setUp() { super.setUp() do { let fileManager = FileManager() if fileManager.itemExists(at: tempZipDirectoryURL) { try fileManager.removeItem(at: tempZipDirectoryURL) } try fileManager.createDirectory(at: tempZipDirectoryURL, withIntermediateDirectories: true, attributes: nil) } catch { XCTFail("Unexpected error while trying to set up test resources.") } // TODO: Setup empty in-memory archive for testing here. } override class func tearDown() { do { let fileManager = FileManager() try fileManager.removeItem(at: tempZipDirectoryURL) } catch { XCTFail("Unexpected error while trying to clean up test resources.") } super.tearDown() } func testArchiveReadErrorConditions() { let nonExistantURL = URL(fileURLWithPath: "/nothing") let nonExistantArchive = Archive(url: nonExistantURL, accessMode: .read) XCTAssertNil(nonExistantArchive) var unreadableArchiveURL = ZIPFoundationTests.tempZipDirectoryURL let processInfo = ProcessInfo.processInfo unreadableArchiveURL.appendPathComponent(processInfo.globallyUniqueString) let noPermissionAttributes = [FileAttributeKey.posixPermissions: NSNumber(value: Int16(0o000))] let fileManager = FileManager() var result = fileManager.createFile(atPath: unreadableArchiveURL.path, contents: nil, attributes: noPermissionAttributes) XCTAssert(result == true) let unreadableArchive = Archive(url: unreadableArchiveURL, accessMode: .read) XCTAssertNil(unreadableArchive) var noEndOfCentralDirectoryArchiveURL = ZIPFoundationTests.tempZipDirectoryURL noEndOfCentralDirectoryArchiveURL.appendPathComponent(processInfo.globallyUniqueString) let fullPermissionAttributes = [FileAttributeKey.posixPermissions: NSNumber(value: defaultFilePermissions)] result = fileManager.createFile(atPath: noEndOfCentralDirectoryArchiveURL.path, contents: nil, attributes: fullPermissionAttributes) XCTAssert(result == true) let noEndOfCentralDirectoryArchive = Archive(url: noEndOfCentralDirectoryArchiveURL, accessMode: .read) XCTAssertNil(noEndOfCentralDirectoryArchive) } func testArchiveIteratorErrorConditions() { var didFailToMakeIteratorAsExpected = true // Construct an archive that only contains an EndOfCentralDirectoryRecord // with a number of entries > 0. // While the initializer is expected to work for such archives, iterator creation // should fail. let invalidCentralDirECDS: [UInt8] = [0x50, 0x4B, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5A, 0x00, 0x00, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00] let invalidCentralDirECDSData = Data(invalidCentralDirECDS) let processInfo = ProcessInfo.processInfo var invalidCentralDirArchiveURL = ZIPFoundationTests.tempZipDirectoryURL invalidCentralDirArchiveURL.appendPathComponent(processInfo.globallyUniqueString) let fileManager = FileManager() let result = fileManager.createFile(atPath: invalidCentralDirArchiveURL.path, contents: invalidCentralDirECDSData, attributes: nil) XCTAssert(result == true) guard let invalidCentralDirArchive = Archive(url: invalidCentralDirArchiveURL, accessMode: .read) else { XCTFail("Failed to read archive.") return } for _ in invalidCentralDirArchive { didFailToMakeIteratorAsExpected = false } XCTAssertTrue(didFailToMakeIteratorAsExpected) let archive = self.archive(for: #function, mode: .read) do { var invalidLocalFHArchiveURL = ZIPFoundationTests.tempZipDirectoryURL invalidLocalFHArchiveURL.appendPathComponent(processInfo.globallyUniqueString) var invalidLocalFHArchiveData = try Data(contentsOf: archive.url) // Construct an archive with a corrupt LocalFileHeader. // While the initializer is expected to work for such archives, iterator creation // should fail. invalidLocalFHArchiveData[26] = 0xFF try invalidLocalFHArchiveData.write(to: invalidLocalFHArchiveURL) guard let invalidLocalFHArchive = Archive(url: invalidLocalFHArchiveURL, accessMode: .read) else { XCTFail("Failed to read local file header.") return } for _ in invalidLocalFHArchive { didFailToMakeIteratorAsExpected = false } } catch { XCTFail("Unexpected error while testing iterator error conditions.") } XCTAssertTrue(didFailToMakeIteratorAsExpected) } func testArchiveInvalidDataErrorConditions() { let emptyECDR = Archive.EndOfCentralDirectoryRecord(data: Data(), additionalDataProvider: {_ -> Data in return Data() }) XCTAssertNil(emptyECDR) let invalidECDRData = Data(count: 22) let invalidECDR = Archive.EndOfCentralDirectoryRecord(data: invalidECDRData, additionalDataProvider: {_ -> Data in return Data() }) XCTAssertNil(invalidECDR) let ecdrInvalidCommentBytes: [UInt8] = [0x50, 0x4B, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5A, 0x00, 0x00, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00] let invalidECDRCommentData = Data(ecdrInvalidCommentBytes) let invalidECDRComment = Archive.EndOfCentralDirectoryRecord(data: invalidECDRCommentData, additionalDataProvider: {_ -> Data in throw AdditionalDataError.invalidDataError }) XCTAssertNil(invalidECDRComment) let ecdrInvalidCommentLengthBytes: [UInt8] = [0x50, 0x4B, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5A, 0x00, 0x00, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x00, 0x01] let invalidECDRCommentLengthData = Data(ecdrInvalidCommentLengthBytes) let invalidECDRCommentLength = Archive.EndOfCentralDirectoryRecord(data: invalidECDRCommentLengthData, additionalDataProvider: {_ -> Data in return Data() }) XCTAssertNil(invalidECDRCommentLength) } // MARK: - Helpers func archive(for testFunction: String, mode: Archive.AccessMode, preferredEncoding: String.Encoding? = nil) -> Archive { var sourceArchiveURL = ZIPFoundationTests.resourceDirectoryURL sourceArchiveURL.appendPathComponent(testFunction.replacingOccurrences(of: "()", with: "")) sourceArchiveURL.appendPathExtension("zip") var destinationArchiveURL = ZIPFoundationTests.tempZipDirectoryURL destinationArchiveURL.appendPathComponent(sourceArchiveURL.lastPathComponent) do { if mode != .create { let fileManager = FileManager() try fileManager.copyItem(at: sourceArchiveURL, to: destinationArchiveURL) } guard let archive = Archive(url: destinationArchiveURL, accessMode: mode, preferredEncoding: preferredEncoding) else { throw Archive.ArchiveError.unreadableArchive } return archive } catch { XCTFail("Failed to get test archive '\(destinationArchiveURL.lastPathComponent)'") type(of: self).tearDown() preconditionFailure() } } func pathComponent(for testFunction: String) -> String { return testFunction.replacingOccurrences(of: "()", with: "") } func archiveName(for testFunction: String, suffix: String = "") -> String { let archiveName = testFunction.replacingOccurrences(of: "()", with: "") return archiveName.appending(suffix).appending(".zip") } func resourceURL(for testFunction: String, pathExtension: String) -> URL { var sourceAssetURL = ZIPFoundationTests.resourceDirectoryURL sourceAssetURL.appendPathComponent(testFunction.replacingOccurrences(of: "()", with: "")) sourceAssetURL.appendPathExtension(pathExtension) var destinationAssetURL = ZIPFoundationTests.tempZipDirectoryURL destinationAssetURL.appendPathComponent(sourceAssetURL.lastPathComponent) do { let fileManager = FileManager() try fileManager.copyItem(at: sourceAssetURL, to: destinationAssetURL) return destinationAssetURL } catch { XCTFail("Failed to get test resource '\(destinationAssetURL.lastPathComponent)'") type(of: self).tearDown() preconditionFailure() } } func createDirectory(for testFunction: String) -> URL { let fileManager = FileManager() var URL = ZIPFoundationTests.tempZipDirectoryURL URL = URL.appendingPathComponent(self.pathComponent(for: testFunction)) do { try fileManager.createDirectory(at: URL, withIntermediateDirectories: true, attributes: nil) } catch { XCTFail("Failed to get create directory for test function:\(testFunction)") type(of: self).tearDown() preconditionFailure() } return URL } } extension ZIPFoundationTests { // From https://oleb.net/blog/2017/03/keeping-xctest-in-sync/ func testLinuxTestSuiteIncludesAllTests() { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let thisClass = type(of: self) let linuxCount = thisClass.allTests.count let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount) XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests") #endif } static var allTests: [(String, (ZIPFoundationTests) -> () throws -> Void)] { return [ ("testArchiveAddEntryErrorConditions", testArchiveAddEntryErrorConditions), ("testArchiveCreateErrorConditions", testArchiveCreateErrorConditions), ("testArchiveInvalidDataErrorConditions", testArchiveInvalidDataErrorConditions), ("testArchiveIteratorErrorConditions", testArchiveIteratorErrorConditions), ("testArchiveReadErrorConditions", testArchiveReadErrorConditions), ("testArchiveUpdateErrorConditions", testArchiveUpdateErrorConditions), ("testCorruptFileErrorConditions", testCorruptFileErrorConditions), ("testCorruptSymbolicLinkErrorConditions", testCorruptSymbolicLinkErrorConditions), ("testCreateArchiveAddCompressedEntry", testCreateArchiveAddCompressedEntry), ("testCreateArchiveAddDirectory", testCreateArchiveAddDirectory), ("testCreateArchiveAddEntryErrorConditions", testCreateArchiveAddEntryErrorConditions), ("testCreateArchiveAddZeroSizeUncompressedEntry", testCreateArchiveAddZeroSizeUncompressedEntry), ("testCreateArchiveAddZeroSizeCompressedEntry", testCreateArchiveAddZeroSizeCompressedEntry), ("testCreateArchiveAddLargeCompressedEntry", testCreateArchiveAddLargeCompressedEntry), ("testCreateArchiveAddLargeUncompressedEntry", testCreateArchiveAddLargeUncompressedEntry), ("testCreateArchiveAddSymbolicLink", testCreateArchiveAddSymbolicLink), ("testCreateArchiveAddTooLargeUncompressedEntry", testCreateArchiveAddTooLargeUncompressedEntry), ("testCreateArchiveAddUncompressedEntry", testCreateArchiveAddUncompressedEntry), ("testDirectoryCreationHelperMethods", testDirectoryCreationHelperMethods), ("testEntryInvalidAdditionalDataErrorConditions", testEntryInvalidAdditionalDataErrorConditions), ("testEntryInvalidPathEncodingErrorConditions", testEntryInvalidPathEncodingErrorConditions), ("testEntryInvalidSignatureErrorConditions", testEntryInvalidSignatureErrorConditions), ("testEntryMissingDataDescriptorErrorCondition", testEntryMissingDataDescriptorErrorCondition), ("testEntryTypeDetectionHeuristics", testEntryTypeDetectionHeuristics), ("testEntryWrongDataLengthErrorConditions", testEntryWrongDataLengthErrorConditions), ("testExtractCompressedDataDescriptorArchive", testExtractCompressedDataDescriptorArchive), ("testExtractCompressedFolderEntries", testExtractCompressedFolderEntries), ("testExtractEncryptedArchiveErrorConditions", testExtractEncryptedArchiveErrorConditions), ("testExtractUncompressedEntryCancelation", testExtractUncompressedEntryCancelation), ("testExtractCompressedEntryCancelation", testExtractCompressedEntryCancelation), ("testExtractErrorConditions", testExtractErrorConditions), ("testExtractPreferredEncoding", testExtractPreferredEncoding), ("testExtractMSDOSArchive", testExtractMSDOSArchive), ("testExtractUncompressedDataDescriptorArchive", testExtractUncompressedDataDescriptorArchive), ("testExtractUncompressedFolderEntries", testExtractUncompressedFolderEntries), ("testExtractZIP64ArchiveErrorConditions", testExtractZIP64ArchiveErrorConditions), ("testFileAttributeHelperMethods", testFileAttributeHelperMethods), ("testFilePermissionHelperMethods", testFilePermissionHelperMethods), ("testFileSizeHelperMethods", testFileSizeHelperMethods), ("testFileTypeHelperMethods", testFileTypeHelperMethods), ("testInvalidCompressionMethodErrorConditions", testInvalidCompressionMethodErrorConditions), ("testPerformanceReadCompressed", testPerformanceReadCompressed), ("testPerformanceReadUncompressed", testPerformanceReadUncompressed), ("testPerformanceWriteCompressed", testPerformanceWriteCompressed), ("testPerformanceWriteUncompressed", testPerformanceWriteUncompressed), ("testPOSIXPermissions", testPOSIXPermissions), ("testProgressHelpers", testProgressHelpers), ("testRemoveCompressedEntry", testRemoveCompressedEntry), ("testRemoveDataDescriptorCompressedEntry", testRemoveDataDescriptorCompressedEntry), ("testRemoveEntryErrorConditions", testRemoveEntryErrorConditions), ("testRemoveUncompressedEntry", testRemoveUncompressedEntry), ("testUniqueTemporaryDirectoryURL", testUniqueTemporaryDirectoryURL), ("testTraversalAttack", testTraversalAttack), ("testUnzipArchive", testUnzipArchive), ("testUnzipArchiveWithPreferredEncoding", testUnzipArchiveWithPreferredEncoding), ("testUnzipArchiveErrorConditions", testUnzipArchiveErrorConditions), ("testUnzipItem", testUnzipItem), ("testUnzipItemWithPreferredEncoding", testUnzipItemWithPreferredEncoding), ("testUnzipItemErrorConditions", testUnzipItemErrorConditions), ("testZipItem", testZipItem), ("testZipItemToArchive", testZipItemToArchive), ("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests) ] + darwinOnlyTests + swift5OnlyTests } static var darwinOnlyTests: [(String, (ZIPFoundationTests) -> () throws -> Void)] { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) return [ ("testFileModificationDate", testFileModificationDate), ("testFileModificationDateHelperMethods", testFileModificationDateHelperMethods), ("testZipItemProgress", testZipItemProgress), ("testUnzipItemProgress", testUnzipItemProgress), ("testUnzipArchiveProgress", testUnzipArchiveProgress), ("testRemoveEntryProgress", testRemoveEntryProgress), ("testReplaceCurrentArchiveWithArchiveCrossLink", testReplaceCurrentArchiveWithArchiveCrossLink), ("testArchiveAddUncompressedEntryProgress", testArchiveAddUncompressedEntryProgress), ("testArchiveAddCompressedEntryProgress", testArchiveAddCompressedEntryProgress), // The below test cases test error code paths but they lead to undefined behavior and memory // corruption on non-Darwin platforms. We disable them for now. ("testReadStructureErrorConditions", testReadStructureErrorConditions), ("testReadChunkErrorConditions", testReadChunkErrorConditions), ("testWriteChunkErrorConditions", testWriteChunkErrorConditions), // Fails for Swift < 4.2 on Linux. We can re-enable that when we drop Swift 4.x support ("testZipItemErrorConditions", testZipItemErrorConditions), ("testZipItemToArchiveErrorConditions", testZipItemToArchiveErrorConditions) ] #else return [] #endif } static var swift5OnlyTests: [(String, (ZIPFoundationTests) -> () throws -> Void)] { #if swift(>=5.0) return [ ("testAppendFile", testAppendFile), ("testCreateArchiveAddUncompressedEntryToMemory", testCreateArchiveAddUncompressedEntryToMemory), ("testCreateArchiveAddCompressedEntryToMemory", testCreateArchiveAddCompressedEntryToMemory), ("testExtractCompressedFolderEntriesFromMemory", testExtractCompressedFolderEntriesFromMemory), ("testExtractUncompressedFolderEntriesFromMemory", testExtractUncompressedFolderEntriesFromMemory), ("testMemoryArchiveErrorConditions", testMemoryArchiveErrorConditions), ("testWriteOnlyFile", testWriteOnlyFile), ("testReadOnlyFile", testReadOnlyFile), ("testReadOnlySlicedFile", testReadOnlySlicedFile), ("testReadWriteFile", testReadWriteFile), ("testZipItemAndReturnArchive", testZipItemAndReturnArchive), ("testZipItemAndReturnArchiveErrorConditions", testZipItemAndReturnArchiveErrorConditions) ] #else return [] #endif } } extension Archive { func checkIntegrity() -> Bool { var isCorrect = false do { for entry in self { let checksum = try self.extract(entry, consumer: { _ in }) isCorrect = checksum == entry.checksum guard isCorrect else { break } } } catch { return false } return isCorrect } } extension Data { static func makeRandomData(size: Int) -> Data { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let bytes = [UInt32](repeating: 0, count: size).map { _ in arc4random() } #else let bytes = [UInt32](repeating: 0, count: size).map { _ in random() } #endif return Data(bytes: bytes, count: size) } }
54.840102
117
0.655991
0a5cbc4cbc147bb8d9509964f14917ee9e553161
344
import UI import Core import SwiftUI @main struct FlipperApp: App { init() { #if !targetEnvironment(simulator) Core.registerDependencies() #else Core.registerMockDependencies() #endif } var body: some Scene { WindowGroup { RootView(viewModel: .init()) } } }
16.380952
41
0.56686
261ff3ab4fa49dcbc7b3faef8cb6e464e42a3884
6,195
// // SKScNavViewController.swift // SCNavController // // Created by Xin on 16/10/30. // Copyright © 2016年 王鑫. All rights reserved. // import UIKit class XScNavViewController: UIViewController, XScNavBarDelegate, UIScrollViewDelegate { //MARK:必须设置的一些属性 /** * @param scNaBarColor * @param showArrowButton * @param lineColor */ //MARK: -- 公共设置属性 /** * 是否显示扩展按钮 */ var showArrowButton:Bool! // 默认值是true /** * 导航栏的颜色 */ var scNavBarColor:UIColor! //默认值clearColor /** * 扩展按钮上的图片 */ var scNavBarArrowImage:UIImage! /** * 包含所有子视图控制器的数组 */ var subViewControllers:NSArray! /** * 线的颜色 */ var lineColor:UIColor! //默认值redColor /** * 扩展菜单栏的高度 */ var launchMenuHeight:CGFloat! //MARK: -- 私有属性 private var currentIndex:Int! //当前显示的页面的下标 private var titles:NSMutableArray! //子视图控制器的title数组 private var scNavBar:XScNavBar! //导航栏视图 private var mainView:UIScrollView! //主页面的ScrollView //MARK: ----- 方法 ----- //MARK: -- 外界接口 /** * 初始化withShowArrowButton * @param showArrowButton 显示扩展菜单按钮 */ init(show:Bool){ super.init(nibName: nil, bundle: nil) self.showArrowButton = show } /** * 初始化withSubViewControllers * @param subViewControllers 子视图控制器数组 */ init(subViewControllers:NSArray) { super.init(nibName: nil, bundle: nil) self.subViewControllers = subViewControllers } /** * 初始化withParentViewController * @param parentViewController 父视图控制器 */ init(parentViewController:UIViewController) { super.init(nibName: nil, bundle: nil) self.addParentController(parentViewController) } /** * 初始化SKScNavBarController * @param subViewControllers 子视图控制器 * @param parentViewController 父视图控制器 * @param show 是否显示展开扩展菜单栏按钮 */ init(subViewControllers:NSArray, parentViewController:HotViewController, show:Bool) { super.init(nibName: nil, bundle: nil) self.subViewControllers = subViewControllers self.showArrowButton = show self.addParentController(parentViewController) } /** * 添加父视图控制器的方法 * @param viewController 父视图控制器 */ func addParentController(viewcontroller:UIViewController) { // viewcontroller.edgesForExtendedLayout = UIRectEdge.None viewcontroller.addChildViewController(self) viewcontroller.view.addSubview(self.view) } override func viewDidLoad() { super.viewDidLoad() //调用初始化属性的方法 initParamConfig() //调用初始化、配置视图的方法 viewParamConfig() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: -- 私有方法 //初始化一些属性 private func initParamConfig() { //初始化一些变量 currentIndex = 1 scNavBarColor = scNavBarColor != nil ? scNavBarColor : navColor if scNavBarArrowImage == nil { scNavBarArrowImage = UIImage(named: "arrow.png") } if showArrowButton == nil { showArrowButton = true } if lineColor == nil { lineColor = UIColor.blueColor() } //获取所有子视图控制器上的title titles = NSMutableArray(capacity: subViewControllers.count) for vc in subViewControllers { titles.addObject(vc.navigationItem.title!) } } //初始化视图 private func initWithScNavBarAndMainView() { scNavBar = XScNavBar(frame: CGRectMake(0, 64, kScreenWidth, scNavBarHeight), show: showArrowButton, image: scNavBarArrowImage) scNavBar.delegate = self scNavBar.backgroundColor = scNavBarColor scNavBar.itemsTitles = titles scNavBar.lineColor = lineColor scNavBar.setItemsData() mainView = UIScrollView(frame: CGRectMake(0, scNavBar.frame.origin.y + scNavBar.frame.size.height, kScreenWidth, kScreenHeight - scNavBar.frame.origin.y - scNavBar.frame.size.height)) mainView.delegate = self mainView.pagingEnabled = true mainView.bounces = false mainView.showsHorizontalScrollIndicator = false mainView.contentSize = CGSizeMake(kScreenWidth * CGFloat(subViewControllers.count), 0) view.addSubview(mainView) view.addSubview(scNavBar) } //配置视图参数 private func viewParamConfig() { initWithScNavBarAndMainView() //将子视图控制器的view添加到mainView上 subViewControllers.enumerateObjectsUsingBlock { (_, index:Int, _) -> Void in let vc = self.subViewControllers[index] as! UIViewController vc.view.frame = CGRectMake(CGFloat(index) * kScreenWidth, 0, kScreenWidth, self.mainView.frame.size.height) self.mainView.addSubview(vc.view) self.mainView.backgroundColor = UIColor.whiteColor() self.addChildViewController(vc) } } //MARK: -- ScrollView Delegate 方法 func scrollViewDidScroll(scrollView: UIScrollView) { currentIndex = Int(scrollView.contentOffset.x / kScreenWidth) scNavBar.setViewWithItemIndex = currentIndex } //MARK: -- SKScNavBarDelegate 中的方法 func didSelectedWithIndex(index: Int) { mainView.setContentOffset(CGPointMake(CGFloat(index) * kScreenWidth, 0), animated: true) } func isShowScNavBarItemMenu(show: Bool, height: CGFloat) { if show { UIView.animateWithDuration(0.5) { () -> Void in self.scNavBar.frame = CGRectMake(self.scNavBar.frame.origin.x, self.scNavBar.frame.origin.y, kScreenWidth, height) } }else{ UIView.animateWithDuration(0.5, animations: { () -> Void in self.scNavBar.frame = CGRectMake(self.scNavBar.frame.origin.x, self.scNavBar.frame.origin.y, kScreenWidth, scNavBarHeight) }) } scNavBar.refreshAll() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
30.072816
191
0.626957
7106afdb46f8f4f4ffec475e4d9051b9324f27e2
1,148
// // NT+Font.swift // NomadTools // // Created by Justin Ackermann on 5/28/21. // import UIKit public enum Font { public static var Key: NSAttributedString.Key = .font case Default case Thin case Light case Medium case Bold case Black case BlackItalic case BoldItalic case ExtraLight case ExtraLightItalic case LightItalic case Regular case Italic case SemiBold case SemiBoldItalic public func getFont(size: CGFloat? = 14) -> UIFont { guard let size = size else { return UIFont(name: "Helvetica Neue", size: 14)! } switch self { case .Default: return UIFont(name: "Helvetica Neue", size: size)! case .Thin: return UIFont(name: "HelveticaNeue-Thin", size: size)! case .Light: return UIFont(name: "HelveticaNeue-Light", size: size)! case .Medium: return UIFont(name: "HelveticaNeue-Medium", size: size)! case .Bold: return UIFont(name: "HelveticaNeue-Bold", size: size)! default: return UIFont(name: "Helvetica Neue", size: size)! } } }
25.511111
87
0.608885
fc70065f2130b8cacf2d3f56c4cbfc0b65254ba0
5,354
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import Foundation /// A structure representing money type and set of attributes to formats the /// output. /// /// # Example /// /// ```swift /// let amount = Money(120.30) /// .signed() /// .font(.body) /// .style(.removeMinorUnitIfZero) /// /// // Display the amount in a label. /// let amountLabel = UILabel() /// amountLabel.setText(amount) /// ``` /// /// # Using Custom Formats /// /// ```swift /// let monthlyPayment = Money(9.99) /// .font(.headline) /// .attributedString(format: "%@ per month") /// /// // Display the amount in a label. /// let amountLabel = UILabel() /// amountLabel.setText(amount) /// ``` public struct Money: Equatable, Hashable, MutableAppliable { /// The amount of money. public var amount: Decimal public init(_ amount: Decimal) { self.amount = amount shouldSuperscriptMinorUnit = Self.appearance().shouldSuperscriptMinorUnit } public init?(_ amount: Double?) { guard let amount = amount else { return nil } self.init(amount) } /// The currency formatter used to format the amount. /// /// The default value is `.shared`. public var formatter: CurrencyFormatter = .shared /// The style used to format money components. /// /// The default value is `.default`. public var style: Components.Style = .default /// The font used to display money components. /// /// The default value is `.none`. public var font: Components.Font = .none /// The sign (+/-) used to format money components. /// /// The default value is `.none`. public var sign: Sign = .none /// A property to indicate whether the color changes based on the amount. public var color: Color = .none /// The custom string to use when the amount is `0`. /// /// This value is ignored if the `shouldDisplayZero` property is `true`. /// /// The default value is `--`. public var zeroString: String = "--" public var shouldDisplayZero = true /// A property to indicate whether the minor unit is rendered as superscript. /// /// The default value is `false`. public var shouldSuperscriptMinorUnit: Bool public var accessibilityLabel: String { formatter.string(from: amount, style: style) } } // MARK: - ExpressibleByFloatLiteral extension Money: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(Decimal(value)) } public init(_ value: Double) { self.init(Decimal(value)) } } // MARK: - ExpressibleByIntegerLiteral extension Money: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(Decimal(value)) } public init(_ value: Int) { self.init(Decimal(value)) } } // MARK: - CustomStringConvertible extension Money: CustomStringConvertible { public var description: String { formatter.string(from: self) } } // MARK: - StringRepresentable extension Money: StringRepresentable { public var stringSource: StringSourceType { .attributedString(formatter.attributedString(from: self)) } } // MARK: - Appearance extension Money { /// This configuration exists to allow some of the properties to be configured /// to match app's appearance style. The `UIAppearance` protocol doesn't work /// when the stored properites are set using associated object. /// /// **Usage:** /// /// ```swift /// Money.appearance().shouldSuperscriptMinorUnit = true /// ``` final public class Appearance: Appliable { public var shouldSuperscriptMinorUnit = false } private static var appearanceProxy = Appearance() public static func appearance() -> Appearance { appearanceProxy } } // MARK: - Chaining Syntactic Syntax extension Money { public func style(_ style: Components.Style) -> Self { applying { $0.style = style } } public func font(_ font: Components.Font) -> Self { applying { $0.font = font } } public func sign(_ sign: Sign) -> Self { applying { $0.sign = sign } } public func color(_ color: Color) -> Self { applying { $0.color = color } } public func color(_ color: UIColor) -> Self { applying { $0.color = .init(color) } } public func signed() -> Self { sign(.default) } /// Signed positive amount with (`"+"`), minus (`""`) and `0` amount omits /// `+` or `-` sign. public func positiveSigned() -> Self { sign(.init(plus: amount == 0 ? "" : "+", minus: "")) } /// Zero amount will be displayed as "--". /// /// See: `zeroString` to customize the default value. public func dasherizeZero() -> Self { applying { $0.shouldDisplayZero = false } } public func attributedString(format: String? = nil) -> NSAttributedString { formatter.attributedString(from: self, format: format) } public func string(format: String? = nil) -> String { formatter.string(from: self, format: format) } }
24.672811
82
0.609077
87b1b2fe5d1cfd2b5703b14945a2f09b1132dc82
2,151
// // AppDelegate.swift // AardvarkSample // // Created by Dan Federman on 9/21/16. // Copyright © 2016 Square, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Aardvark import CoreAardvark import UIKit @UIApplicationMain class SampleAppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var bugReporter: ARKBugReporter? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // This line is all you'll need to get started. bugReporter = Aardvark.addDefaultBugReportingGestureWithEmailBugReporter(withRecipient: "[email protected]") // Log all log messages to Crashlytics to help debug crashes. ARKLogDistributor.default().add(SampleCrashlyticsLogObserver()) log("Hello World", type: .separator) NSSetUncaughtExceptionHandler(existingUncaughtExceptionHandler) ARKEnableLogOnUncaughtException() return true } func applicationDidEnterBackground(_ application: UIApplication) { log("\(#function)") } func applicationWillEnterForeground(_ application: UIApplication) { log("\(#function)") } func applicationWillTerminate(_ application: UIApplication) { log("\(#function)", type: .error) } } // MARK: - Uncaught Exception Handling func existingUncaughtExceptionHandler(exception: NSException) { print("Existing uncaught exception handler got called for exception: \(exception)") }
31.632353
144
0.711762
cc8cf027298850c14776896cb0df57a8214320d6
10,528
import UIKit extension ScrollViewBuilder { public class Collection: ScrollViewBuilder { private unowned var _manager: ScrollViewBuilder.Collection.ColManager! { return manager as? ScrollViewBuilder.Collection.ColManager } /// 是否设定了prefetchDataSource代理,默认是false private var isConfigDataSourcePrefetching = false internal func build(for collectionView: UICollectionView) { collectionView.delegate = nil collectionView.dataSource = nil collectionView.delegate = _manager collectionView.dataSource = _manager if #available(iOS 10.0, *) { if isConfigDataSourcePrefetching { collectionView.prefetchDataSource = _manager } } } } } // MARK: - UICollectionViewDelegate public extension ScrollViewBuilder.Collection { @discardableResult func shouldHighlightItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.shouldHighlightItem = block return self } @discardableResult func didHighlightItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> ()) -> Self { _manager.didHighlightItem = block return self } @discardableResult func didUnhighlightItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> ()) -> Self { _manager.didUnhighlightItem = block return self } @discardableResult func shouldSelectItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.shouldSelectItem = block return self } @discardableResult func shouldDeselectItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.shouldDeselectItem = block return self } @discardableResult func didSelectItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> ()) -> Self { _manager.didSelectItem = block return self } @discardableResult func didDeselectItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> ()) -> Self { _manager.didDeselectItem = block return self } @discardableResult func willDisplayCell(_ block: @escaping (_ collectionView: UICollectionView, _ cell: UICollectionViewCell, _ indexPath: IndexPath) -> ()) -> Self { _manager.willDisplayCell = block return self } @discardableResult func willDisplaySupplementaryView(_ block: @escaping (_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ kind: UICollectionElementKind, _ indexPath: IndexPath) -> ()) -> Self { _manager.willDisplaySupplementaryView = block return self } @discardableResult func didEndDisplayingCell(_ block: @escaping (_ collectionView: UICollectionView, _ cell: UICollectionViewCell, _ indexPath: IndexPath) -> ()) -> Self { _manager.didEndDisplayingCell = block return self } @discardableResult func didEndDisplayingSupplementaryView(_ block: @escaping (_ collectionView: UICollectionView, _ view: UICollectionReusableView, _ kind: UICollectionElementKind, _ indexPath: IndexPath) -> ()) -> Self { _manager.didEndDisplayingSupplementaryView = block return self } @discardableResult func shouldShowMenuForItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.shouldShowMenuForItem = block return self } @discardableResult func canPerformAction(_ block: @escaping (_ collectionView: UICollectionView, _ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> Bool) -> Self { _manager.canPerformAction = block return self } @discardableResult func performAction(_ block: @escaping (_ collectionView: UICollectionView, _ action: Selector, _ indexPath: IndexPath, _ sender: Any?) -> ()) -> Self { _manager.performAction = block return self } @discardableResult func transitionLayout(_ block: @escaping (_ collectionView: UICollectionView, _ fromLayout: UICollectionViewLayout, _ newLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout) -> Self { _manager.transitionLayout = block return self } @discardableResult func canFocusItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.canFocusItem = block return self } @discardableResult func shouldUpdateFocus(_ block: @escaping (_ collectionView: UICollectionView, _ context: UICollectionViewFocusUpdateContext) -> Bool) -> Self { _manager.shouldUpdateFocus = block return self } @discardableResult func didUpdateFocus(_ block: @escaping (_ collectionView: UICollectionView, _ context: UICollectionViewFocusUpdateContext, _ coordinator: UIFocusAnimationCoordinator) -> ()) -> Self { _manager.didUpdateFocus = block return self } @discardableResult func indexPathForPreferredFocusedView(_ block: @escaping (_ collectionView: UICollectionView) -> IndexPath?) -> Self { _manager.indexPathForPreferredFocusedView = block return self } @discardableResult func targetContentOffset(_ block: @escaping (_ collectionView: UICollectionView, _ proposedContentOffset: CGPoint) -> CGPoint) -> Self { _manager.targetContentOffset = block return self } @discardableResult func targetIndexPathForMove(_ block: @escaping (_ collectionView: UICollectionView, _ originalIndexPath: IndexPath, _ proposedIndexPath: IndexPath) -> IndexPath) -> Self { _manager.targetIndexPathForMove = block return self } @available(iOS 11.0, *) @discardableResult func shouldSpringLoadItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath, _ context: UISpringLoadedInteractionContext) -> Bool) -> Self { _manager.shouldSpringLoadItem = block return self } } // MARK: - UICollectionViewDataSource public extension ScrollViewBuilder.Collection { @discardableResult func numberOfItems(_ block: @escaping (_ collectionView: UICollectionView, _ section: Int) -> Int) -> Self { _manager.numberOfItems = block return self } @discardableResult func numberOfSections(_ block: @escaping (_ collectionView: UICollectionView) -> Int) -> Self { _manager.numberOfSections = block return self } @discardableResult func cellForItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> UICollectionViewCell) -> Self { _manager.cellForItem = block return self } @discardableResult func viewForSupplementaryElement(_ block: @escaping (_ collectionView: UICollectionView, _ kind: UICollectionElementKind, _ indexPath: IndexPath) -> UICollectionReusableView) -> Self { _manager.viewForSupplementaryElement = block return self } @discardableResult func canMoveItem(_ block: @escaping (_ collectionView: UICollectionView, _ indexPath: IndexPath) -> Bool) -> Self { _manager.canMoveItem = block return self } @discardableResult func moveItem(_ block: @escaping (_ collectionView: UICollectionView, _ sourceIndexPath: IndexPath, _ destinationIndexPath: IndexPath) -> ()) -> Self { _manager.moveItem = block return self } @discardableResult func indexTitles(_ block: @escaping (_ collectionView: UICollectionView) -> [String]?) -> Self { _manager.indexTitles = block return self } @discardableResult func indexPathForIndexTitle(_ block: @escaping (_ collectionView: UICollectionView, _ title: String, _ index: Int) -> IndexPath) -> Self { _manager.indexPathForIndexTitle = block return self } } // MARK: - UICollectionViewDataSourcePrefetching public extension ScrollViewBuilder.Collection { @available(iOS 10.0, *) @discardableResult func prefetchItems(_ block: @escaping (_ collectionView: UICollectionView, _ indexPaths: [IndexPath]) -> ()) -> Self { isConfigDataSourcePrefetching = true _manager.prefetchItems = block return self } @available(iOS 10.0, *) @discardableResult func cancelPrefetchingForItems(_ block: @escaping (_ collectionView: UICollectionView, _ indexPaths: [IndexPath]) -> ()) -> Self { isConfigDataSourcePrefetching = true _manager.cancelPrefetchingForItems = block return self } } // MARK: - UICollectionViewDelegateFlowLayout public extension ScrollViewBuilder.Collection { @discardableResult func sizeForItem(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ indexPath: IndexPath) -> CGSize) -> Self { _manager.sizeForItem = block return self } @discardableResult func insetForSection(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ section: Int) -> UIEdgeInsets) -> Self { _manager.insetForSection = block return self } @discardableResult func minimumLineSpacingForSection(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ section: Int) -> CGFloat) -> Self { _manager.minimumLineSpacingForSection = block return self } @discardableResult func minimumInteritemSpacingForSection(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ section: Int) -> CGFloat) -> Self { _manager.minimumInteritemSpacingForSection = block return self } @discardableResult func referenceSizeForHeaderInSection(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ section: Int) -> CGSize) -> Self { _manager.referenceSizeForHeader = block return self } @discardableResult func referenceSizeForFooterInSection(_ block: @escaping (_ collectionView: UICollectionView, _ layout: UICollectionViewLayout, _ section: Int) -> CGSize) -> Self { _manager.referenceSizeForFooter = block return self } }
45.184549
206
0.700893
0319123ad94bd9c70f4f1df43d0ac0968c10a39e
357
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import Foundation enum AppStatus { case foreground case background } class LifeCycleState: ReduxState { let currentStatus: AppStatus init(currentStatus: AppStatus = .foreground) { self.currentStatus = currentStatus } }
16.227273
61
0.70028
2633792f806bbe5edb2bd6a64727673a82f3d237
2,889
// // DetailViewController.swift // Todo // // Created by tanhaipeng on 2017/9/9. // Copyright © 2017年 tanhaipeng. All rights reserved. // import UIKit class DetailViewController: UIViewController, UITextViewDelegate{ @IBOutlet weak var child: UIButton! @IBOutlet weak var plane: UIButton! @IBOutlet weak var shop: UIButton! @IBOutlet weak var tel: UIButton! @IBOutlet weak var todoL: UILabel! @IBOutlet weak var todo: UITextField! @IBOutlet weak var datepicker: UIDatePicker! var todoOld:TodoModel? override func viewDidLoad() { super.viewDidLoad() if todoOld==nil{ navigationItem.title = "新增todo" child.isSelected = true }else{ navigationItem.title = "编辑todo" if todoOld?.image == "children_s"{ child.isSelected = true } if todoOld?.image == "plane_s"{ plane.isSelected = true } if todoOld?.image == "tel_s"{ tel.isSelected = true } if todoOld?.image == "shop_s"{ shop.isSelected = true } todo.text = todoOld?.title datepicker.setDate((todoOld?.date)!, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func resetButton(){ child.isSelected = false plane.isSelected = false shop.isSelected = false tel.isSelected = false } @IBAction func childClick(_ sender: Any) { resetButton() child.isSelected = true } @IBAction func planeClick(_ sender: Any) { resetButton() plane.isSelected = true } @IBAction func shopClick(_ sender: Any) { resetButton() shop.isSelected = true } @IBAction func telClick(_ sender: Any) { resetButton() tel.isSelected = true } @IBAction func okClick(_ sender: Any) { var image = "" if child.isSelected { image = "children_s" } if plane.isSelected { image = "plane_s" } if shop.isSelected { image = "shop_s" } if tel.isSelected { image = "tel_s" } if todoOld == nil{ let uuid = NSUUID.init().uuidString var todo = TodoModel(id:uuid,image:image,title:self.todo.text!,date:datepicker.date) todos.append(todo) }else{ todoOld?.image = image todoOld?.title = todo.text! todoOld?.date = datepicker.date } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { todo.resignFirstResponder() } }
26.027027
92
0.548979
8ff18df09916097cb6d2c2835fed3d52a2f8f64e
1,140
// // ProductTableViewCell.swift // ClassifiedApp // // Created by AJ Sagar Parwani on 12/02/2021. // import UIKit class ProductTableViewCell: UITableViewCell { @IBOutlet weak var imageProduct: UIImageView! @IBOutlet weak var labelProductName: UILabel! @IBOutlet weak var labelProductDateCreated: UILabel! @IBOutlet weak var labelProductPrice: UILabel! var presenter: ProductCellPresenter? { didSet { self.configureCell() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } fileprivate func configureCell() { self.labelProductName.text = presenter?.getName() self.labelProductDateCreated.text = presenter?.getDate() self.labelProductPrice.text = presenter?.getPrice() presenter?.getThumbmailImage(onCompletion: { (image, error) in self.imageProduct.image = image }) } }
25.909091
70
0.659649
ddc556bfbb6766b83356b2865907f13c2b60d9a1
2,278
// // ArticleListFlowLayout.swift // iOCNews // // Created by Peter Hedlund on 1/15/19. // Copyright © 2019 Peter Hedlund. All rights reserved. // import UIKit @objcMembers class ArticleListFlowLayout: UICollectionViewFlowLayout { private var computedContentSize: CGSize = .zero private var cellAttributes = [IndexPath: UICollectionViewLayoutAttributes]() static let itemHeight: CGFloat = 154 override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { let _ = super.shouldInvalidateLayout(forBoundsChange: newBounds) return true } override func prepare() { guard let cv = self.collectionView else { return } computedContentSize = .zero cellAttributes = [IndexPath: UICollectionViewLayoutAttributes]() let itemWidth = cv.frame.size.width for section in 0 ..< cv.numberOfSections { for item in 0 ..< cv.numberOfItems(inSection: section) { let itemFrame = CGRect(x: 0, y: CGFloat(item) * ArticleListFlowLayout.itemHeight, width: itemWidth, height: ArticleListFlowLayout.itemHeight) let indexPath = IndexPath(item: item, section: section) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = itemFrame cellAttributes[indexPath] = attributes } } computedContentSize = CGSize(width: itemWidth, height: ArticleListFlowLayout.itemHeight * CGFloat(cv.numberOfItems(inSection: 0))) } override var collectionViewContentSize: CGSize { return computedContentSize } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributeList = [UICollectionViewLayoutAttributes]() for (_, attributes) in cellAttributes { if attributes.frame.intersects(rect) { attributeList.append(attributes) } } return attributeList } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cellAttributes[indexPath] } }
33.5
157
0.653205
e5d56018474f87a24757de39c4edcf007d5b786c
724
// // FeedEvent.swift // CastrApp // // Created by Antoine on 01/09/2017. // Copyright © 2017 Castr. All rights reserved. // import Foundation enum FeedEvent { case notificationsLoaded(notifications: [FeedElement]) case notificationsAdded(notification: FeedElement) case notificationUpdated(notification: FeedElement) case notificationDeleted(notificationId: String) case favoritesLoaded(favorites: [FeedElement]) case favoriteAdded(favorite: FeedElement) case favoriteUpdated(favorite: FeedElement) case favoriteDeleted(favoriteId: String) case chatsLoaded(chats:[FeedElement]) case chatAdded(chat:FeedElement) case chatUpdated(chat:FeedElement) case chatDeleted(chatId: String) }
24.965517
56
0.769337
f915d3616b3659cd75928e403283054493263a9a
7,175
import UIKit import RobinHood import IrohaCrypto import SubstrateSdk final class AnalyticsValidatorsInteractor { weak var presenter: AnalyticsValidatorsInteractorOutputProtocol! let selectedAddress: AccountAddress let chainAsset: ChainAsset let stakingLocalSubscriptionFactory: StakingLocalSubscriptionFactoryProtocol let identityOperationFactory: IdentityOperationFactoryProtocol let operationManager: OperationManagerProtocol let connection: JSONRPCEngine let runtimeService: RuntimeCodingServiceProtocol let storageRequestFactory: StorageRequestFactoryProtocol let logger: LoggerProtocol? private var stashItemProvider: StreamableProvider<StashItem>? private var currentEraProvider: AnyDataProvider<DecodedEraIndex>? private var nominationProvider: AnyDataProvider<DecodedNomination>? private var identitiesByAddress: [AccountAddress: AccountIdentity]? private var currentEra: EraIndex? private var nomination: Nomination? private var stashItem: StashItem? init( selectedAddress: AccountAddress, chainAsset: ChainAsset, stakingLocalSubscriptionFactory: StakingLocalSubscriptionFactoryProtocol, identityOperationFactory: IdentityOperationFactoryProtocol, operationManager: OperationManagerProtocol, connection: JSONRPCEngine, runtimeService: RuntimeCodingServiceProtocol, storageRequestFactory: StorageRequestFactoryProtocol, logger: LoggerProtocol? ) { self.selectedAddress = selectedAddress self.chainAsset = chainAsset self.stakingLocalSubscriptionFactory = stakingLocalSubscriptionFactory self.identityOperationFactory = identityOperationFactory self.operationManager = operationManager self.connection = connection self.runtimeService = runtimeService self.storageRequestFactory = storageRequestFactory self.logger = logger } private func fetchValidatorIdentity(accountIds: [AccountId]) { let operation = identityOperationFactory.createIdentityWrapper( for: { accountIds }, engine: connection, runtimeService: runtimeService, chainFormat: chainAsset.chain.chainFormat ) operation.targetOperation.completionBlock = { [weak self] in DispatchQueue.main.async { do { let identitiesByAddress = try operation.targetOperation.extractNoCancellableResultData() self?.presenter.didReceive(identitiesByAddressResult: .success(identitiesByAddress)) } catch { self?.presenter.didReceive(identitiesByAddressResult: .failure(error)) } } } operationManager.enqueue(operations: operation.allOperations, in: .transient) } private func fetchEraStakers() { guard let analyticsURL = chainAsset.chain.externalApi?.staking?.url, let stashAddress = stashItem?.stash, let nomination = nomination, let currentEra = currentEra else { return } let eraRange = EraRange(start: nomination.submittedIn + 1, end: currentEra) DispatchQueue.main.async { [weak self] in self?.presenter.didReceive(eraRange: eraRange) } let source = SubqueryEraStakersInfoSource(url: analyticsURL, address: stashAddress) let fetchOperation = source.fetch { eraRange } fetchOperation.targetOperation.completionBlock = { [weak self] in DispatchQueue.main.async { do { let erasInfo = try fetchOperation.targetOperation.extractNoCancellableResultData() self?.presenter.didReceive(eraValidatorInfosResult: .success(erasInfo)) } catch { self?.presenter.didReceive(eraValidatorInfosResult: .failure(error)) } } } operationManager.enqueue(operations: fetchOperation.allOperations, in: .transient) } private func fetchRewards() { guard let analyticsURL = chainAsset.chain.externalApi?.staking?.url, let stashAddress = stashItem?.stash else { return } let subqueryRewardsSource = SubqueryRewardsSource(address: stashAddress, url: analyticsURL) let fetchOperation = subqueryRewardsSource.fetchOperation() fetchOperation.targetOperation.completionBlock = { [weak self] in DispatchQueue.main.async { do { let response = try fetchOperation.targetOperation.extractNoCancellableResultData() ?? [] self?.presenter.didReceive(rewardsResult: .success(response)) } catch { self?.presenter.didReceive(rewardsResult: .failure(error)) } } } operationManager.enqueue(operations: fetchOperation.allOperations, in: .transient) } } extension AnalyticsValidatorsInteractor: AnalyticsValidatorsInteractorInputProtocol { func setup() { stashItemProvider = subscribeStashItemProvider(for: selectedAddress) currentEraProvider = subscribeCurrentEra(for: chainAsset.chain.chainId) } func reload() { fetchEraStakers() fetchRewards() } } extension AnalyticsValidatorsInteractor: StakingLocalStorageSubscriber, StakingLocalSubscriptionHandler, AnyProviderAutoCleaning { func handleStashItem(result: Result<StashItem?, Error>, for _: AccountAddress) { clear(dataProvider: &nominationProvider) switch result { case let .success(stashItem): self.stashItem = stashItem if let stashAddress = stashItem?.stash, let stashId = try? stashAddress.toAccountId() { presenter.didReceive(stashAddressResult: .success(stashAddress)) nominationProvider = subscribeNomination(for: stashId, chainId: chainAsset.chain.chainId) fetchRewards() } case let .failure(error): presenter.didReceive(stashAddressResult: .failure(error)) } } func handleCurrentEra(result: Result<EraIndex?, Error>, chainId _: ChainModel.Id) { switch result { case let .success(currentEra): self.currentEra = currentEra fetchEraStakers() case let .failure(error): logger?.error("Gor error on currentEra subscription: \(error.localizedDescription)") } } func handleNomination( result: Result<Nomination?, Error>, accountId _: AccountId, chainId _: ChainModel.Id ) { presenter.didReceive(nominationResult: result) switch result { case let .success(nomination): self.nomination = nomination if let nomination = nomination { fetchValidatorIdentity(accountIds: nomination.targets) } fetchEraStakers() case let .failure(error): logger?.error("Gor error on nomination request: \(error.localizedDescription)") } } }
39.20765
108
0.670383
0ecec8a6fcf4b41c9ad75c5a5e2865f367c422f5
2,198
//: # With a tortoise 🐢 //: [👉 With 2 tortoises 🐢🐢](@next) import PlaygroundSupport import TortoiseGraphics import CoreGraphics import Foundation let canvas = PlaygroundCanvas(frame: CGRect(x: 0, y: 0, width: 800, height: 800)) canvas.frameRate = 30 canvas.color = .white PlaygroundPage.current.liveView = canvas canvas.drawing { 🐢 in 🐢.penColor(.red) 🐢.penDown() 🐢.forward(100) 🐢.left(40) 🐢.forward(100) 🐢.left(-40) // draw a square // 🐢.forward(100) // 🐢.left(90) // 🐢.forward(100) // 🐢.left(90) // 🐢.forward(100) // 🐢.left(90) // 🐢.forward(100) // 🐢.left(90) // look for repeats... // for i in 1 ... 4 { // 🐢.forward(100) // 🐢.left(90) // } //make it a function // func square() { // for i in 1 ... 4 { // 🐢.left(90) // 🐢.forward(100) // } // } // try it out //square() // // make it an adjustable function // func adjustableSquare(size: Double) { // for i in 1 ... 4 { // 🐢.left(90) // 🐢.forward(size) // } // } // let's make something out of those squares // for i in 1...90 { // adjustableSquare(size: 100) // 🐢.left(4) // } // Instantiate a ImageCanvas // let canvie = ImageCanvas(size: CGSize(width: 1500, height: 1500)) // // canvie.drawing { 🐢 in // // // make it an adjustable function // func adjustableSquare(size: Double) { // for i in 1 ... 4 { // 🐢.left(90) ///Users/mgreen/GitHub Clones/TortoiseGraphics-master/Playground/Playground.playground/Pages/With a tortoise.xcplaygroundpage 🐢.forward(size) // } // } // // for i in 1...90 { // adjustableSquare(size: 300) // 🐢.left(4) // } // } // // let cgImage = canvie.cgImage // // let image = canvie.image // // //canvie.writePNG(to: URL(fileURLWithPath: "./image.png")) // // let desktop = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop") // canvie.writePNG(to: desktop.appendingPathComponent("image.png")) // // }
22.895833
156
0.529117
d97d473c7366c1f840fb36e5d02d0fcbb9b76cd4
56
import Foundation enum MapType { case ubike, bus }
9.333333
19
0.696429
0324e5242bc6a11aece1320c309f8433f8aa8e47
2,165
// // AppDelegate.swift // EYViewActionDemo // // Created by eric on 3/07/17. // Copyright © 2017 Eric. 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.06383
285
0.755196
bbf254f7e8b5d89e1108a1e696c2cc5fd650ec3c
510
// // ViewController.swift // ExtensionDemo // // Created by Mstarc on 2017/8/11. // Copyright © 2017年 com.mstarc.app. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.615385
80
0.670588
8775b0a013d1cce384a01a1ff4eb62f60f915860
4,940
import Foundation enum SaveResult { case success case failure(Error) } enum CacheDBWritingResultWithURLRequests { case success([URLRequest]) case failure(Error) } enum CacheDBWritingResultWithItemAndVariantKeys { case success([CacheController.ItemKeyAndVariant]) case failure(Error) } enum CacheDBWritingResult { case success case failure(Error) } enum CacheDBWritingMarkDownloadedError: Error { case cannotFindCacheGroup case cannotFindCacheItem case unableToDetermineItemKey case missingMOC } enum CacheDBWritingRemoveError: Error { case cannotFindCacheGroup case cannotFindCacheItem case missingMOC } protocol CacheDBWriting: CacheTaskTracking { var context: NSManagedObjectContext { get } typealias CacheDBWritingCompletionWithURLRequests = (CacheDBWritingResultWithURLRequests) -> Void typealias CacheDBWritingCompletionWithItemAndVariantKeys = (CacheDBWritingResultWithItemAndVariantKeys) -> Void func add(url: URL, groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithURLRequests) func add(urls: [URL], groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithURLRequests) func shouldDownloadVariant(itemKey: CacheController.ItemKey, variant: String?) -> Bool func shouldDownloadVariant(urlRequest: URLRequest) -> Bool func shouldDownloadVariantForAllVariantItems(variant: String?, _ allVariantItems: [CacheController.ItemKeyAndVariant]) -> Bool var fetcher: CacheFetching { get } //default implementations func remove(itemAndVariantKey: CacheController.ItemKeyAndVariant, completion: @escaping (CacheDBWritingResult) -> Void) func remove(groupKey: String, completion: @escaping (CacheDBWritingResult) -> Void) func fetchKeysToRemove(for groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithItemAndVariantKeys) func markDownloaded(urlRequest: URLRequest, response: HTTPURLResponse?, completion: @escaping (CacheDBWritingResult) -> Void) } extension CacheDBWriting { func fetchKeysToRemove(for groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithItemAndVariantKeys) { context.perform { guard let group = CacheDBWriterHelper.cacheGroup(with: groupKey, in: self.context) else { completion(.failure(CacheDBWritingMarkDownloadedError.cannotFindCacheGroup)) return } guard let cacheItems = group.cacheItems as? Set<CacheItem> else { completion(.failure(CacheDBWritingMarkDownloadedError.cannotFindCacheItem)) return } let cacheItemsToRemove = cacheItems.filter({ (cacheItem) -> Bool in return cacheItem.cacheGroups?.count == 1 }) completion(.success(cacheItemsToRemove.compactMap { CacheController.ItemKeyAndVariant(itemKey: $0.key, variant: $0.variant) })) } } func remove(itemAndVariantKey: CacheController.ItemKeyAndVariant, completion: @escaping (CacheDBWritingResult) -> Void) { context.perform { guard let cacheItem = CacheDBWriterHelper.cacheItem(with: itemAndVariantKey.itemKey, variant: itemAndVariantKey.variant, in: self.context) else { completion(.failure(CacheDBWritingRemoveError.cannotFindCacheItem)) return } self.context.delete(cacheItem) CacheDBWriterHelper.save(moc: self.context) { (result) in switch result { case .success: completion(.success) case .failure(let error): completion(.failure(error)) } } } } func remove(groupKey: CacheController.GroupKey, completion: @escaping (CacheDBWritingResult) -> Void) { context.perform { guard let cacheGroup = CacheDBWriterHelper.cacheGroup(with: groupKey, in: self.context) else { completion(.failure(CacheDBWritingRemoveError.cannotFindCacheItem)) return } self.context.delete(cacheGroup) CacheDBWriterHelper.save(moc: self.context) { (result) in switch result { case .success: completion(.success) case .failure(let error): completion(.failure(error)) } } } } func shouldDownloadVariant(urlRequest: URLRequest) -> Bool { guard let itemKey = fetcher.itemKeyForURLRequest(urlRequest) else { return false } let variant = fetcher.variantForURLRequest(urlRequest) return shouldDownloadVariant(itemKey: itemKey, variant: variant) } }
38.59375
157
0.673482
6a2c703c2c8c8d0ce663839c4868755894fad784
65,684
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import SwiftUI /// Global Tokens represent a unified set of constants to be used by Fluent UI. public final class GlobalTokens { // MARK: - BrandColors public enum BrandColorsTokens: CaseIterable { case primary case shade10 case shade20 case shade30 case tint10 case tint20 case tint30 case tint40 } lazy public var brandColors: TokenSet<BrandColorsTokens, DynamicColor> = .init { token in switch token { case .primary: return DynamicColor(light: ColorValue(0x0078D4), dark: ColorValue(0x0086F0)) case .shade10: return DynamicColor(light: ColorValue(0x106EBE), dark: ColorValue(0x1890F1)) case .shade20: return DynamicColor(light: ColorValue(0x005A9E), dark: ColorValue(0x3AA0F3)) case .shade30: return DynamicColor(light: ColorValue(0x004578), dark: ColorValue(0x6CB8F6)) case .tint10: return DynamicColor(light: ColorValue(0x2B88D8), dark: ColorValue(0x0074D3)) case .tint20: return DynamicColor(light: ColorValue(0xC7E0F4), dark: ColorValue(0x004F90)) case .tint30: return DynamicColor(light: ColorValue(0xDEECF9), dark: ColorValue(0x002848)) case .tint40: return DynamicColor(light: ColorValue(0xEFF6FC), dark: ColorValue(0x001526)) } } // MARK: - NeutralColors public enum NeutralColorsToken: CaseIterable { case black case grey2 case grey4 case grey6 case grey8 case grey10 case grey12 case grey14 case grey16 case grey18 case grey20 case grey22 case grey24 case grey26 case grey28 case grey30 case grey32 case grey34 case grey36 case grey38 case grey40 case grey42 case grey44 case grey46 case grey48 case grey50 case grey52 case grey54 case grey56 case grey58 case grey60 case grey62 case grey64 case grey66 case grey68 case grey70 case grey72 case grey74 case grey76 case grey78 case grey80 case grey82 case grey84 case grey86 case grey88 case grey90 case grey92 case grey94 case grey96 case grey98 case white } lazy public var neutralColors: TokenSet<NeutralColorsToken, ColorValue> = .init { token in switch token { case .black: return ColorValue(0x000000) case .grey2: return ColorValue(0x050505) case .grey4: return ColorValue(0x0A0A0A) case .grey6: return ColorValue(0x0F0F0F) case .grey8: return ColorValue(0x141414) case .grey10: return ColorValue(0x1A1A1A) case .grey12: return ColorValue(0x1F1F1F) case .grey14: return ColorValue(0x242424) case .grey16: return ColorValue(0x292929) case .grey18: return ColorValue(0x2E2E2E) case .grey20: return ColorValue(0x333333) case .grey22: return ColorValue(0x383838) case .grey24: return ColorValue(0x3D3D3D) case .grey26: return ColorValue(0x424242) case .grey28: return ColorValue(0x474747) case .grey30: return ColorValue(0x4D4D4D) case .grey32: return ColorValue(0x525252) case .grey34: return ColorValue(0x575757) case .grey36: return ColorValue(0x5C5C5C) case .grey38: return ColorValue(0x616161) case .grey40: return ColorValue(0x666666) case .grey42: return ColorValue(0x6B6B6B) case .grey44: return ColorValue(0x707070) case .grey46: return ColorValue(0x757575) case .grey48: return ColorValue(0x7A7A7A) case .grey50: return ColorValue(0x808080) case .grey52: return ColorValue(0x858585) case .grey54: return ColorValue(0x8A8A8A) case .grey56: return ColorValue(0x8F8F8F) case .grey58: return ColorValue(0x949494) case .grey60: return ColorValue(0x999999) case .grey62: return ColorValue(0x9E9E9E) case .grey64: return ColorValue(0xA3A3A3) case .grey66: return ColorValue(0xA8A8A8) case .grey68: return ColorValue(0xADADAD) case .grey70: return ColorValue(0xB3B3B3) case .grey72: return ColorValue(0xB8B8B8) case .grey74: return ColorValue(0xBDBDBD) case .grey76: return ColorValue(0xC2C2C2) case .grey78: return ColorValue(0xC7C7C7) case .grey80: return ColorValue(0xCCCCCC) case .grey82: return ColorValue(0xD1D1D1) case .grey84: return ColorValue(0xD6D6D6) case .grey86: return ColorValue(0xDBDBDB) case .grey88: return ColorValue(0xE0E0E0) case .grey90: return ColorValue(0xE6E6E6) case .grey92: return ColorValue(0xEBEBEB) case .grey94: return ColorValue(0xF0F0F0) case .grey96: return ColorValue(0xF5F5F5) case .grey98: return ColorValue(0xFAFAFA) case .white: return ColorValue(0xFFFFFF) } } // MARK: - SharedColors public enum SharedColorSets: CaseIterable { case darkRed case burgundy case cranberry case red case darkOrange case bronze case pumpkin case orange case peach case marigold case yellow case gold case brass case brown case darkBrown case lime case forest case seafoam case lightGreen case green case darkGreen case lightTeal case teal case darkTeal case cyan case steel case lightBlue case blue case royalBlue case darkBlue case cornflower case navy case lavender case purple case darkPurple case orchid case grape case berry case lilac case pink case hotPink case magenta case plum case beige case mink case silver case platinum case anchor case charcoal } public enum SharedColorsTokens: CaseIterable { case shade50 case shade40 case shade30 case shade20 case shade10 case primary case tint10 case tint20 case tint30 case tint40 case tint50 case tint60 } lazy public var sharedColors: TokenSet<SharedColorSets, TokenSet<SharedColorsTokens, ColorValue>> = .init { sharedColor in switch sharedColor { case .anchor: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x394146) case .shade10: return ColorValue(0x333A3F) case .shade20: return ColorValue(0x2B3135) case .shade30: return ColorValue(0x202427) case .shade40: return ColorValue(0x111315) case .shade50: return ColorValue(0x090A0B) case .tint10: return ColorValue(0x4D565C) case .tint20: return ColorValue(0x626C72) case .tint30: return ColorValue(0x808A90) case .tint40: return ColorValue(0xBCC3C7) case .tint50: return ColorValue(0xDBDFE1) case .tint60: return ColorValue(0xF6F7F8) } } case .beige: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x7A7574) case .shade10: return ColorValue(0x6E6968) case .shade20: return ColorValue(0x5D5958) case .shade30: return ColorValue(0x444241) case .shade40: return ColorValue(0x252323) case .shade50: return ColorValue(0x141313) case .tint10: return ColorValue(0x8A8584) case .tint20: return ColorValue(0x9A9594) case .tint30: return ColorValue(0xAFABAA) case .tint40: return ColorValue(0xD7D4D4) case .tint50: return ColorValue(0xEAE8E8) case .tint60: return ColorValue(0xFAF9F9) } } case .berry: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xC239B3) case .shade10: return ColorValue(0xAF33A1) case .shade20: return ColorValue(0x932B88) case .shade30: return ColorValue(0x6D2064) case .shade40: return ColorValue(0x3A1136) case .shade50: return ColorValue(0x1F091D) case .tint10: return ColorValue(0xC94CBC) case .tint20: return ColorValue(0xD161C4) case .tint30: return ColorValue(0xDA7ED0) case .tint40: return ColorValue(0xEDBBE7) case .tint50: return ColorValue(0xF5DAF2) case .tint60: return ColorValue(0xFDF5FC) } } case .blue: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x0078D4) case .shade10: return ColorValue(0x006CBF) case .shade20: return ColorValue(0x005BA1) case .shade30: return ColorValue(0x004377) case .shade40: return ColorValue(0x002440) case .shade50: return ColorValue(0x001322) case .tint10: return ColorValue(0x1A86D9) case .tint20: return ColorValue(0x3595DE) case .tint30: return ColorValue(0x5CAAE5) case .tint40: return ColorValue(0xA9D3F2) case .tint50: return ColorValue(0xD0E7F8) case .tint60: return ColorValue(0xF3F9FD) } } case .brass: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x986F0B) case .shade10: return ColorValue(0x89640A) case .shade20: return ColorValue(0x745408) case .shade30: return ColorValue(0x553E06) case .shade40: return ColorValue(0x2E2103) case .shade50: return ColorValue(0x181202) case .tint10: return ColorValue(0xA47D1E) case .tint20: return ColorValue(0xB18C34) case .tint30: return ColorValue(0xC1A256) case .tint40: return ColorValue(0xE0CEA2) case .tint50: return ColorValue(0xEFE4CB) case .tint60: return ColorValue(0xFBF8F2) } } case .bronze: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xA74109) case .shade10: return ColorValue(0x963A08) case .shade20: return ColorValue(0x7F3107) case .shade30: return ColorValue(0x5E2405) case .shade40: return ColorValue(0x321303) case .shade50: return ColorValue(0x1B0A01) case .tint10: return ColorValue(0xB2521E) case .tint20: return ColorValue(0xBC6535) case .tint30: return ColorValue(0xCA8057) case .tint40: return ColorValue(0xE5BBA4) case .tint50: return ColorValue(0xF1D9CC) case .tint60: return ColorValue(0xFBF5F2) } } case .brown: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x8E562E) case .shade10: return ColorValue(0x804D29) case .shade20: return ColorValue(0x6C4123) case .shade30: return ColorValue(0x50301A) case .shade40: return ColorValue(0x2B1A0E) case .shade50: return ColorValue(0x170E07) case .tint10: return ColorValue(0x9C663F) case .tint20: return ColorValue(0xA97652) case .tint30: return ColorValue(0xBB8F6F) case .tint40: return ColorValue(0xDDC3B0) case .tint50: return ColorValue(0xEDDED3) case .tint60: return ColorValue(0xFAF7F4) } } case .burgundy: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xA4262C) case .shade10: return ColorValue(0x942228) case .shade20: return ColorValue(0x7D1D21) case .shade30: return ColorValue(0x5C1519) case .shade40: return ColorValue(0x310B0D) case .shade50: return ColorValue(0x1A0607) case .tint10: return ColorValue(0xAF393E) case .tint20: return ColorValue(0xBA4D52) case .tint30: return ColorValue(0xC86C70) case .tint40: return ColorValue(0xE4AFB2) case .tint50: return ColorValue(0xF0D3D4) case .tint60: return ColorValue(0xFBF4F4) } } case .charcoal: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x393939) case .shade10: return ColorValue(0x333333) case .shade20: return ColorValue(0x2B2B2B) case .shade30: return ColorValue(0x202020) case .shade40: return ColorValue(0x111111) case .shade50: return ColorValue(0x090909) case .tint10: return ColorValue(0x515151) case .tint20: return ColorValue(0x686868) case .tint30: return ColorValue(0x888888) case .tint40: return ColorValue(0xC4C4C4) case .tint50: return ColorValue(0xDFDFDF) case .tint60: return ColorValue(0xF7F7F7) } } case .cornflower: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x4F6BED) case .shade10: return ColorValue(0x4760D5) case .shade20: return ColorValue(0x3C51B4) case .shade30: return ColorValue(0x2C3C85) case .shade40: return ColorValue(0x182047) case .shade50: return ColorValue(0x0D1126) case .tint10: return ColorValue(0x637CEF) case .tint20: return ColorValue(0x778DF1) case .tint30: return ColorValue(0x93A4F4) case .tint40: return ColorValue(0xC8D1FA) case .tint50: return ColorValue(0xE1E6FC) case .tint60: return ColorValue(0xF7F9FE) } } case .cranberry: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xC50F1F) case .shade10: return ColorValue(0xB10E1C) case .shade20: return ColorValue(0x960B18) case .shade30: return ColorValue(0x6E0811) case .shade40: return ColorValue(0x3B0509) case .shade50: return ColorValue(0x200205) case .tint10: return ColorValue(0xCC2635) case .tint20: return ColorValue(0xD33F4C) case .tint30: return ColorValue(0xDC626D) case .tint40: return ColorValue(0xEEACB2) case .tint50: return ColorValue(0xF6D1D5) case .tint60: return ColorValue(0xFDF3F4) } } case .cyan: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x0099BC) case .shade10: return ColorValue(0x008AA9) case .shade20: return ColorValue(0x00748F) case .shade30: return ColorValue(0x005669) case .shade40: return ColorValue(0x002E38) case .shade50: return ColorValue(0x00181E) case .tint10: return ColorValue(0x18A4C4) case .tint20: return ColorValue(0x31AFCC) case .tint30: return ColorValue(0x56BFD7) case .tint40: return ColorValue(0xA4DEEB) case .tint50: return ColorValue(0xCDEDF4) case .tint60: return ColorValue(0xF2FAFC) } } case .darkBlue: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x003966) case .shade10: return ColorValue(0x00335C) case .shade20: return ColorValue(0x002B4E) case .shade30: return ColorValue(0x002039) case .shade40: return ColorValue(0x00111F) case .shade50: return ColorValue(0x000910) case .tint10: return ColorValue(0x0E4A78) case .tint20: return ColorValue(0x215C8B) case .tint30: return ColorValue(0x4178A3) case .tint40: return ColorValue(0x92B5D1) case .tint50: return ColorValue(0xC2D6E7) case .tint60: return ColorValue(0xEFF4F9) } } case .darkBrown: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x4D291C) case .shade10: return ColorValue(0x452519) case .shade20: return ColorValue(0x3A1F15) case .shade30: return ColorValue(0x2B1710) case .shade40: return ColorValue(0x170C08) case .shade50: return ColorValue(0x0C0704) case .tint10: return ColorValue(0x623A2B) case .tint20: return ColorValue(0x784D3E) case .tint30: return ColorValue(0x946B5C) case .tint40: return ColorValue(0xCAADA3) case .tint50: return ColorValue(0xE3D2CB) case .tint60: return ColorValue(0xF8F3F2) } } case .darkGreen: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x0B6A0B) case .shade10: return ColorValue(0x0A5F0A) case .shade20: return ColorValue(0x085108) case .shade30: return ColorValue(0x063B06) case .shade40: return ColorValue(0x032003) case .shade50: return ColorValue(0x021102) case .tint10: return ColorValue(0x1A7C1A) case .tint20: return ColorValue(0x2D8E2D) case .tint30: return ColorValue(0x4DA64D) case .tint40: return ColorValue(0x9AD29A) case .tint50: return ColorValue(0xC6E7C6) case .tint60: return ColorValue(0xF0F9F0) } } case .darkOrange: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xDA3B01) case .shade10: return ColorValue(0xC43501) case .shade20: return ColorValue(0xA62D01) case .shade30: return ColorValue(0x7A2101) case .shade40: return ColorValue(0x411200) case .shade50: return ColorValue(0x230900) case .tint10: return ColorValue(0xDE501C) case .tint20: return ColorValue(0xE36537) case .tint30: return ColorValue(0xE9835E) case .tint40: return ColorValue(0xF4BFAB) case .tint50: return ColorValue(0xF9DCD1) case .tint60: return ColorValue(0xFDF6F3) } } case .darkPurple: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x401B6C) case .shade10: return ColorValue(0x3A1861) case .shade20: return ColorValue(0x311552) case .shade30: return ColorValue(0x240F3C) case .shade40: return ColorValue(0x130820) case .shade50: return ColorValue(0x0A0411) case .tint10: return ColorValue(0x512B7E) case .tint20: return ColorValue(0x633E8F) case .tint30: return ColorValue(0x7E5CA7) case .tint40: return ColorValue(0xB9A3D3) case .tint50: return ColorValue(0xD8CCE7) case .tint60: return ColorValue(0xF5F2F9) } } case .darkRed: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x750B1C) case .shade10: return ColorValue(0x690A19) case .shade20: return ColorValue(0x590815) case .shade30: return ColorValue(0x420610) case .shade40: return ColorValue(0x230308) case .shade50: return ColorValue(0x130204) case .tint10: return ColorValue(0x861B2C) case .tint20: return ColorValue(0x962F3F) case .tint30: return ColorValue(0xAC4F5E) case .tint40: return ColorValue(0xD69CA5) case .tint50: return ColorValue(0xE9C7CD) case .tint60: return ColorValue(0xF9F0F2) } } case .darkTeal: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x006666) case .shade10: return ColorValue(0x005C5C) case .shade20: return ColorValue(0x004E4E) case .shade30: return ColorValue(0x003939) case .shade40: return ColorValue(0x001F1F) case .shade50: return ColorValue(0x001010) case .tint10: return ColorValue(0x0E7878) case .tint20: return ColorValue(0x218B8B) case .tint30: return ColorValue(0x41A3A3) case .tint40: return ColorValue(0x92D1D1) case .tint50: return ColorValue(0xC2E7E7) case .tint60: return ColorValue(0xEFF9F9) } } case .forest: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x498205) case .shade10: return ColorValue(0x427505) case .shade20: return ColorValue(0x376304) case .shade30: return ColorValue(0x294903) case .shade40: return ColorValue(0x162702) case .shade50: return ColorValue(0x0C1501) case .tint10: return ColorValue(0x599116) case .tint20: return ColorValue(0x6BA02B) case .tint30: return ColorValue(0x85B44C) case .tint40: return ColorValue(0xBDD99B) case .tint50: return ColorValue(0xDBEBC7) case .tint60: return ColorValue(0xF6FAF0) } } case .gold: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xC19C00) case .shade10: return ColorValue(0xAE8C00) case .shade20: return ColorValue(0x937700) case .shade30: return ColorValue(0x6C5700) case .shade40: return ColorValue(0x3A2F00) case .shade50: return ColorValue(0x1F1900) case .tint10: return ColorValue(0xC8A718) case .tint20: return ColorValue(0xD0B232) case .tint30: return ColorValue(0xDAC157) case .tint40: return ColorValue(0xECDFA5) case .tint50: return ColorValue(0xF5EECE) case .tint60: return ColorValue(0xFDFBF2) } } case .grape: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x881798) case .shade10: return ColorValue(0x7A1589) case .shade20: return ColorValue(0x671174) case .shade30: return ColorValue(0x4C0D55) case .shade40: return ColorValue(0x29072E) case .shade50: return ColorValue(0x160418) case .tint10: return ColorValue(0x952AA4) case .tint20: return ColorValue(0xA33FB1) case .tint30: return ColorValue(0xB55FC1) case .tint40: return ColorValue(0xD9A7E0) case .tint50: return ColorValue(0xEACEEF) case .tint60: return ColorValue(0xFAF2FB) } } case .green: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x107C10) case .shade10: return ColorValue(0x0E700E) case .shade20: return ColorValue(0x0C5E0C) case .shade30: return ColorValue(0x094509) case .shade40: return ColorValue(0x052505) case .shade50: return ColorValue(0x031403) case .tint10: return ColorValue(0x218C21) case .tint20: return ColorValue(0x359B35) case .tint30: return ColorValue(0x54B054) case .tint40: return ColorValue(0x9FD89F) case .tint50: return ColorValue(0xC9EAC9) case .tint60: return ColorValue(0xF1FAF1) } } case .hotPink: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xE3008C) case .shade10: return ColorValue(0xCC007E) case .shade20: return ColorValue(0xAD006A) case .shade30: return ColorValue(0x7F004E) case .shade40: return ColorValue(0x44002A) case .shade50: return ColorValue(0x240016) case .tint10: return ColorValue(0xE61C99) case .tint20: return ColorValue(0xEA38A6) case .tint30: return ColorValue(0xEE5FB7) case .tint40: return ColorValue(0xF7ADDA) case .tint50: return ColorValue(0xFBD2EB) case .tint60: return ColorValue(0xFEF4FA) } } case .lavender: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x7160E8) case .shade10: return ColorValue(0x6656D1) case .shade20: return ColorValue(0x5649B0) case .shade30: return ColorValue(0x3F3682) case .shade40: return ColorValue(0x221D46) case .shade50: return ColorValue(0x120F25) case .tint10: return ColorValue(0x8172EB) case .tint20: return ColorValue(0x9184EE) case .tint30: return ColorValue(0xA79CF1) case .tint40: return ColorValue(0xD2CCF8) case .tint50: return ColorValue(0xE7E4FB) case .tint60: return ColorValue(0xF9F8FE) } } case .lightBlue: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x3A96DD) case .shade10: return ColorValue(0x3487C7) case .shade20: return ColorValue(0x2C72A8) case .shade30: return ColorValue(0x20547C) case .shade40: return ColorValue(0x112D42) case .shade50: return ColorValue(0x091823) case .tint10: return ColorValue(0x4FA1E1) case .tint20: return ColorValue(0x65ADE5) case .tint30: return ColorValue(0x83BDEB) case .tint40: return ColorValue(0xBFDDF5) case .tint50: return ColorValue(0xDCEDFA) case .tint60: return ColorValue(0xF6FAFE) } } case .lightGreen: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x13A10E) case .shade10: return ColorValue(0x11910D) case .shade20: return ColorValue(0x0E7A0B) case .shade30: return ColorValue(0x0B5A08) case .shade40: return ColorValue(0x063004) case .shade50: return ColorValue(0x031A02) case .tint10: return ColorValue(0x27AC22) case .tint20: return ColorValue(0x3DB838) case .tint30: return ColorValue(0x5EC75A) case .tint40: return ColorValue(0xA7E3A5) case .tint50: return ColorValue(0xCEF0CD) case .tint60: return ColorValue(0xF2FBF2) } } case .lightTeal: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x00B7C3) case .shade10: return ColorValue(0x00A5AF) case .shade20: return ColorValue(0x008B94) case .shade30: return ColorValue(0x00666D) case .shade40: return ColorValue(0x00373A) case .shade50: return ColorValue(0x001D1F) case .tint10: return ColorValue(0x18BFCA) case .tint20: return ColorValue(0x32C8D1) case .tint30: return ColorValue(0x58D3DB) case .tint40: return ColorValue(0xA6E9ED) case .tint50: return ColorValue(0xCEF3F5) case .tint60: return ColorValue(0xF2FCFD) } } case .lilac: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xB146C2) case .shade10: return ColorValue(0x9F3FAF) case .shade20: return ColorValue(0x863593) case .shade30: return ColorValue(0x63276D) case .shade40: return ColorValue(0x35153A) case .shade50: return ColorValue(0x1C0B1F) case .tint10: return ColorValue(0xBA58C9) case .tint20: return ColorValue(0xC36BD1) case .tint30: return ColorValue(0xCF87DA) case .tint40: return ColorValue(0xE6BFED) case .tint50: return ColorValue(0xF2DCF5) case .tint60: return ColorValue(0xFCF6FD) } } case .lime: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x73AA24) case .shade10: return ColorValue(0x689920) case .shade20: return ColorValue(0x57811B) case .shade30: return ColorValue(0x405F14) case .shade40: return ColorValue(0x23330B) case .shade50: return ColorValue(0x121B06) case .tint10: return ColorValue(0x81B437) case .tint20: return ColorValue(0x90BE4C) case .tint30: return ColorValue(0xA4CC6C) case .tint40: return ColorValue(0xCFE5AF) case .tint50: return ColorValue(0xE5F1D3) case .tint60: return ColorValue(0xF8FCF4) } } case .magenta: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xBF0077) case .shade10: return ColorValue(0xAC006B) case .shade20: return ColorValue(0x91005A) case .shade30: return ColorValue(0x6B0043) case .shade40: return ColorValue(0x390024) case .shade50: return ColorValue(0x1F0013) case .tint10: return ColorValue(0xC71885) case .tint20: return ColorValue(0xCE3293) case .tint30: return ColorValue(0xD957A8) case .tint40: return ColorValue(0xECA5D1) case .tint50: return ColorValue(0xF5CEE6) case .tint60: return ColorValue(0xFCF2F9) } } case .marigold: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xEAA300) case .shade10: return ColorValue(0xD39300) case .shade20: return ColorValue(0xB27C00) case .shade30: return ColorValue(0x835B00) case .shade40: return ColorValue(0x463100) case .shade50: return ColorValue(0x251A00) case .tint10: return ColorValue(0xEDAD1C) case .tint20: return ColorValue(0xEFB839) case .tint30: return ColorValue(0xF2C661) case .tint40: return ColorValue(0xF9E2AE) case .tint50: return ColorValue(0xFCEFD3) case .tint60: return ColorValue(0xFEFBF4) } } case .mink: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x5D5A58) case .shade10: return ColorValue(0x54514F) case .shade20: return ColorValue(0x474443) case .shade30: return ColorValue(0x343231) case .shade40: return ColorValue(0x1C1B1A) case .shade50: return ColorValue(0x0F0E0E) case .tint10: return ColorValue(0x706D6B) case .tint20: return ColorValue(0x84817E) case .tint30: return ColorValue(0x9E9B99) case .tint40: return ColorValue(0xCECCCB) case .tint50: return ColorValue(0xE5E4E3) case .tint60: return ColorValue(0xF8F8F8) } } case .navy: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x0027B4) case .shade10: return ColorValue(0x0023A2) case .shade20: return ColorValue(0x001E89) case .shade30: return ColorValue(0x001665) case .shade40: return ColorValue(0x000C36) case .shade50: return ColorValue(0x00061D) case .tint10: return ColorValue(0x173BBD) case .tint20: return ColorValue(0x3050C6) case .tint30: return ColorValue(0x546FD2) case .tint40: return ColorValue(0xA3B2E8) case .tint50: return ColorValue(0xCCD5F3) case .tint60: return ColorValue(0xF2F4FC) } } case .orange: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xF7630C) case .shade10: return ColorValue(0xDE590B) case .shade20: return ColorValue(0xBC4B09) case .shade30: return ColorValue(0x8A3707) case .shade40: return ColorValue(0x4A1E04) case .shade50: return ColorValue(0x271002) case .tint10: return ColorValue(0xF87528) case .tint20: return ColorValue(0xF98845) case .tint30: return ColorValue(0xFAA06B) case .tint40: return ColorValue(0xFDCFB4) case .tint50: return ColorValue(0xFEE5D7) case .tint60: return ColorValue(0xFFF9F5) } } case .orchid: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x8764B8) case .shade10: return ColorValue(0x795AA6) case .shade20: return ColorValue(0x674C8C) case .shade30: return ColorValue(0x4C3867) case .shade40: return ColorValue(0x281E37) case .shade50: return ColorValue(0x16101D) case .tint10: return ColorValue(0x9373C0) case .tint20: return ColorValue(0xA083C9) case .tint30: return ColorValue(0xB29AD4) case .tint40: return ColorValue(0xD7CAEA) case .tint50: return ColorValue(0xE9E2F4) case .tint60: return ColorValue(0xF9F8FC) } } case .peach: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xFF8C00) case .shade10: return ColorValue(0xE67E00) case .shade20: return ColorValue(0xC26A00) case .shade30: return ColorValue(0x8F4E00) case .shade40: return ColorValue(0x4D2A00) case .shade50: return ColorValue(0x291600) case .tint10: return ColorValue(0xFF9A1F) case .tint20: return ColorValue(0xFFA83D) case .tint30: return ColorValue(0xFFBA66) case .tint40: return ColorValue(0xFFDDB3) case .tint50: return ColorValue(0xFFEDD6) case .tint60: return ColorValue(0xFFFAF5) } } case .pink: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xE43BA6) case .shade10: return ColorValue(0xCD3595) case .shade20: return ColorValue(0xAD2D7E) case .shade30: return ColorValue(0x80215D) case .shade40: return ColorValue(0x441232) case .shade50: return ColorValue(0x24091B) case .tint10: return ColorValue(0xE750B0) case .tint20: return ColorValue(0xEA66BA) case .tint30: return ColorValue(0xEF85C8) case .tint40: return ColorValue(0xF7C0E3) case .tint50: return ColorValue(0xFBDDF0) case .tint60: return ColorValue(0xFEF6FB) } } case .platinum: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x69797E) case .shade10: return ColorValue(0x5F6D71) case .shade20: return ColorValue(0x505C60) case .shade30: return ColorValue(0x3B4447) case .shade40: return ColorValue(0x1F2426) case .shade50: return ColorValue(0x111314) case .tint10: return ColorValue(0x79898D) case .tint20: return ColorValue(0x89989D) case .tint30: return ColorValue(0xA0ADB2) case .tint40: return ColorValue(0xCDD6D8) case .tint50: return ColorValue(0xE4E9EA) case .tint60: return ColorValue(0xF8F9FA) } } case .plum: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x77004D) case .shade10: return ColorValue(0x6B0045) case .shade20: return ColorValue(0x5A003B) case .shade30: return ColorValue(0x43002B) case .shade40: return ColorValue(0x240017) case .shade50: return ColorValue(0x13000C) case .tint10: return ColorValue(0x87105D) case .tint20: return ColorValue(0x98246F) case .tint30: return ColorValue(0xAD4589) case .tint40: return ColorValue(0xD696C0) case .tint50: return ColorValue(0xE9C4DC) case .tint60: return ColorValue(0xFAF0F6) } } case .pumpkin: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xCA5010) case .shade10: return ColorValue(0xB6480E) case .shade20: return ColorValue(0x9A3D0C) case .shade30: return ColorValue(0x712D09) case .shade40: return ColorValue(0x3D1805) case .shade50: return ColorValue(0x200D03) case .tint10: return ColorValue(0xD06228) case .tint20: return ColorValue(0xD77440) case .tint30: return ColorValue(0xDF8E64) case .tint40: return ColorValue(0xEFC4AD) case .tint50: return ColorValue(0xF7DFD2) case .tint60: return ColorValue(0xFDF7F4) } } case .purple: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x5C2E91) case .shade10: return ColorValue(0x532982) case .shade20: return ColorValue(0x46236E) case .shade30: return ColorValue(0x341A51) case .shade40: return ColorValue(0x1C0E2B) case .shade50: return ColorValue(0x0F0717) case .tint10: return ColorValue(0x6B3F9E) case .tint20: return ColorValue(0x7C52AB) case .tint30: return ColorValue(0x9470BD) case .tint40: return ColorValue(0xC6B1DE) case .tint50: return ColorValue(0xE0D3ED) case .tint60: return ColorValue(0xF7F4FB) } } case .red: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xD13438) case .shade10: return ColorValue(0xBC2F32) case .shade20: return ColorValue(0x9F282B) case .shade30: return ColorValue(0x751D1F) case .shade40: return ColorValue(0x3F1011) case .shade50: return ColorValue(0x210809) case .tint10: return ColorValue(0xD7494C) case .tint20: return ColorValue(0xDC5E62) case .tint30: return ColorValue(0xE37D80) case .tint40: return ColorValue(0xF1BBBC) case .tint50: return ColorValue(0xF8DADB) case .tint60: return ColorValue(0xFDF6F6) } } case .royalBlue: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x004E8C) case .shade10: return ColorValue(0x00467E) case .shade20: return ColorValue(0x003B6A) case .shade30: return ColorValue(0x002C4E) case .shade40: return ColorValue(0x00172A) case .shade50: return ColorValue(0x000C16) case .tint10: return ColorValue(0x125E9A) case .tint20: return ColorValue(0x286FA8) case .tint30: return ColorValue(0x4A89BA) case .tint40: return ColorValue(0x9ABFDC) case .tint50: return ColorValue(0xC7DCED) case .tint60: return ColorValue(0xF0F6FA) } } case .seafoam: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x00CC6A) case .shade10: return ColorValue(0x00B85F) case .shade20: return ColorValue(0x009B51) case .shade30: return ColorValue(0x00723B) case .shade40: return ColorValue(0x003D20) case .shade50: return ColorValue(0x002111) case .tint10: return ColorValue(0x19D279) case .tint20: return ColorValue(0x34D889) case .tint30: return ColorValue(0x5AE0A0) case .tint40: return ColorValue(0xA8F0CD) case .tint50: return ColorValue(0xCFF7E4) case .tint60: return ColorValue(0xF3FDF8) } } case .silver: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x859599) case .shade10: return ColorValue(0x78868A) case .shade20: return ColorValue(0x657174) case .shade30: return ColorValue(0x4A5356) case .shade40: return ColorValue(0x282D2E) case .shade50: return ColorValue(0x151818) case .tint10: return ColorValue(0x92A1A5) case .tint20: return ColorValue(0xA0AEB1) case .tint30: return ColorValue(0xB3BFC2) case .tint40: return ColorValue(0xD8DFE0) case .tint50: return ColorValue(0xEAEEEF) case .tint60: return ColorValue(0xFAFBFB) } } case .steel: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x005B70) case .shade10: return ColorValue(0x005265) case .shade20: return ColorValue(0x004555) case .shade30: return ColorValue(0x00333F) case .shade40: return ColorValue(0x001B22) case .shade50: return ColorValue(0x000F12) case .tint10: return ColorValue(0x0F6C81) case .tint20: return ColorValue(0x237D92) case .tint30: return ColorValue(0x4496A9) case .tint40: return ColorValue(0x94C8D4) case .tint50: return ColorValue(0xC3E1E8) case .tint60: return ColorValue(0xEFF7F9) } } case .teal: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0x038387) case .shade10: return ColorValue(0x037679) case .shade20: return ColorValue(0x026467) case .shade30: return ColorValue(0x02494C) case .shade40: return ColorValue(0x012728) case .shade50: return ColorValue(0x001516) case .tint10: return ColorValue(0x159195) case .tint20: return ColorValue(0x2AA0A4) case .tint30: return ColorValue(0x4CB4B7) case .tint40: return ColorValue(0x9BD9DB) case .tint50: return ColorValue(0xC7EBEC) case .tint60: return ColorValue(0xF0FAFA) } } case .yellow: return TokenSet<SharedColorsTokens, ColorValue>.init { token in switch token { case .primary: return ColorValue(0xFDE300) case .shade10: return ColorValue(0xE4CC00) case .shade20: return ColorValue(0xC0AD00) case .shade30: return ColorValue(0x8E7F00) case .shade40: return ColorValue(0x4C4400) case .shade50: return ColorValue(0x282400) case .tint10: return ColorValue(0xFDE61E) case .tint20: return ColorValue(0xFDEA3D) case .tint30: return ColorValue(0xFEEE66) case .tint40: return ColorValue(0xFEF7B2) case .tint50: return ColorValue(0xFFFAD6) case .tint60: return ColorValue(0xFFFEF5) } } } } // MARK: - FontSize public enum FontSizeToken: CaseIterable { case size100 case size200 case size300 case size400 case size500 case size600 case size700 case size800 case size900 } lazy public var fontSize: TokenSet<FontSizeToken, CGFloat> = .init { token in switch token { case .size100: return 12.0 case .size200: return 13.0 case .size300: return 15.0 case .size400: return 17.0 case .size500: return 20.0 case .size600: return 22.0 case .size700: return 28.0 case .size800: return 34.0 case .size900: return 60.0 } } // MARK: - FontWeight public enum FontWeightToken: CaseIterable { case regular case medium case semibold case bold } lazy public var fontWeight: TokenSet<FontWeightToken, Font.Weight> = .init { token in switch token { case .regular: return .regular case .medium: return .medium case .semibold: return .semibold case .bold: return .bold } } // MARK: - IconSize public enum IconSizeToken: CaseIterable { case xxxSmall case xxSmall case xSmall case small case medium case large case xLarge case xxLarge case xxxLarge } lazy public var iconSize: TokenSet<IconSizeToken, CGFloat> = .init { token in switch token { case .xxxSmall: return 10 case .xxSmall: return 12 case .xSmall: return 16 case .small: return 20 case .medium: return 24 case .large: return 28 case .xLarge: return 36 case .xxLarge: return 40 case .xxxLarge: return 48 } } // MARK: - Spacing public enum SpacingToken: CaseIterable { case none case xxxSmall case xxSmall case xSmall case small case medium case large case xLarge case xxLarge case xxxLarge case xxxxLarge } lazy public var spacing: TokenSet<SpacingToken, CGFloat> = .init { token in switch token { case .none: return 0 case .xxxSmall: return 2 case .xxSmall: return 4 case .xSmall: return 8 case .small: return 12 case .medium: return 16 case .large: return 20 case .xLarge: return 24 case .xxLarge: return 36 case .xxxLarge: return 48 case .xxxxLarge: return 72 } } // MARK: - BorderRadius public enum BorderRadiusToken: CaseIterable { case none case small case medium case large case xLarge case circle } lazy public var borderRadius: TokenSet<BorderRadiusToken, CGFloat> = .init { token in switch token { case .none: return 0 case .small: return 2 case .medium: return 4 case .large: return 8 case .xLarge: return 12 case .circle: return 9999 } } // MARK: - BorderSize public enum BorderSizeToken: CaseIterable { case none case thin case thick case thicker case thickest } lazy public var borderSize: TokenSet<BorderSizeToken, CGFloat> = .init { token in switch token { case .none: return 0 case .thin: return 1 case .thick: return 2 case .thicker: return 4 case .thickest: return 6 } } // MARK: Initialization public init() {} }
34.735061
126
0.459503
8793369b8263e165cf3963bfcadd80f6505805a8
2,154
// // Character.swift // SuperSmashBrosStats // // Created by Kamaal Farah on 06/06/2020. // Copyright © 2020 Kamaal. All rights reserved. // import SwiftUI struct CodableCharacter: Codable, Hashable, Identifiable { let colorTheme: String let displayName: String let name: String let id: String // swiftlint:disable:this identifier_name let ownerId: Int let fullUrl: String let mainImageUrl: String let thumbnailUrl: String let game: String let related: CodableRelated var colorThemeRGB: Color { let rgb = ColorHelper.hexToRGB(hexString: colorTheme) return Color(red: rgb.red / 255, green: rgb.green / 255, blue: rgb.blue / 255) } private enum CodingKeys: String, CodingKey { case colorTheme = "ColorTheme" case displayName = "DisplayName" case name = "Name" case id = "InstanceId" // swiftlint:disable:this identifier_name case ownerId = "OwnerId" case fullUrl = "FullUrl" case mainImageUrl = "MainImageUrl" case thumbnailUrl = "ThumbnailUrl" case game = "Game" case related = "Related" } struct CodableRelated: Codable, Hashable { let ultimate: CodableRelatedLinks? let smash4: CodableRelatedLinks? private enum CodingKeys: String, CodingKey { // swiftlint:disable:this nesting case ultimate = "Ultimate" case smash4 = "Smash4" } } struct CodableRelatedLinks: Codable, Hashable { let itSelf: String let moves: String private enum CodingKeys: String, CodingKey { // swiftlint:disable:this nesting case itSelf = "Self" case moves = "Moves" } } } struct Character: Hashable, Identifiable { let id: String // swiftlint:disable:this identifier_name let details: CodableCharacter var cachedThumbnailUrl: Data? // swiftlint:disable:next identifier_name init(id: String, details: CodableCharacter, cachedThumbnailUrl: Data? = nil) { self.id = id self.details = details self.cachedThumbnailUrl = cachedThumbnailUrl } }
29.108108
86
0.650418
22c0f6e41eff12d915e66b5a9ac3ce95a929b0a1
2,633
// // ActionInteractor.swift // BellisBox // // Created by Nikita Arkhipov on 18.06.2020. // Copyright © 2020 Anvics. All rights reserved. // import Foundation import Magics public class FastBaseInteractor: NSObject, MagicsInteractor{ public typealias ModifyBlock = (inout URLRequest) -> Void public typealias CompletionBlock = (MagicsJSON, MagicsAPI) -> Void public static var defaultAPI = MagicsAPI() public let relativeURL: String public let api: MagicsAPI public let method: MagicsMethod let modify: ModifyBlock? let complete: CompletionBlock? public init(_ url: String, api: MagicsAPI = FastBaseInteractor.defaultAPI, method: MagicsMethod = .get, modify: ModifyBlock? = nil, complete: CompletionBlock? = nil) { self.relativeURL = url self.api = api self.method = method self.modify = modify self.complete = complete } public convenience init(_ url: String, api: MagicsAPI = FastBaseInteractor.defaultAPI, method: MagicsMethod = .get, json: [String: Any] = [:], complete: CompletionBlock? = nil) { precondition(json.isEmpty || method != .get, "Trying to set json \(json) with \(method) for \(url)") self.init(url, api: api, method: method, modify: { if !json.isEmpty { $0.setJSONBody(with: json, shouldPrintJSON: true) } }, complete: complete) } public func modify(request: URLRequest) -> URLRequest { var r = request print("performing \(method.rawValue.uppercased()) '\(relativeURL)'") modify?(&r) return r } public func process(key: String?, json: MagicsJSON, api: MagicsAPI) { complete?(json, api) } } public class FastArrayInteractor<Model: MagicsModel>: FastBaseInteractor{ public typealias DataBlock = ([Model], MagicsJSON) -> Void public init(_ url: String, api: MagicsAPI = FastBaseInteractor.defaultAPI, method: MagicsMethod = .get, jsonPath: String, modify: ModifyBlock? = nil, complete: @escaping DataBlock) { super.init(url, api: api, method: method, modify: modify, complete: { json, api in guard let js = json[jsonPath] else { complete([], json); return } complete(api.arrayFrom(json: js), json) }) } public convenience init(_ url: String, api: MagicsAPI = FastBaseInteractor.defaultAPI, method: MagicsMethod = .get, jsonPath: String, json: [String: Any] = [:], complete: @escaping DataBlock) { self.init(url, api: api, method: method, jsonPath: jsonPath, modify: { $0.setJSONBody(with: json) }, complete: complete) } }
40.507692
197
0.659324
6acddb9eaee8e53936b3073c37c575c491c3c5fb
318
// // ChatSecretMessages.swift // Stranger-Chat // // Created by Jakub Danielczyk on 09/12/2019. // Copyright © 2019 Jakub Danielczyk. All rights reserved. // import Foundation enum ChatSecretMessages: String, CaseIterable { case endChat = "/chat-disconnect" case conversationId = "/conversationId=" }
18.705882
59
0.713836
2f88501e14ab5c4049c00878a9d6e89da58805d3
2,519
import XCTest @testable import CommandLine class ExecutableSpec: XCTestCase { func testProperties() { let command = CommandMockNonOptionality() let sut = Executable(command: command, arguments: ["argument", Path(components: ["path", "other name"])]) XCTAssertEqual(sut.argumentStrings, ["CommandMockRawValue", "argument", "path/other\\ name", "test", "post"]) XCTAssertEqual(sut.fullCommandStrings, ["test", "arguments", "CommandMockRawValue", "argument", "path/other\\ name", "test", "post"]) XCTAssertEqual(sut.process.launchPath, "test/path") XCTAssertEqual(sut.process.arguments!, ["test", "arguments", "CommandMockRawValue", "argument", "path/other\\ name", "test", "post"]) } static var allTests : [(String, (ExecutableSpec) -> () throws -> Void)] { return [ ("testProperties", testProperties), ] } } class ProcessSpec: XCTestCase { func testProcess() { let sut = Process.standard XCTAssertEqual(sut.launchPath, "/usr/bin/env") XCTAssertNotNil(sut.outputPipe) XCTAssertNotNil(sut.errorPipe) XCTAssertNil(sut.inputPipe) XCTAssertTrue(sut.standardOutput is Pipe) XCTAssertTrue(sut.standardError is Pipe) } func testExecutionSync() { let process = Process.standard let sut = process.execute() XCTAssertNotNil(sut) } func testExecutionAsync() { let process = Process.standard let sut = process.execute(asynchronously: true) XCTAssertNil(sut) } func testExecutionDebug() { let process = Process.standard let sut = process.execute(debug: true) XCTAssertNotNil(sut) } static var allTests : [(String, (ProcessSpec) -> () throws -> Void)] { return [ ("testProcess", testProcess), ("testExecutionSync", testExecutionSync), ("testExecutionAsync", testExecutionAsync), ("testExecutionDebug", testExecutionDebug), ] } } class PipeSpec: XCTestCase { func testProperties() { let process = Process.standard let sut = process.execute()?.error XCTAssertEqual(sut!, [""]) XCTAssertEqual(process.errorPipe!.output, [""]) XCTAssertEqual(process.outputPipe!.output, [""]) } static var allTests : [(String, (PipeSpec) -> () throws -> Void)] { return [ ("testProperties", testProperties), ] } }
33.144737
141
0.613736