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
4bf3a6f68be664da2dbf5c6b4a020d89cce73d76
3,374
import CoreData import CoreSpotlight class PersistentStoreManager { private(set) static var container: NSPersistentContainer! private static let storeName = "books" private static var storeFileName: String { return "\(storeName).sqlite" } /** Creates the NSPersistentContainer, migrating if necessary. */ static func initalisePersistentStore(completion: @escaping () -> ()) { guard container == nil else { fatalError("Attempting to reinitialise the PersistentStoreManager") } let storeLocation = URL.applicationSupport.appendingPathComponent(storeFileName) // Default location of NSPersistentContainer is in the ApplicationSupport directory; // previous versions put the store in the Documents directory. Move it if necessary. moveStoreFromLegacyLocationIfNecessary(toNewLocation: storeLocation) // Migrate the store to the latest version if necessary and then initialise container = NSPersistentContainer(name: storeName, manuallyMigratedStoreAt: storeLocation) container.migrateAndLoad(BooksModelVersion.self) { self.container.viewContext.automaticallyMergesChangesFromParent = true completion() } } /** If a store exists in the Documents directory, copies it to the Application Support directory and destroys the old store. */ private static func moveStoreFromLegacyLocationIfNecessary(toNewLocation newLocation: URL) { let legacyStoreLocation = URL.documents.appendingPathComponent(storeFileName) if FileManager.default.fileExists(atPath: legacyStoreLocation.path) && !FileManager.default.fileExists(atPath: newLocation.path) { print("Store located in Documents directory; migrating to Application Support directory") let tempStoreCoordinator = NSPersistentStoreCoordinator() try! tempStoreCoordinator.replacePersistentStore(at: newLocation, destinationOptions: nil, withPersistentStoreFrom: legacyStoreLocation, sourceOptions: nil, ofType: NSSQLiteStoreType) // Delete the old store tempStoreCoordinator.destroyAndDeleteStore(at: legacyStoreLocation) // The same version (1.7.1) also removed support for spotlight indexing, so deindex everything if CSSearchableIndex.isIndexingAvailable() { CSSearchableIndex.default().deleteAllSearchableItems() } } } /** Deletes all objects of the given type */ static func delete<T>(type: T.Type) where T: NSManagedObject { print("Deleting all \(String(describing: type)) objects") let batchDelete = NSBatchDeleteRequest(fetchRequest: type.fetchRequest()) try! PersistentStoreManager.container.persistentStoreCoordinator.execute(batchDelete, with: container.viewContext) } /** Deletes all data from the persistent store. */ static func deleteAll() { delete(type: List.self) delete(type: Subject.self) delete(type: Book.self) NotificationCenter.default.post(name: Notification.Name.PersistentStoreBatchOperationOccurred, object: nil) } } extension Notification.Name { static let PersistentStoreBatchOperationOccurred = Notification.Name("persistent-store-batch-delete-occurred") }
45.594595
195
0.713397
03a2f45418cccd3f3a66dcbcd8f6b6bac67923ac
1,238
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// /// A finding category that wraps a `Rule` type. /// /// Findings emitted by `SyntaxLintRule` and `SyntaxFormatRule` subclasses automatically emit their /// findings using this category type, via an instance that wraps the calling rule. The displayable /// name of the category is the same as the rule's name provided by the `ruleName` property (which /// defaults to the rule's type name). struct RuleBasedFindingCategory: FindingCategorizing { /// The type of the rule associated with this category. private let ruleType: Rule.Type var description: String { ruleType.ruleName } /// Creates a finding category that wraps the given rule type. init(ruleType: Rule.Type) { self.ruleType = ruleType } }
41.266667
99
0.647819
7a43b5ba2bab40cc02eda53bc9f14dd8d689f4cd
6,247
// // PeripheralsViewController.swift // Harald // // Created by Andrew Shepard on 2/24/18. // Copyright © 2018 Andrew Shepard. All rights reserved. // import Cocoa import CoreBluetooth import Combine import OSLog final class PeripheralsViewController: NSViewController { private var cancellables = Set<AnyCancellable>() public var reloadEvent = PassthroughSubject<Void, Never>() @IBOutlet private weak var tableView: NSTableView! @IBOutlet private weak var statusTextField: NSTextField! @objc private var discovered: [DiscoveredPeripheral] = [] public var searchTermChanged: AnySubscriber<String, Never> { return AnySubscriber(_searchTermChanged) } private let _searchTermChanged = PassthroughSubject<String, Never>() public var manager: CBCentralManager? { didSet { guard let manager = manager else { return } bind(to: manager) } } lazy var peripheralsController: NSArrayController = { let controller = NSArrayController() controller.bind(.contentArray, to: self, withKeyPath: "discovered") return controller }() override func viewDidLoad() { super.viewDidLoad() tableView.bind(.content, to: peripheralsController, withKeyPath: "arrangedObjects") tableView.bind(.selectionIndexes, to: peripheralsController, withKeyPath: "selectionIndexes") bind(to: peripheralsController) reloadEvent .sink { [weak self] _ in guard let this = self else { return } this.closeActiveConnections() this.manager?.stopScan() this.willChangeValue(for: \.discovered) this.discovered = [] this.didChangeValue(for: \.discovered) this.manager?.scanForPeripherals(withServices: nil) } .store(in: &cancellables) _searchTermChanged .eraseToAnyPublisher() .debounce(for: .milliseconds(250), scheduler: RunLoop.main) .map { string -> NSPredicate? in guard string.count != 0 else { return nil } return NSPredicate(format: "peripheral.displayName contains[c] %@", string) } .sink { [weak self] predicate in self?.peripheralsController.filterPredicate = predicate } .store(in: &cancellables) } } extension PeripheralsViewController { func bind(to manager: CBCentralManager) { manager.peripheralCachePublisher .map { $0.map { DiscoveredPeripheral(discovery: $0) } } .sink { [weak self] (discovery) in guard let this = self else { return } this.willChangeValue(for: \.discovered) this.discovered = discovery this.didChangeValue(for: \.discovered) } .store(in: &cancellables) manager.statePublisher .filter { $0 == .poweredOn } // once the manager is powered on, begin periodic scanning .prefix(1) // start a 25 second repeating timer .flatMap { _ -> AnyPublisher<Double, Never> in return RepeatableIntervalTimer(interval: 25.0) .eraseToAnyPublisher() } // begin scanning whenever the timer fires .do(onNext: { [weak self] in os_log("%s: starting scan...", log: OSLog.bluetooth, type: .debug, "\(#function)") self?.manager?.scanForPeripherals( withServices: nil, options: [ CBCentralManagerScanOptionAllowDuplicatesKey: false, CBConnectPeripheralOptionNotifyOnConnectionKey: true, // CBConnectPeripheralOptionNotifyOnDisconnectionKey: false, // CBConnectPeripheralOptionNotifyOnNotificationKey: false ] ) }) // each time we start scanning, start another one-time 10 second timer .flatMap { _ -> AnyPublisher<Double, Never> in return SingleIntervalTimer(interval: 10.0) .eraseToAnyPublisher() } // stop scanning once the second timer fires .do(onNext: { [weak self] in os_log("%s: stopping scan.", log: OSLog.bluetooth, type: .debug, "\(#function)") self?.manager?.stopScan() }) .subscribe(andStoreIn: &cancellables) } func bind(to arrayController: NSArrayController) { arrayController .arrangedObjectsPublisher .map { [weak self] _ -> Int in guard let controller = self?.peripheralsController else { return 0 } guard let objects = controller.arrangedObjects as? [AnyObject] else { return 0 } return objects.count } .map { $0.discoveryDescriptor } .sink { [weak self] (result) in self?.statusTextField.stringValue = result } .store(in: &cancellables) } } extension PeripheralsViewController { private func closeActiveConnections() { guard let discovered = peripheralsController.selectedObjects.first as? DiscoveredPeripheral else { return } manager?.cancelPeripheralConnection(discovered.peripheral) } } private extension CBPeripheral { @objc var displayName: String { guard let name = name else { return "Unknown" } return name // .trimmingLowEnergyPrefix } } private extension Int { var discoveryDescriptor: String { switch self { case 0: return "No peripherals discovered" case 1: return "1 peripheral discovered" default: return "\(self) peripherals discovered" } } } private extension String { var trimmingLowEnergyPrefix: String { if prefix(3) == "LE-" { return String(dropFirst(3)) } else { return self } } }
34.513812
115
0.579638
f8c508f976587cf2b1ec64572bb5f389263fc6c0
24,647
// // ImageCacheTests.swift // Kingfisher // // Created by Wei Wang on 15/4/10. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Kingfisher class ImageCacheTests: XCTestCase { var cache: ImageCache! var observer: NSObjectProtocol! override func setUp() { super.setUp() let uuid = UUID().uuidString let cacheName = "test-\(uuid)" cache = ImageCache(name: cacheName) } override func tearDown() { clearCaches([cache]) cache = nil observer = nil super.tearDown() } func testInvalidCustomCachePath() { let customPath = "/path/to/image/cache" let url = URL(fileURLWithPath: customPath) XCTAssertThrowsError(try ImageCache(name: "test", cacheDirectoryURL: url)) { error in guard case KingfisherError.cacheError(reason: .cannotCreateDirectory(let path, _)) = error else { XCTFail("Should be KingfisherError with cacheError reason.") return } XCTAssertEqual(path, customPath + "/com.onevcat.Kingfisher.ImageCache.test") } } func testCustomCachePath() { let cacheURL = try! FileManager.default.url( for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let subFolder = cacheURL.appendingPathComponent("temp") let customPath = subFolder.path let cache = try! ImageCache(name: "test", cacheDirectoryURL: subFolder) XCTAssertEqual( cache.diskStorage.directoryURL.path, (customPath as NSString).appendingPathComponent("com.onevcat.Kingfisher.ImageCache.test")) clearCaches([cache]) } func testCustomCachePathByBlock() { let cache = try! ImageCache(name: "test", cacheDirectoryURL: nil, diskCachePathClosure: { (url, path) -> URL in let modifiedPath = path + "-modified" return url.appendingPathComponent(modifiedPath, isDirectory: true) }) let cacheURL = try! FileManager.default.url( for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) XCTAssertEqual( cache.diskStorage.directoryURL.path, (cacheURL.path as NSString).appendingPathComponent("com.onevcat.Kingfisher.ImageCache.test-modified")) clearCaches([cache]) } func testMaxCachePeriodInSecond() { cache.diskStorage.config.expiration = .seconds(1) XCTAssertEqual(cache.diskStorage.config.expiration.timeInterval, 1) } func testMaxMemorySize() { cache.memoryStorage.config.totalCostLimit = 1 XCTAssert(cache.memoryStorage.config.totalCostLimit == 1, "maxMemoryCost should be able to be set.") } func testMaxDiskCacheSize() { cache.diskStorage.config.sizeLimit = 1 XCTAssert(cache.diskStorage.config.sizeLimit == 1, "maxDiskCacheSize should be able to be set.") } func testClearDiskCache() { let exp = expectation(description: #function) let key = testKeys[0] <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: key, toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: key, toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data, forKey: key, toDisk: true) { >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in >>>>>>> onevcat/master self.cache.clearMemoryCache() let cacheResult = self.cache.imageCachedType(forKey: key) XCTAssertTrue(cacheResult.cached) XCTAssertEqual(cacheResult, .disk) self.cache.clearDiskCache { let cacheResult = self.cache.imageCachedType(forKey: key) XCTAssertFalse(cacheResult.cached) exp.fulfill() } } waitForExpectations(timeout: 3, handler:nil) } func testClearMemoryCache() { <<<<<<< HEAD let expectation = self.expectation(description: "wait for retrieving image") <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in >>>>>>> onevcat/master ======= let exp = expectation(description: #function) let key = testKeys[0] cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in >>>>>>> onevcat/master self.cache.clearMemoryCache() self.cache.retrieveImage(forKey: key) { result in XCTAssertNotNil(result.value?.image) XCTAssertEqual(result.value?.cacheType, .disk) exp.fulfill() } } waitForExpectations(timeout: 3, handler: nil) } func testNoImageFound() { let exp = expectation(description: #function) cache.retrieveImage(forKey: testKeys[0]) { result in XCTAssertNotNil(result.value) XCTAssertNil(result.value!.image) exp.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func testCachedFileDoesNotExist() { let URLString = testKeys[0] let url = URL(string: URLString)! let exists = cache.imageCachedType(forKey: url.cacheKey).cached XCTAssertFalse(exists) } func testStoreImageInMemory() { let exp = expectation(description: #function) let key = testKeys[0] cache.store(testImage, forKey: key, toDisk: false) { _ in self.cache.retrieveImage(forKey: key) { result in XCTAssertNotNil(result.value?.image) XCTAssertEqual(result.value?.cacheType, .memory) exp.fulfill() } } waitForExpectations(timeout: 3, handler: nil) } func testStoreMultipleImages() { let exp = expectation(description: #function) storeMultipleImages { let diskCachePath = self.cache.diskStorage.directoryURL.path var files: [String] = [] do { files = try FileManager.default.contentsOfDirectory(atPath: diskCachePath) } catch _ { XCTFail() } XCTAssertEqual(files.count, testKeys.count) exp.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func testCachedFileExists() { let exp = expectation(description: #function) let key = testKeys[0] let url = URL(string: key)! let exists = cache.imageCachedType(forKey: url.cacheKey).cached XCTAssertFalse(exists) cache.retrieveImage(forKey: key) { result in switch result { case .success(let value): XCTAssertNil(value.image) XCTAssertEqual(value.cacheType, .none) case .failure: XCTFail() return } self.cache.store(testImage, forKey: key, toDisk: true) { _ in self.cache.retrieveImage(forKey: key) { result in XCTAssertNotNil(result.value?.image) XCTAssertEqual(result.value?.cacheType, .memory) self.cache.clearMemoryCache() self.cache.retrieveImage(forKey: key) { result in XCTAssertNotNil(result.value?.image) XCTAssertEqual(result.value?.cacheType, .disk) exp.fulfill() } } } } waitForExpectations(timeout: 3, handler: nil) } func testCachedFileWithCustomPathExtensionExists() { cache.diskStorage.config.pathExtension = "jpg" let exp = expectation(description: #function) let key = testKeys[0] let url = URL(string: key)! cache.store(testImage, forKey: key, toDisk: true) { _ in let cachePath = self.cache.cachePath(forKey: url.cacheKey) XCTAssertTrue(cachePath.hasSuffix(".jpg")) exp.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func testCachedImageIsFetchedSyncronouslyFromTheMemoryCache() { cache.store(testImage, forKey: testKeys[0], toDisk: false) var foundImage: Image? cache.retrieveImage(forKey: testKeys[0]) { result in foundImage = result.value?.image } XCTAssertEqual(testImage, foundImage) } func testIsImageCachedForKey() { <<<<<<< HEAD let expectation = self.expectation(description: "wait for caching image") <<<<<<< HEAD XCTAssert(self.cache.isImageCached(forKey: testKeys[0]).cached == false, "This image should not be cached yet.") <<<<<<< HEAD self.cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in ======= self.cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in >>>>>>> onevcat/master XCTAssert(self.cache.isImageCached(forKey: testKeys[0]).cached == true, "This image should be already cached.") ======= XCTAssert(self.cache.imageCachedType(forKey: testKeys[0]).cached == false, "This image should not be cached yet.") self.cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in XCTAssert(self.cache.imageCachedType(forKey: testKeys[0]).cached == true, "This image should be already cached.") >>>>>>> onevcat/master expectation.fulfill() } self.waitForExpectations(timeout: 5, handler: nil) } func testRetrievingImagePerformance() { let expectation = self.expectation(description: "wait for retrieving image") <<<<<<< HEAD <<<<<<< HEAD self.cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in ======= self.cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in >>>>>>> onevcat/master ======= self.cache.store(testImage, original: testImageData as Data, forKey: testKeys[0], toDisk: true) { () -> Void in >>>>>>> onevcat/master self.measure({ () -> Void in for _ in 1 ..< 200 { _ = self.cache.retrieveImageInDiskCache(forKey: testKeys[0]) } }) expectation.fulfill() ======= let exp = expectation(description: #function) let key = testKeys[0] XCTAssertFalse(cache.imageCachedType(forKey: key).cached) cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in XCTAssertTrue(self.cache.imageCachedType(forKey: key).cached) exp.fulfill() >>>>>>> onevcat/master } waitForExpectations(timeout: 3, handler: nil) } func testCleanDiskCacheNotification() { <<<<<<< HEAD let expectation = self.expectation(description: "wait for retrieving image") <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in >>>>>>> onevcat/master ======= let exp = expectation(description: #function) let key = testKeys[0] >>>>>>> onevcat/master cache.diskStorage.config.expiration = .seconds(0.01) cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in self.observer = NotificationCenter.default.addObserver( forName: .KingfisherDidCleanDiskCache, object: self.cache, queue: .main) { noti in let receivedCache = noti.object as? ImageCache XCTAssertNotNil(receivedCache) XCTAssertTrue(receivedCache === self.cache) guard let hashes = noti.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] else { XCTFail("Notification should contains Strings in key 'KingfisherDiskCacheCleanedHashKey'") exp.fulfill() return } XCTAssertEqual(hashes.count, 1) XCTAssertEqual(hashes.first!, self.cache.hash(forKey: key)) NotificationCenter.default.removeObserver(self.observer) exp.fulfill() } delay(1) { self.cache.cleanExpiredDiskCache() } } waitForExpectations(timeout: 2, handler: nil) } func testCannotRetrieveCacheWithProcessorIdentifier() { let exp = expectation(description: #function) let key = testKeys[0] let p = RoundCornerImageProcessor(cornerRadius: 40) <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in >>>>>>> onevcat/master self.cache.retrieveImage(forKey: testKeys[0], options: [.processor(p)], completionHandler: { (image, type) -> Void in XCTAssert(image == nil, "The image with prosossor should not be cached yet.") expectation.fulfill() }) ======= cache.store(testImage, original: testImageData, forKey: key, toDisk: true) { _ in self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in XCTAssertNotNil(result.value) XCTAssertNil(result.value!.image) exp.fulfill() } >>>>>>> onevcat/master } waitForExpectations(timeout: 3, handler: nil) } func testRetrieveCacheWithProcessorIdentifier() { let exp = expectation(description: #function) let key = testKeys[0] let p = RoundCornerImageProcessor(cornerRadius: 40) <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], processorIdentifier: p.identifier,toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], processorIdentifier: p.identifier,toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], processorIdentifier: p.identifier,toDisk: true) { () -> Void in >>>>>>> onevcat/master ======= cache.store( testImage, original: testImageData, forKey: key, processorIdentifier: p.identifier, toDisk: true) { _ in self.cache.retrieveImage(forKey: key, options: [.processor(p)]) { result in XCTAssertNotNil(result.value?.image) exp.fulfill() } } waitForExpectations(timeout: 3, handler: nil) } func testDefaultCache() { let exp = expectation(description: #function) let key = testKeys[0] let cache = ImageCache.default cache.store(testImage, forKey: key) { _ in XCTAssertTrue(cache.memoryStorage.isCached(forKey: key)) XCTAssertTrue(cache.diskStorage.isCached(forKey: key)) cleanDefaultCache() exp.fulfill() } waitForExpectations(timeout: 3, handler: nil) } func testRetrieveDiskCacheSynchronously() { let exp = expectation(description: #function) let key = testKeys[0] cache.store(testImage, forKey: key, toDisk: true) { _ in var cacheType = self.cache.imageCachedType(forKey: key) XCTAssertEqual(cacheType, .memory) >>>>>>> onevcat/master try! self.cache.memoryStorage.remove(forKey: key) cacheType = self.cache.imageCachedType(forKey: key) XCTAssertEqual(cacheType, .disk) var dispatched = false self.cache.retrieveImageInDiskCache(forKey: key, options: [.loadDiskFileSynchronously]) { result in XCTAssertFalse(dispatched) exp.fulfill() } // This should be called after the completion handler above. dispatched = true } waitForExpectations(timeout: 3, handler: nil) } func testRetrieveDiskCacheAsynchronously() { let exp = expectation(description: #function) let key = testKeys[0] cache.store(testImage, forKey: key, toDisk: true) { _ in var cacheType = self.cache.imageCachedType(forKey: key) XCTAssertEqual(cacheType, .memory) try! self.cache.memoryStorage.remove(forKey: key) cacheType = self.cache.imageCachedType(forKey: key) XCTAssertEqual(cacheType, .disk) var dispatched = false self.cache.retrieveImageInDiskCache(forKey: key, options: nil) { result in XCTAssertTrue(dispatched) exp.fulfill() } // This should be called before the completion handler above. dispatched = true } waitForExpectations(timeout: 3, handler: nil) } #if os(iOS) || os(tvOS) || os(watchOS) func testGettingMemoryCachedImageCouldBeModified() { let exp = expectation(description: #function) let key = testKeys[0] var modifierCalled = false let modifier = AnyImageModifier { image in modifierCalled = true return image.withRenderingMode(.alwaysTemplate) } cache.store(testImage, original: testImageData, forKey: key) { _ in self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in XCTAssertTrue(modifierCalled) XCTAssertEqual(result.value?.image?.renderingMode, .alwaysTemplate) exp.fulfill() } } waitForExpectations(timeout: 3, handler: nil) } func testGettingDiskCachedImageCouldBeModified() { let exp = expectation(description: #function) let key = testKeys[0] var modifierCalled = false let modifier = AnyImageModifier { image in modifierCalled = true return image.withRenderingMode(.alwaysTemplate) } cache.store(testImage, original: testImageData, forKey: key) { _ in self.cache.clearMemoryCache() self.cache.retrieveImage(forKey: key, options: [.imageModifier(modifier)]) { result in XCTAssertTrue(modifierCalled) XCTAssertEqual(result.value?.image?.renderingMode, .alwaysTemplate) exp.fulfill() } } waitForExpectations(timeout: 3, handler: nil) } #endif func testStoreToMemoryWithExpiration() { let exp = expectation(description: #function) let key = testKeys[0] cache.store( testImage, original: testImageData, forKey: key, options: KingfisherParsedOptionsInfo([.memoryCacheExpiration(.seconds(0.2))]), toDisk: true) { _ in XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory) delay(1) { XCTAssertEqual(self.cache.imageCachedType(forKey: key), .disk) exp.fulfill() } } waitForExpectations(timeout: 5, handler: nil) } func testStoreToDiskWithExpiration() { let exp = expectation(description: #function) let key = testKeys[0] cache.store( testImage, original: testImageData, forKey: key, options: KingfisherParsedOptionsInfo([.diskCacheExpiration(.expired)]), toDisk: true) { _ in XCTAssertEqual(self.cache.imageCachedType(forKey: key), .memory) self.cache.clearMemoryCache() XCTAssertEqual(self.cache.imageCachedType(forKey: key), .none) exp.fulfill() } waitForExpectations(timeout: 3, handler: nil) } // MARK: - Helper func storeMultipleImages(_ completionHandler: @escaping () -> Void) { let group = DispatchGroup() <<<<<<< HEAD group.enter() <<<<<<< HEAD <<<<<<< HEAD cache.store(testImage, original: testImageData as? Data, forKey: testKeys[0], toDisk: true) { () -> () in group.leave() } group.enter() cache.store(testImage, original: testImageData as? Data, forKey: testKeys[1], toDisk: true) { () -> () in group.leave() } group.enter() cache.store(testImage, original: testImageData as? Data, forKey: testKeys[2], toDisk: true) { () -> () in group.leave() } group.enter() cache.store(testImage, original: testImageData as? Data, forKey: testKeys[3], toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> () in ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[0], toDisk: true) { () -> Void in >>>>>>> onevcat/master group.leave() } group.enter() cache.store(testImage, original: testImageData as Data?, forKey: testKeys[1], toDisk: true) { () -> Void in group.leave() } group.enter() cache.store(testImage, original: testImageData as Data?, forKey: testKeys[2], toDisk: true) { () -> Void in group.leave() } group.enter() <<<<<<< HEAD cache.store(testImage, original: testImageData as Data?, forKey: testKeys[3], toDisk: true) { () -> () in >>>>>>> onevcat/master ======= cache.store(testImage, original: testImageData as Data?, forKey: testKeys[3], toDisk: true) { () -> Void in >>>>>>> onevcat/master group.leave() ======= testKeys.forEach { group.enter() cache.store(testImage, original: testImageData, forKey: $0, toDisk: true) { _ in group.leave() } >>>>>>> onevcat/master } group.notify(queue: .main, execute: completionHandler) } }
38.510938
149
0.592648
8a57bbc610cc1c4c68fe5a20549b021b39feec1f
1,256
// // MyGestureVC.swift // Swift_Info // // Created by hello on 2018/11/14. // Copyright © 2018 William. All rights reserved. // import UIKit class MyGestureVC: UIViewController { lazy var gesturesView: GestureBlockView = { let itemWidth: CGFloat = ScreenWIDTH - 80 let gesturesV = GestureBlockView.init(frame: CGRect(x: 40, y: ScreenHEIGHT / 2 - itemWidth / 2, width: itemWidth, height: itemWidth)) gesturesV.backgroundColor = UIColor.green return gesturesV }() override func viewDidLoad() { super.viewDidLoad() title = "手势密码" view.backgroundColor = UIColor.yellow self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "重置", style: .plain, target: self, action: #selector(btnClick)) view.addSubview(gesturesView) gesturesView.sendGestureClousure = {(numbers:Array<String>) -> Void in print(numbers) } } @objc func btnClick() { gesturesView.reset() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = false hidesBottomBarWhenPushed = true } }
27.911111
141
0.634554
48d7cab5bb90d818b098bff34ced08e952d88c03
987
// // RealmService.swift // VKClient // // Created by Сергей Черных on 21.10.2021. // import UIKit import RealmSwift class RealmService { static let deleteIfMigration = Realm.Configuration(deleteRealmIfMigrationNeeded: true) static func save<T:Object>( items: [T], configuration: Realm.Configuration = deleteIfMigration, update: Realm.UpdatePolicy = .modified) throws { let realm = try Realm(configuration: configuration) // print(configuration.fileURL ?? "") try realm.write { realm.add( items, update: update) } } static func load<T:Object>(typeOf: T.Type) throws -> Results<T> { let realm = try Realm() return realm.objects(T.self) } static func delete<T: Object>(object: T) throws { let realm = try Realm() try realm.write { realm.delete(object) } } }
25.307692
90
0.567376
b91afc8df0ac10d03d4e79a29ce10f6212c3eede
896
// // Array+SwiftyChrono.swift // Clendar // // Created by Vinh Nguyen on 24/3/19. // Copyright © 2019 Vinh Nguyen. All rights reserved. // import Foundation import SwiftyChrono extension Array where Element == ParsedResult { // swiftlint:disable large_tuple func process(with input: String) -> (action: String, startDate: Date, endDate: Date?) { var dateTexts = [String]() var startDate = Date().nextHour var endDate: Date? for result in self { dateTexts.append(result.text) startDate = result.start.date endDate = result.end?.date ?? startDate.offsetWithDefaultDuration } var commonAction = [String]() for dateText in dateTexts { let text = input.trim(text: dateText) commonAction.append(text) } let action = commonAction.isEmpty == false ? commonAction.commonText : input return (action, startDate, endDate) } // swiftlint:enable large_tuple }
24.216216
88
0.710938
622a88aa19ff3c23eb2cb5521e73613484e86a8c
3,565
// // EmptyViewModel.swift // ViewModel // // Created by Григорий Сухоруков on 15/02/2020. // Copyright © 2020 Григорий Сухоруков. All rights reserved. // import YogaKit import YogaUI typealias ViewModelBuilder = ResultBuilder<EmptyViewModel> class EmptyViewModel: NSObject { private(set) var yoga: YGLayout! var frame: CGRect = .zero fileprivate(set) var bounds: CGRect = .zero private var layoutIsValid = false private(set) var subviews: [EmptyViewModel] = [] override init() { super.init() yoga = YGLayout(layoutNode: self) yoga.isEnabled = true } func add(_ subview: EmptyViewModel) { subviews.append(subview) } func add(_ generator: () -> EmptyViewModel) { let subview = generator() add(subview) } @discardableResult func childs(@ViewModelBuilder _ constructor: () -> [EmptyViewModel]) -> Self { let submodels = constructor() for submodel in submodels { if submodel === self { fatalError("Trying to add view as it's subview") } add(submodel) } return self } @discardableResult func layout(_ configurator: (YGLayout) -> ()) -> Self { configurator(yoga) invalidateLayout() return self } func bind(toContainer container: UIView, origin: CGPoint, viewStorage: ViewStorage?) { for subview in subviews { subview.bind(toContainer: container, origin: origin, viewStorage: viewStorage) } } func unbind(withViewStorage viewStorage: ViewStorage?) { for subview in subviews { subview.unbind(withViewStorage: viewStorage) } } func sizeThatFits(_ size: CGSize) -> CGSize { return .zero } func layout(with containerSize: CGSize) { self.bounds = CGRect(origin: .zero, size: containerSize) yoga.applyLayout(preservingOrigin: false) layoutIsValid = false } func layoutIfNeeded(with containerSize: CGSize) { if needsLayout() { layout(with: containerSize) } } func invalidateLayout() { layoutIsValid = false yoga.markDirty() } func needsLayout() -> Bool { guard layoutIsValid else { return true } for subview in subviews { if !subview.layoutIsValid { return true } } for subview in subviews { if subview.needsLayout() { return true } } return false } func applyLayout() { for subview in subviews { subview.applyLayout() } } func configureViewsTree() { for subview in subviews { subview.configureViewsTree() } } } // YGLayoutNode: extension EmptyViewModel: YGLayoutNode { var isUIView: Bool { return false } var subnodes: [YGLayoutNode] { return subviews } func safeSetFrame(_ frame: CGRect) { self.frame = frame } } extension EmptyViewModel { func width(_ w: YGValue) -> Self { yoga.width = w return self } func height(_ h: YGValue) -> Self { yoga.height = h return self } func size(_ size: CGSize) -> Self { yoga.width = YGValue(size.width) yoga.height = YGValue(size.height) return self } }
22.707006
101
0.561851
91b50d3ba874b3f821e91ad4e098d43aae8521ea
461
// // DeviceIdentifier+installedDeviceIdentifier_iOS.swift // AppReceiptValidator macOS // // Created by Hannes Oud on 06.09.17. // Copyright © 2017 IdeasOnCanvas GmbH. All rights reserved. // import UIKit extension AppReceiptValidator.Parameters.DeviceIdentifier { /// On iOS this is the UIDevice's identifierForVendor UUID data static var installedDeviceIdentifierData: Data? { return UIDevice.current.identifierForVendor?.data } }
25.611111
67
0.754881
20aca9adb5cdaa9f760b48c312e76f48712807b2
9,669
// // Delaunay.swift // TrainAndTouch // // Created by Erich Flock on 02.06.19. // Copyright © 2019 flock. All rights reserved. // based onhttps://github.com/ahashim1/Face // import Foundation import Darwin import UIKit open class Delaunay { public init() { } /* Generates a supertraingle containing all other triangles */ fileprivate func supertriangle(_ vertices: [Vertex]) -> [Vertex] { var xmin = Double(Int32.max) var ymin = Double(Int32.max) var xmax = -Double(Int32.max) var ymax = -Double(Int32.max) for i in 0..<vertices.count { if vertices[i].x < xmin { xmin = vertices[i].x } if vertices[i].x > xmax { xmax = vertices[i].x } if vertices[i].y < ymin { ymin = vertices[i].y } if vertices[i].y > ymax { ymax = vertices[i].y } } let dx = xmax - xmin let dy = ymax - ymin let dmax = max(dx, dy) let xmid = xmin + dx * 0.5 let ymid = ymin + dy * 0.5 return [ Vertex(x: xmid - 20 * dmax, y: ymid - dmax), Vertex(x: xmid, y: ymid + 20 * dmax), Vertex(x: xmid + 20 * dmax, y: ymid - dmax) ] } /* Calculate a circumcircle for a set of 3 vertices */ fileprivate func circumcircle(_ i: Vertex, j: Vertex, k: Vertex) -> Circumcircle { let x1 = i.x let y1 = i.y let x2 = j.x let y2 = j.y let x3 = k.x let y3 = k.y let xc: Double let yc: Double let fabsy1y2 = abs(y1 - y2) let fabsy2y3 = abs(y2 - y3) if fabsy1y2 < .ulpOfOne { let m2 = -((x3 - x2) / (y3 - y2)) let mx2 = (x2 + x3) / 2 let my2 = (y2 + y3) / 2 xc = (x2 + x1) / 2 yc = m2 * (xc - mx2) + my2 } else if fabsy2y3 < .ulpOfOne { let m1 = -((x2 - x1) / (y2 - y1)) let mx1 = (x1 + x2) / 2 let my1 = (y1 + y2) / 2 xc = (x3 + x2) / 2 yc = m1 * (xc - mx1) + my1 } else { let m1 = -((x2 - x1) / (y2 - y1)) let m2 = -((x3 - x2) / (y3 - y2)) let mx1 = (x1 + x2) / 2 let mx2 = (x2 + x3) / 2 let my1 = (y1 + y2) / 2 let my2 = (y2 + y3) / 2 xc = (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2) if fabsy1y2 > fabsy2y3 { yc = m1 * (xc - mx1) + my1 } else { yc = m2 * (xc - mx2) + my2 } } let dx = x2 - xc let dy = y2 - yc let rsqr = dx * dx + dy * dy return Circumcircle(vertex1: i, vertex2: j, vertex3: k, x: xc, y: yc, rsqr: rsqr) } fileprivate func dedup(_ edges: [Vertex]) -> [Vertex] { var e = edges var a: Vertex?, b: Vertex?, m: Vertex?, n: Vertex? var j = e.count while j > 0 { j -= 1 b = j < e.count ? e[j] : nil j -= 1 a = j < e.count ? e[j] : nil var i = j while i > 0 { i -= 1 n = e[i] i -= 1 m = e[i] if (a == m && b == n) || (a == n && b == m) { e.removeSubrange(j...j + 1) e.removeSubrange(i...i + 1) break } } } return e } open func triangulate(_ vertices: [Vertex]) -> [Triangle] { var _vertices = vertices.removeDuplicates() guard _vertices.count >= 3 else { return [Triangle]() } let n = _vertices.count var open = [Circumcircle]() var completed = [Circumcircle]() var edges = [Vertex]() /* Make an array of indices into the vertex array, sorted by the * vertices' x-position. */ let indices = [Int](0..<n).sorted { _vertices[$0].x < _vertices[$1].x } /* Next, find the vertices of the supertriangle (which contains all other * triangles) */ _vertices += supertriangle(_vertices) /* Initialize the open list (containing the supertriangle and nothing * else) and the closed list (which is empty since we havn't processed * any triangles yet). */ open.append(circumcircle(_vertices[n], j: _vertices[n + 1], k: _vertices[n + 2])) /* Incrementally add each vertex to the mesh. */ for i in 0..<n { let c = indices[i] edges.removeAll() /* For each open triangle, check to see if the current point is * inside it's circumcircle. If it is, remove the triangle and add * it's edges to an edge list. */ for j in (0..<open.count).reversed() { /* If this point is to the right of this triangle's circumcircle, * then this triangle should never get checked again. Remove it * from the open list, add it to the closed list, and skip. */ let dx = _vertices[c].x - open[j].x if dx > 0 && dx * dx > open[j].rsqr { completed.append(open.remove(at: j)) continue } /* If we're outside the circumcircle, skip this triangle. */ let dy = _vertices[c].y - open[j].y if dx * dx + dy * dy - open[j].rsqr > .ulpOfOne { continue } /* Remove the triangle and add it's edges to the edge list. */ edges += [ open[j].vertex1, open[j].vertex2, open[j].vertex2, open[j].vertex3, open[j].vertex3, open[j].vertex1 ] open.remove(at: j) } /* Remove any doubled edges. */ edges = dedup(edges) /* Add a new triangle for each edge. */ var j = edges.count while j > 0 { j -= 1 let b = edges[j] j -= 1 let a = edges[j] open.append(circumcircle(a, j: b, k: _vertices[c])) } } /* Copy any remaining open triangles to the closed list, and then * remove any triangles that share a vertex with the supertriangle, * building a list of triplets that represent triangles. */ completed += open let ignored: Set<Vertex> = [_vertices[n], _vertices[n + 1], _vertices[n + 2]] let results = completed.compactMap { (circumCircle) -> Triangle? in let current: Set<Vertex> = [circumCircle.vertex1, circumCircle.vertex2, circumCircle.vertex3] let intersection = ignored.intersection(current) if intersection.count > 0 { return nil } return Triangle(vertex1: circumCircle.vertex1, vertex2: circumCircle.vertex2, vertex3: circumCircle.vertex3) } /* Yay, we're done! */ return results } } public struct Vertex: Hashable { public init(x: Double, y: Double) { self.x = x self.y = y } public let x: Double public let y: Double } extension Vertex: Equatable { } public func ==(lhs: Vertex, rhs: Vertex) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } extension Array where Element:Equatable { func removeDuplicates() -> [Element] { var result = [Element]() for value in self { if result.contains(value) == false { result.append(value) } } return result } } //extension Vertex: Hashable { // public var hashValue: Int { // return "\(x)\(y)".hashValue // } //} /// A simple struct representing 3 vertices public struct Triangle { public init(vertex1: Vertex, vertex2: Vertex, vertex3: Vertex) { self.vertex1 = vertex1 self.vertex2 = vertex2 self.vertex3 = vertex3 } public let vertex1: Vertex public let vertex2: Vertex public let vertex3: Vertex } /// Represents a bounding circle for a set of 3 vertices internal struct Circumcircle { let vertex1: Vertex let vertex2: Vertex let vertex3: Vertex let x: Double let y: Double let rsqr: Double } class Line { var start: CGPoint var end: CGPoint var color: UIColor var brushWidth: CGFloat init(start startPoint: CGPoint, end endPoint: CGPoint, color drawColor: UIColor, brushWidth lineWidth: CGFloat){ start = startPoint end = endPoint color = drawColor brushWidth = lineWidth } } extension Triangle { func toPath() -> CGPath { let path = CGMutablePath() let point1 = vertex1.pointValue() let point2 = vertex2.pointValue() let point3 = vertex3.pointValue() path.move(to: point1) path.addLine(to: point2) path.addLine(to: point3) path.addLine(to: point1) path.closeSubpath() return path } } extension Vertex { func pointValue() -> CGPoint { return CGPoint(x: x, y: y) } }
29.750769
120
0.477402
263126153560305cf2557d6d09abefec1dbb6c84
3,595
// // CollectionViewController.swift // FourSquareProject1 // // Created by Alfredo Barragan on 2/11/19. // Copyright © 2019 Alfredo Barragan. All rights reserved. // import UIKit class CollectionViewController: UIViewController { let controlView = CollectionView() var folders = [FolderModel](){ didSet{ self.controlView.myCollectionView.reloadData() } } let cellIdentifier = "CollectionViewCell" override func viewDidLoad() { super.viewDidLoad() view.addSubview(controlView) title = "My Collection" controlView.myCollectionView.dataSource = self controlView.myCollectionView.delegate = self navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showAlert)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) folders = FolderManager.loadingEntry() } @objc func showAlert(){ let alert = UIAlertController(title: "Enter title for new folder", message: "No spaces allowed or special characters", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "enter folder title" textField.textAlignment = .center } let okay = UIAlertAction(title: "Okay", style: .default) { (UIAlertAction) in if var text = alert.textFields?.first?.text{ text.insert("@", at: text.startIndex) let folder = FolderModel(name: text, contents: [SaveModel]()) FolderManager.CreateNewFolder(type: folder) self.folders = FolderManager.loadingEntry() } } alert.addAction(okay) present(alert, animated: true, completion: nil) } @objc private func deleteFolder(_ sender:UIButton){ let deleteAtIndex = sender.tag FolderManager.removing(at: deleteAtIndex) folders = FolderManager.loadingEntry() } } extension CollectionViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return folders.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as? CollectionViewCell else { fatalError("")} let folder = folders[indexPath.row] cell.deleteButton.tag = indexPath.row cell.collectionNameLabel.text = folder.name cell.layer.borderWidth = 3 cell.layer.cornerRadius = 10 cell.layer.borderColor = UIColor.black.cgColor cell.backgroundColor = .lightGray cell.deleteButton.addTarget(self, action: #selector(deleteFolder(_:)), for: .touchUpInside) return cell } } extension CollectionViewController: UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 300, height: 200) } } extension CollectionViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let folder = folders[indexPath.row] let venuesVC = VenuesViewController(folder: folder) navigationController?.pushViewController(venuesVC, animated: true) } }
39.944444
164
0.693185
8affa62ea1d186c06e910570582b2efdb40fa1e1
5,245
import Foundation public func allPass<T, U> (_ passFunc: @escaping (T?) throws -> Bool) -> Predicate<U> where U: Sequence, T == U.Iterator.Element { let matcher = Predicate.simpleNilable("pass a condition") { actualExpression in return PredicateStatus(bool: try passFunc(try actualExpression.evaluate())) } return createPredicate(matcher) } public func allPass<T, U> (_ passName: String, _ passFunc: @escaping (T?) throws -> Bool) -> Predicate<U> where U: Sequence, T == U.Iterator.Element { let matcher = Predicate.simpleNilable(passName) { actualExpression in return PredicateStatus(bool: try passFunc(try actualExpression.evaluate())) } return createPredicate(matcher) } public func allPass<S, M>(_ elementMatcher: M) -> Predicate<S> where S: Sequence, M: Matcher, S.Iterator.Element == M.ValueType { return createPredicate(elementMatcher.predicate) } public func allPass<S>(_ elementPredicate: Predicate<S.Iterator.Element>) -> Predicate<S> where S: Sequence { return createPredicate(elementPredicate) } private func createPredicate<S>(_ elementMatcher: Predicate<S.Iterator.Element>) -> Predicate<S> where S: Sequence { return Predicate { actualExpression in guard let actualValue = try actualExpression.evaluate() else { return PredicateResult( status: .fail, message: .appends(.expectedTo("all pass"), " (use beNil() to match nils)") ) } var failure: ExpectationMessage = .expectedTo("all pass") for currentElement in actualValue { let exp = Expression( expression: {currentElement}, location: actualExpression.location) let predicateResult = try elementMatcher.satisfies(exp) if predicateResult.status == .matches { failure = predicateResult.message.prepended(expectation: "all ") } else { failure = predicateResult.message .replacedExpectation({ .expectedTo($0.expectedMessage) }) .wrappedExpectation( before: "all ", after: ", but failed first at element <\(stringify(currentElement))>" + " in <\(stringify(actualValue))>" ) return PredicateResult(status: .doesNotMatch, message: failure) } } failure = failure.replacedExpectation({ expectation in return .expectedTo(expectation.expectedMessage) }) return PredicateResult(status: .matches, message: failure) } } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func allPassMatcher(_ matcher: NMBMatcher) -> NMBPredicate { return NMBPredicate { actualExpression in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() var nsObjects = [NSObject]() var collectionIsUsable = true if let value = actualValue as? NSFastEnumeration { var generator = NSFastEnumerationIterator(value) while let obj = generator.next() { if let nsObject = obj as? NSObject { nsObjects.append(nsObject) } else { collectionIsUsable = false break } } } else { collectionIsUsable = false } if !collectionIsUsable { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( // swiftlint:disable:next line_length fail: "allPass can only be used with types which implement NSFastEnumeration (NSArray, NSSet, ...), and whose elements subclass NSObject, got <\(actualValue?.description ?? "nil")>" ) ) } let expr = Expression(expression: ({ nsObjects }), location: location) let pred: Predicate<[NSObject]> = createPredicate(Predicate { expr in if let predicate = matcher as? NMBPredicate { return predicate.satisfies(({ try! expr.evaluate() }), location: expr.location).toSwift() } else { let failureMessage = FailureMessage() let result = matcher.matches( ({ try! expr.evaluate() }), failureMessage: failureMessage, location: expr.location ) let expectationMsg = failureMessage.toExpectationMessage() return PredicateResult( bool: result, message: expectationMsg ) } }) return try! pred.satisfies(expr).toObjectiveC() } } } #endif
42.991803
205
0.551764
fe59a0bdcdbc0554a3866c17394c74d0c61ee75b
15,169
import UIKit class WMFAccountCreationViewController: WMFScrollViewController, WMFCaptchaViewControllerDelegate, UITextFieldDelegate, UIScrollViewDelegate { @IBOutlet fileprivate var usernameField: UITextField! @IBOutlet fileprivate var usernameAlertLabel: UILabel! @IBOutlet fileprivate var passwordField: UITextField! @IBOutlet fileprivate var passwordRepeatField: UITextField! @IBOutlet fileprivate var emailField: UITextField! @IBOutlet fileprivate var usernameTitleLabel: UILabel! @IBOutlet fileprivate var passwordTitleLabel: UILabel! @IBOutlet fileprivate var passwordRepeatTitleLabel: UILabel! @IBOutlet fileprivate var passwordRepeatAlertLabel: UILabel! @IBOutlet fileprivate var emailTitleLabel: UILabel! @IBOutlet fileprivate var captchaContainer: UIView! @IBOutlet fileprivate var loginButton: WMFAuthLinkLabel! @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var stackView: UIStackView! @IBOutlet fileprivate var createAccountButton: WMFAuthButton! let accountCreationInfoFetcher = WMFAuthAccountCreationInfoFetcher() let tokenFetcher = WMFAuthTokenFetcher() let accountCreator = WMFAccountCreator() public var funnel: CreateAccountFunnel? fileprivate lazy var captchaViewController: WMFCaptchaViewController? = WMFCaptchaViewController.wmf_initialViewControllerFromClassStoryboard() func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction fileprivate func createAccountButtonTapped(withSender sender: UIButton) { save() } func loginButtonPushed(_ recognizer: UITapGestureRecognizer) { guard recognizer.state == .ended, let presenter = presentingViewController, let loginVC = WMFLoginViewController.wmf_initialViewControllerFromClassStoryboard() else { assertionFailure("Expected view controller(s) not found") return } dismiss(animated: true, completion: { presenter.present(UINavigationController.init(rootViewController: loginVC), animated: true, completion: nil) }) } override func viewDidLoad() { super.viewDidLoad() [titleLabel, usernameTitleLabel, passwordTitleLabel, passwordRepeatTitleLabel, emailTitleLabel].forEach{$0.textColor = .wmf_authTitle} usernameAlertLabel.textColor = .wmf_red passwordRepeatAlertLabel.textColor = .wmf_yellow navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) createAccountButton.setTitle(WMFLocalizedString("account-creation-create-account", value:"Create your account", comment:"Text for create account button"), for: .normal) scrollView.delegate = self usernameField.placeholder = WMFLocalizedString("field-username-placeholder", value:"enter username", comment:"Placeholder text shown inside username field until user taps on it") passwordField.placeholder = WMFLocalizedString("field-password-placeholder", value:"enter password", comment:"Placeholder text shown inside password field until user taps on it") passwordRepeatField.placeholder = WMFLocalizedString("field-password-confirm-placeholder", value:"re-enter password", comment:"Placeholder text shown inside confirm password field until user taps on it") emailField.placeholder = WMFLocalizedString("field-email-placeholder", value:"[email protected]", comment:"Placeholder text shown inside email address field until user taps on it") usernameTitleLabel.text = WMFLocalizedString("field-username-title", value:"Username", comment:"Title for username field\n{{Identical|Username}}") passwordTitleLabel.text = WMFLocalizedString("field-password-title", value:"Password", comment:"Title for password field\n{{Identical|Password}}") passwordRepeatTitleLabel.text = WMFLocalizedString("field-password-confirm-title", value:"Confirm password", comment:"Title for confirm password field") emailTitleLabel.text = WMFLocalizedString("field-email-title-optional", value:"Email (optional)", comment:"Noun. Title for optional email address field.") passwordRepeatAlertLabel.text = WMFLocalizedString("field-alert-password-confirm-mismatch", value:"Passwords do not match", comment:"Alert shown if password confirmation did not match password") usernameField.wmf_addThinBottomBorder() passwordField.wmf_addThinBottomBorder() passwordRepeatField.wmf_addThinBottomBorder() emailField.wmf_addThinBottomBorder() loginButton.strings = WMFAuthLinkLabelStrings(dollarSignString: WMFLocalizedString("account-creation-have-account", value:"Already have an account? %1$@", comment:"Text for button which shows login interface. %1$@ is the message {{msg-wikimedia|account-creation-log-in}}"), substitutionString: WMFLocalizedString("account-creation-log-in", value:"Log in.", comment:"Log in text to be used as part of a log in button\n{{Identical|Log in}}")) loginButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(loginButtonPushed(_:)))) titleLabel.text = WMFLocalizedString("account-creation-title", value:"Create a new account", comment:"Title for account creation interface") view.wmf_configureSubviewsForDynamicType() captchaViewController?.captchaDelegate = self wmf_add(childController:captchaViewController, andConstrainToEdgesOfContainerView: captchaContainer) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Check if captcha is required right away. Things could be configured so captcha is required at all times. getCaptcha() updateEmailFieldReturnKeyType() enableProgressiveButtonIfNecessary() } fileprivate func getCaptcha() { let failure: WMFErrorHandler = {error in } let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() accountCreationInfoFetcher.fetchAccountCreationInfoForSiteURL(siteURL!, success: { info in self.captchaViewController?.captcha = info.captcha if info.captcha != nil { self.funnel?.logCaptchaShown() } self.updateEmailFieldReturnKeyType() self.enableProgressiveButtonIfNecessary() }, failure:failure) enableProgressiveButtonIfNecessary() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) usernameField.becomeFirstResponder() } @IBAction func textFieldDidChange(_ sender: UITextField) { enableProgressiveButtonIfNecessary() } fileprivate func hasUserEnteredCaptchaText() -> Bool { guard let text = captchaViewController?.solution else { return false } return (text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).characters.count > 0) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case usernameField: passwordField.becomeFirstResponder() case passwordField: passwordRepeatField.becomeFirstResponder() case passwordRepeatField: emailField.becomeFirstResponder() case emailField: if captchaIsVisible() { captchaViewController?.captchaTextFieldBecomeFirstResponder() }else{ save() } default: assertionFailure("Unhandled text field") } return true } func captchaKeyboardReturnKeyTapped() { save() } fileprivate func enableProgressiveButtonIfNecessary() { createAccountButton.isEnabled = shouldProgressiveButtonBeEnabled() } fileprivate func shouldProgressiveButtonBeEnabled() -> Bool { var shouldEnable = areRequiredFieldsPopulated() if captchaIsVisible() && shouldEnable { shouldEnable = hasUserEnteredCaptchaText() } return shouldEnable } override func viewWillDisappear(_ animated: Bool) { WMFAlertManager.sharedInstance.dismissAlert() super.viewWillDisappear(animated) } fileprivate func captchaIsVisible() -> Bool { return captchaViewController?.captcha != nil } fileprivate func updateEmailFieldReturnKeyType() { emailField.returnKeyType = captchaIsVisible() ? .next : .done // Resign and become first responder so keyboard return key updates right away. if emailField.isFirstResponder { emailField.resignFirstResponder() emailField.becomeFirstResponder() } } func captchaReloadPushed(_ sender: AnyObject) { enableProgressiveButtonIfNecessary() } func captchaSolutionChanged(_ sender: AnyObject, solutionText: String?) { enableProgressiveButtonIfNecessary() } public func captchaSiteURL() -> URL { return (MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL())! } public func captchaHideSubtitle() -> Bool { return false } fileprivate func login() { WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically.\n{{Identical|Logging in}}"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) WMFAuthenticationManager.sharedInstance.login( username: usernameField.text ?? "", password: passwordField.text ?? "", retypePassword: nil, oathToken: nil, captchaID: nil, captchaWord: nil, success: { _ in let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), self.usernameField.text ?? "") WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) self.dismiss(animated: true, completion: nil) }, failure: { error in self.enableProgressiveButtonIfNecessary() WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) }) } fileprivate func requiredInputFields() -> [UITextField] { assert(isViewLoaded, "This method is only intended to be called when view is loaded, since they'll all be nil otherwise") return [usernameField, passwordField, passwordRepeatField] } fileprivate func passwordFieldsMatch() -> Bool { return passwordField.text == passwordRepeatField.text } fileprivate func areRequiredFieldsPopulated() -> Bool { return requiredInputFields().wmf_allFieldsFilled() } fileprivate func save() { usernameAlertLabel.isHidden = true passwordRepeatAlertLabel.isHidden = true guard areRequiredFieldsPopulated() else { WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("account-creation-missing-fields", value:"You must enter a username, password, and password confirmation to create an account.", comment:"Error shown when one of the required fields for account creation (username, password, and password confirmation) is empty."), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) return } guard passwordFieldsMatch() else { self.passwordRepeatField.textColor = .wmf_yellow self.passwordRepeatAlertLabel.isHidden = false self.scrollView.scrollSubView(toTop: self.passwordTitleLabel, offset: 6, animated: true) WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("account-creation-passwords-mismatched", value:"Password fields do not match.", comment:"Alert shown if the user doesn't enter the same password in both password boxes"), sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) return } wmf_hideKeyboard() createAccount() } @IBAction func textFieldDidBeginEditing(_ textField: UITextField) { switch textField { case usernameField: usernameAlertLabel.isHidden = true usernameField.textColor = .black case passwordRepeatField: passwordRepeatAlertLabel.isHidden = true passwordRepeatField.textColor = .black default: break } } fileprivate func createAccount() { WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-saving", value:"Saving...", comment:"Alert shown when user saves account creation form.\n{{Identical|Saving}}"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) let creationFailure: WMFErrorHandler = {error in // Captcha's appear to be one-time, so always try to get a new one on failure. self.getCaptcha() if let error = error as? WMFAccountCreatorError { switch error { case .usernameUnavailable: self.usernameAlertLabel.text = error.localizedDescription self.usernameAlertLabel.isHidden = false self.usernameField.textColor = .wmf_red self.funnel?.logError(error.localizedDescription) WMFAlertManager.sharedInstance.dismissAlert() return case .wrongCaptcha: self.captchaViewController?.captchaTextFieldBecomeFirstResponder() default: break } } self.funnel?.logError(error.localizedDescription) self.enableProgressiveButtonIfNecessary() WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) } let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() tokenFetcher.fetchToken(ofType: .createAccount, siteURL: siteURL!, success: { token in self.accountCreator.createAccount(username: self.usernameField.text!, password: self.passwordField.text!, retypePassword: self.passwordRepeatField.text!, email: self.emailField.text!, captchaID:self.captchaViewController?.captcha?.captchaID, captchaWord: self.captchaViewController?.solution, token: token.token, siteURL: siteURL!, success: {_ in self.login() }, failure: creationFailure) }, failure: creationFailure) } }
50.732441
448
0.69675
11136dd4c172738b17dddf61808c82666fb786a2
266
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let start = { struct d { init { { protocol A { deinit { class B { func b( ) { { { { class case ,
15.647059
87
0.695489
8a386fab7aecd6e25c0768a1903ad4c1112993d5
2,163
// // AppDelegate.swift // SwiftTestRepo // // Created by vic on 08/05/2019. // Copyright (c) 2019 vic. 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.021277
285
0.753583
fc0feaeb033d2945165c7262b7dd9986d7f56bfb
767
/** Regression test for invalid location targeting. Needs to be run with more than one worker for testing! */ import assert; import location; import string; @dispatch=WORKER (string o) hello_worker(string msg) "turbine" "0.0.1" [ "set mytmp1234 <<msg>>; set <<o>> \"Hello from [ adlb::rank ]: $mytmp1234\"; puts $<<o>>" ]; main { // Run multiple times to hopefully get one of the tasks sent to // the wrong worker in case of the bug foreach i in [1:100] { L1 = random_worker(); act1 = test_fn(":)", L1); exp1 = "Hello from " + L1.rank + ": :)"; trace("\"" + act1 + "\"") => assertEqual(act1, exp1, "test 1"); } } (string c) test_fn(string msg, location L) { msg2 = sprintf("%s", msg); c = @location=L hello_worker(msg2); }
23.242424
91
0.615385
38c279b7541082eb8b3248879970701c54076021
3,575
// // Created by apploft on 19.03.18. // Copyright © 2019 apploft GmbH. // MIT License · http://choosealicense.com/licenses/mit/ // import Foundation /// A protocol which represents the state and its associated properties and operations an event can have. public protocol EventState: NSObjectProtocol { /// The name of the associated event. var name: String { get } /// The first occurrence of the associated event, saved as a time interval. var firstOccurrence: TimeInterval { get } /// The last occurrence of the associated event, saved as a time interval. var lastOccurrence: TimeInterval { get } /// The current count of the associated event. If The event is disabled the count returns 0. var count: Int { get } /// A bool which indicates if the associated event is disabled. The count of a disabled event is 0. var disabled: Bool { get set } /// This property presents the name, the first plus last occurrence and the count of the associated event. var logString: String { get } /// Updates the count of the event by a given number. /// - Parameter incrementBy: The number which will be added to the count. The number can be negative. func update(incrementBy: Int) /// Resets the count, the first and last occurrence of the associated event to 0. func reset() /// This function indicates whether the associated event occurred in the last 24 hours. /// - returns: A bool indicating whether the event occurred in the last 24 hours. func occurredInLastDay() -> Bool } /// A protocol which is be adapted by all event engines. This protocol makes sure that an event engine /// implements the essential operations for managing events. public protocol EventEngine { /// This property toggles whether the event engine should log its operations to the console. /** *Example* eventEngine.loggingEnabled = true eventEngine.fire("App Start", incrementBy: 1) -> Console prints: "Updated event App Start by: 1" */ var loggingEnabled: Bool { get set } /// This function increments the counter of an event. /// The change is stored in the memory cache. /// - Parameter event: The name of the event, which will be updated. /// - Parameter incrementBy: The number which will be added to the /// counter of an event state. The number can also be negative. func fire(event: String, incrementBy: Int) /// This function resets an event. A reset sets the the count, the first and last occurrence of the associated event to 0. /// The change is stored in the memory cache. /// - Parameter event: The name of the event, which will be reseted. func reset(event: String) /// This function disables an event. /// The change is stored in the memory cache. /// - Parameter event: The name of the event, which will be disabled. func disable(event: String) /// This function enables an event. /// The change is stored in the memory cache. /// - Parameter event: The name of the event, which will be enabled. func enable(event: String) /// This function returns the event state of an event. /// - Parameter event: The name of the event. /// - returns: The event state of the event. func state(ofEvent: String) -> EventState /// This function persists all event changes stored in the memory cache to the user defaults. /// Call this function before terminating the app to make sure all changes are saved. func synchronize() }
47.666667
126
0.690909
71245b1d2f0c2b29505c95cb0dbc55477450975e
887
// // ContentView.swift // ManaGuide // // Created by Vito Royeca on 11/10/20. // Copyright © 2020 CocoaPods. All rights reserved. // import SwiftUI import ManaKit struct ContentView: View { #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass #endif var body: some View { // #if os(iOS) // if horizontalSizeClass == .compact { TabNavigationView() .environment(\.horizontalSizeClass, horizontalSizeClass) // } else { // SideNavigationView() // .environment(\.horizontalSizeClass, horizontalSizeClass) // } // #else // SideNavigationView() // #endif } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .previewInterfaceOrientation(.landscapeRight) } }
23.342105
74
0.609921
e67fe5a5e3153c880c19607468f132ad71addbc3
11,330
import Flutter import AVFoundation public class SwiftVideoCompressPlugin: NSObject, FlutterPlugin { private let channelName = "video_compress" private var exporter: AVAssetExportSession? = nil private var stopCommand = false private let channel: FlutterMethodChannel private let avController = AvController() init(channel: FlutterMethodChannel) { self.channel = channel } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "video_compress", binaryMessenger: registrar.messenger()) let instance = SwiftVideoCompressPlugin(channel: channel) registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { let args = call.arguments as? Dictionary<String, Any> switch call.method { case "getByteThumbnail": let path = args!["path"] as! String let quality = args!["quality"] as! NSNumber let position = args!["position"] as! NSNumber getByteThumbnail(path, quality, position, result) case "getFileThumbnail": let path = args!["path"] as! String let quality = args!["quality"] as! NSNumber let position = args!["position"] as! NSNumber getFileThumbnail(path, quality, position, result) case "getMediaInfo": let path = args!["path"] as! String getMediaInfo(path, result) case "compressVideo": let path = args!["path"] as! String let output = args!["output"] as! String var quality = 5 if (args!["quality"] != nil) { quality = args!["quality"] as! Int } let deleteOrigin = args!["deleteOrigin"] as! Bool let startTime = args!["startTime"] as? Double let duration = args!["duration"] as? Double let includeAudio = args!["includeAudio"] as? Bool let frameRate = args!["frameRate"] as? Int compressVideo(path, output, quality, deleteOrigin, startTime, duration, includeAudio, frameRate, result) case "cancelCompression": cancelCompression(result) case "deleteAllCache": Utility.deleteFile(Utility.basePath(), clear: true) result(true) case "setLogLevel": result(true) default: result(FlutterMethodNotImplemented) } } private func getBitMap(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult)-> Data? { let url = Utility.getPathUrl(path) let asset = avController.getVideoAsset(url) guard let track = avController.getTrack(asset) else { return nil } let assetImgGenerate = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true let timeScale = CMTimeScale(track.nominalFrameRate) let time = CMTimeMakeWithSeconds(Float64(truncating: position),preferredTimescale: timeScale) guard let img = try? assetImgGenerate.copyCGImage(at:time, actualTime: nil) else { return nil } let thumbnail = UIImage(cgImage: img) let compressionQuality = CGFloat(0.01 * Double(truncating: quality)) return thumbnail.jpegData(compressionQuality: compressionQuality) } private func getByteThumbnail(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult) { if let bitmap = getBitMap(path,quality,position,result) { result(bitmap) } } private func getFileThumbnail(_ path: String,_ quality: NSNumber,_ position: NSNumber,_ result: FlutterResult) { let fileName = Utility.getFileName(path) let url = Utility.getPathUrl("\(Utility.basePath())/\(fileName).jpg") Utility.deleteFile(path) if let bitmap = getBitMap(path,quality,position,result) { guard (try? bitmap.write(to: url)) != nil else { return result(FlutterError(code: channelName,message: "getFileThumbnail error",details: "getFileThumbnail error")) } result(Utility.excludeFileProtocol(url.absoluteString)) } } public func getMediaInfoJson(_ path: String)->[String : Any?] { let url = Utility.getPathUrl(path) let asset = avController.getVideoAsset(url) guard let track = avController.getTrack(asset) else { return [:] } let playerItem = AVPlayerItem(url: url) let metadataAsset = playerItem.asset let orientation = avController.getVideoOrientation(path) let title = avController.getMetaDataByTag(metadataAsset,key: "title") let author = avController.getMetaDataByTag(metadataAsset,key: "author") let duration = asset.duration.seconds * 1000 let filesize = track.totalSampleDataLength let size = track.naturalSize.applying(track.preferredTransform) let width = abs(size.width) let height = abs(size.height) let dictionary = [ "path":Utility.excludeFileProtocol(path), "title":title, "author":author, "width":width, "height":height, "duration":duration, "filesize":filesize, "orientation":orientation ] as [String : Any?] return dictionary } private func getMediaInfo(_ path: String,_ result: FlutterResult) { let json = getMediaInfoJson(path) let string = Utility.keyValueToJson(json) result(string) } @objc private func updateProgress(timer:Timer) { let asset = timer.userInfo as! AVAssetExportSession if(!stopCommand) { channel.invokeMethod("updateProgress", arguments: "\(String(describing: asset.progress * 100))") } } private func getExportPreset(_ quality: Int)->String { switch(quality) { case 1: return AVAssetExportPresetLowQuality case 2: return AVAssetExportPresetMediumQuality case 3: return AVAssetExportPresetHighestQuality case 4: return AVAssetExportPreset640x480 case 5: return AVAssetExportPreset960x540 case 6: return AVAssetExportPreset1280x720 case 7: return AVAssetExportPreset1920x1080 default: return AVAssetExportPresetMediumQuality } } private func getComposition(_ isIncludeAudio: Bool,_ timeRange: CMTimeRange, _ sourceVideoTrack: AVAssetTrack)->AVAsset { let composition = AVMutableComposition() if !isIncludeAudio { let compressionVideoTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid) compressionVideoTrack!.preferredTransform = sourceVideoTrack.preferredTransform try? compressionVideoTrack!.insertTimeRange(timeRange, of: sourceVideoTrack, at: CMTime.zero) } else { return sourceVideoTrack.asset! } return composition } private func compressVideo(_ path: String,_ output: String, _ quality: Int,_ deleteOrigin: Bool,_ startTime: Double?, _ duration: Double?,_ includeAudio: Bool?,_ frameRate: Int?, _ result: @escaping FlutterResult) { let sourceVideoUrl = Utility.getPathUrl(path) let sourceVideoType = "mp4" let sourceVideoAsset = avController.getVideoAsset(sourceVideoUrl) let sourceVideoTrack = avController.getTrack(sourceVideoAsset) let compressionUrl = Utility.getPathUrl(output) //Utility.getPathUrl("\(Utility.basePath())/\(Utility.getFileName(path)).\(sourceVideoType)") let timescale = sourceVideoAsset.duration.timescale let minStartTime = Double(startTime ?? 0) let videoDuration = sourceVideoAsset.duration.seconds let minDuration = Double(duration ?? videoDuration) let maxDurationTime = minStartTime + minDuration < videoDuration ? minDuration : videoDuration let cmStartTime = CMTimeMakeWithSeconds(minStartTime, preferredTimescale: timescale) let cmDurationTime = CMTimeMakeWithSeconds(maxDurationTime, preferredTimescale: timescale) let timeRange: CMTimeRange = CMTimeRangeMake(start: cmStartTime, duration: cmDurationTime) let isIncludeAudio = includeAudio != nil ? includeAudio! : true if (sourceVideoTrack != nil) { let session = getComposition(isIncludeAudio, timeRange, sourceVideoTrack!) let exporter = AVAssetExportSession(asset: session, presetName: getExportPreset(quality))! exporter.outputURL = compressionUrl exporter.outputFileType = AVFileType.mp4 exporter.shouldOptimizeForNetworkUse = true if frameRate != nil { let videoComposition = AVMutableVideoComposition(propertiesOf: sourceVideoAsset) videoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate!)) exporter.videoComposition = videoComposition } if !isIncludeAudio { exporter.timeRange = timeRange } Utility.deleteFile(compressionUrl.absoluteString) let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateProgress), userInfo: exporter, repeats: true) exporter.exportAsynchronously(completionHandler: { timer.invalidate() if(self.stopCommand) { self.stopCommand = false var json = self.getMediaInfoJson(path) json["isCancel"] = true let jsonString = Utility.keyValueToJson(json) return result(jsonString) } if deleteOrigin { let fileManager = FileManager.default do { if fileManager.fileExists(atPath: path) { try fileManager.removeItem(atPath: path) } self.exporter = nil self.stopCommand = false } catch let error as NSError { print(error) } } var json = self.getMediaInfoJson(Utility.excludeEncoding(compressionUrl.path)) json["isCancel"] = false let jsonString = Utility.keyValueToJson(json) result(jsonString) }) } else { result("") } } private func cancelCompression(_ result: FlutterResult) { exporter?.cancelExport() stopCommand = true result("") } }
42.276119
149
0.608914
38203e3b9f3224e6bca270222a7d50f9209602f7
6,117
// // UIImage+Ext.swift // OpenWeatherIos // // Created by Marin Ipati on 12/09/2021. // import UIKit extension UIImage { static public func drawMoonPhase( _ moonPhase: Double, radius: CGFloat, lineWidth: CGFloat, lightColor: UIColor = .white, darkColor: UIColor = .black ) -> UIImage? { let size = CGSize(width: radius * 2.0, height: radius * 2.0) let center = CGPoint(x: size.width / 2, y: size.height / 2) let smallRadius = radius - lineWidth guard let lightShapePath = lightShapePath(moonPhase: moonPhase, center: center, radius: smallRadius) else { return nil } defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(size, false, 0.0) guard let context = UIGraphicsGetCurrentContext() else { return nil } let darkShapePath = darkShapePath(center: center, radius: radius) context.saveGState() context.addPath(darkShapePath.cgPath) darkColor.setFill() context.fillPath() context.restoreGState() context.saveGState() context.addPath(lightShapePath.cgPath) lightColor.setFill() context.fillPath() context.restoreGState() let image = UIGraphicsGetImageFromCurrentImageContext() return image } static private func darkShapePath( center: CGPoint, radius: CGFloat ) -> UIBezierPath { let path = UIBezierPath() path.addArc( withCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true ) return path } static private func lightShapePath( moonPhase: Double, center: CGPoint, radius: CGFloat ) -> UIBezierPath? { let step = 0.25 let (integer, reminder) = modf(moonPhase / step) let ratio = getRatio(moonPhase: moonPhase, step: step) let angle: CGFloat = .pi / 2 * CGFloat(ratio) if reminder == 0 { let path = mainArcPath(phaseIndex: Int(integer), center: center, radius: radius) path?.close() return path } return innerArcPath(phaseIndex: Int(integer), center: center, radius: radius, angle: angle) } static private func mainArcPath(phaseIndex: Int, center: CGPoint, radius: CGFloat) -> UIBezierPath? { switch phaseIndex { case 1: return arcPath( center: center, radius: radius, startAngle: -.pi / 2, endAngle: .pi / 2, clockwise: true ) case 2: return arcPath( center: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true ) case 3: return arcPath( center: center, radius: radius, startAngle: -.pi / 2, endAngle: .pi / 2, clockwise: false ) default: return nil } } static private func innerArcPath( phaseIndex: Int, center: CGPoint, radius: CGFloat, angle: CGFloat ) -> UIBezierPath? { var clockwise = true, innerClockwise = true var innerCenter: CGPoint = .zero var innerStartAngle: CGFloat = 0, innerEndAngle: CGFloat = 0 let innerRadius: CGFloat = radius / cos(angle) switch phaseIndex { case 0: clockwise = true innerClockwise = false innerCenter = CGPoint(x: center.x - radius * tan(angle), y: center.y) innerStartAngle = .pi / 2 - angle innerEndAngle = angle - .pi / 2 case 1: clockwise = true innerClockwise = true innerCenter = CGPoint(x: center.x + radius * tan(angle), y: center.y) innerStartAngle = .pi / 2 + angle innerEndAngle = -.pi / 2 - angle case 2: clockwise = false innerClockwise = false innerCenter = CGPoint(x: center.x - radius * tan(angle), y: center.y) innerStartAngle = .pi / 2 - angle innerEndAngle = -.pi / 2 + angle case 3: clockwise = false innerClockwise = true innerCenter = CGPoint(x: center.x + radius * tan(angle), y: center.y) innerStartAngle = .pi / 2 + angle innerEndAngle = -.pi / 2 - angle default: return nil } let path = UIBezierPath() path.addArc( withCenter: center, radius: radius, startAngle: -.pi / 2, endAngle: .pi / 2, clockwise: clockwise ) path.addArc( withCenter: innerCenter, radius: innerRadius, startAngle: innerStartAngle, endAngle: innerEndAngle, clockwise: innerClockwise ) return path } static private func arcPath( center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool ) -> UIBezierPath { let path = UIBezierPath() path.addArc( withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise ) return path } static private func getRatio(moonPhase: Double, step: Double) -> Double { let (integer, reminder) = modf(moonPhase / step) if reminder == 0 { return Double(Int(integer) % 2) } else { switch integer { case 1, 3: return 1 - (moonPhase - (step * integer)) / step default: return (moonPhase - (step * integer)) / step } } } }
27.186667
106
0.522642
48b052e3fcf9d61d8765fa928783ce06f31b0893
20,919
// // UserAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif open class UserAPI { /** Create user - parameter body: (body) Created user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Create user - POST /user - This can only be done by the logged in user. - parameter body: (body) Created user object - returns: RequestBuilder<Void> */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder<Void> { let localVariablePath = "/user" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Creates list of users with given input array - POST /user/createWithArray - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let localVariablePath = "/user/createWithArray" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Creates list of users with given input array - parameter body: (body) List of user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Creates list of users with given input array - POST /user/createWithList - parameter body: (body) List of user object - returns: RequestBuilder<Void> */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder<Void> { let localVariablePath = "/user/createWithList" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Delete user - parameter username: (path) The name that needs to be deleted - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Delete user - DELETE /user/{username} - This can only be done by the logged in user. - parameter username: (path) The name that needs to be deleted - returns: RequestBuilder<Void> */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder<Void> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Get user by user name - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: User */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> User { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): continuation.resume(returning: response.body!) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Get user by user name - GET /user/{username} - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - returns: RequestBuilder<User> */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder<User> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<User>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Logs user into the system - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: String */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> String { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): continuation.resume(returning: response.body!) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Logs user into the system - GET /user/login - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text - returns: RequestBuilder<String> */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder<String> { let localVariablePath = "/user/login" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil var localVariableUrlComponents = URLComponents(string: localVariableURLString) localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<String>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Logs out current logged in user session - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Logs out current logged in user session - GET /user/logout - returns: RequestBuilder<Void> */ open class func logoutUserWithRequestBuilder() -> RequestBuilder<Void> { let localVariablePath = "/user/logout" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** Updated user - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() return try await withCheckedThrowingContinuation { continuation in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } task = updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result in switch result { case .success: continuation.resume(returning: ()) case let .failure(error): continuation.resume(throwing: error) } } } } onCancel: { [task] in task?.cancel() } } /** Updated user - PUT /user/{username} - This can only be done by the logged in user. - parameter username: (path) name that need to be deleted - parameter body: (body) Updated user object - returns: RequestBuilder<Void> */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder<Void> { var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ : ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } }
43.400415
217
0.651322
7598805f8e5fc5e43803a8b3fa26de57dc9b4573
4,060
// // MainViewController.swift // Delicacy // // Created by Youwei Teng on 9/5/15. // Copyright (c) 2015 Dcard. All rights reserved. // import UIKit import SnapKit let kArticleCellHeight: CGFloat = UIScreen.mainScreen().bounds.size.width class MainViewController: UIViewController { var articleDatasource: ArticleDatesource? let transitionAimator = TransitionAnimator() var didSetUpContraints: Bool = false var selectedCell: ArticleCell? // MARK: - View Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() initialize(); self.view.setNeedsUpdateConstraints() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func updateViewConstraints() { if !self.didSetUpContraints { self.tableView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.view) } self.didSetUpContraints = true } super.updateViewConstraints() } override func prefersStatusBarHidden() -> Bool { return navigationController?.navigationBarHidden == true } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.Fade } // MARK: - Initialize Methods required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Private methods func initialize() { navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: true) self.view.backgroundColor = UIColor.blackColor() self.view.addSubview(self.tableView); } // MARK: - Lazy instantiate lazy var tableView: UITableView = { let lazyTableView = UITableView() lazyTableView.registerClass(ArticleCell.self, forCellReuseIdentifier: NSStringFromClass(ArticleCell.self) as String) lazyTableView.delegate = self lazyTableView.backgroundColor = UIColor .blackColor() lazyTableView.showsVerticalScrollIndicator = false lazyTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0) //hide the separator when empty lazyTableView.estimatedRowHeight = kArticleCellHeight lazyTableView.tableFooterView = UIView() self.articleDatasource = ArticleDatesource(tableView: lazyTableView, cellIdentifier: NSStringFromClass(ArticleCell.self)){ (cell, article) in //Save the 🐴!! if let articleCell = cell as? ArticleCell { articleCell.article = article } } lazyTableView.dataSource = self.articleDatasource return lazyTableView }(); } extension MainViewController: UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return kArticleCellHeight } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedCell = tableView .cellForRowAtIndexPath(indexPath) as? ArticleCell let detailViewController: DetailViewController = DetailViewController(articleCell: self.selectedCell!) detailViewController.transitioningDelegate = self presentViewController(detailViewController, animated: true, completion: nil) tableView.deselectRowAtIndexPath(indexPath, animated: false) } } extension MainViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transitionAimator.originFrame = self.selectedCell!.superview!.convertRect(self.selectedCell!.frame, toView: nil) print(self.selectedCell?.frame) transitionAimator.presenting = true return transitionAimator } // TODO: buggy dismiss // func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // transitionAimator.presenting = false // return transitionAimator // } } extension MainViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { for cell: ArticleCell in self.tableView.visibleCells as! Array { cell.applyParallax(scrollView.contentOffset.y) } } }
31.230769
214
0.785468
f4d3966aed9ae54f695d9d7f0f3ed6599a6f1f56
7,587
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private extension Realm { /** A `Realm.Configuration` is used to describe the different options used to create a `Realm` instance. `Realm.Configuration` instances are just plain Swift structs, and unlike `Realm` and `Object`s can be freely shared between threads. Creating configuration objects for class subsets (by setting the `objectTypes` property) can be expensive, and so you will normally want to cache and reuse a single configuration object for each distinct configuration that you are using rather than creating a new one each time you open a `Realm`. */ public struct Configuration { // MARK: Default Configuration /// Returns the default Realm.Configuration used to create Realms when no other /// configuration is explicitly specified (i.e. `Realm()`). public static var defaultConfiguration: Configuration { get { return fromRLMRealmConfiguration(RLMRealmConfiguration.defaultConfiguration()) } set { RLMRealmConfiguration.setDefaultConfiguration(newValue.rlmConfiguration) } } // MARK: Initialization /** Initializes a `Realm.Configuration`, suitable for creating new `Realm` instances. - parameter path: The path to the realm file. - parameter inMemoryIdentifier: A string used to identify a particular in-memory Realm. - parameter encryptionKey: 64-byte key to use to encrypt the data. - parameter readOnly: Whether the Realm is read-only (must be true for read-only files). - parameter schemaVersion: The current schema version. - parameter migrationBlock: The block which migrates the Realm to the current version. - parameter objectTypes: The subset of `Object` subclasses persisted in the Realm. */ public init(path: String? = RLMRealmPathForFile("default.realm"), inMemoryIdentifier: String? = nil, encryptionKey: NSData? = nil, readOnly: Bool = false, schemaVersion: UInt64 = 0, migrationBlock: MigrationBlock? = nil, objectTypes: [Object.Type]? = nil) { self.path = path if inMemoryIdentifier != nil { self.inMemoryIdentifier = inMemoryIdentifier } self.encryptionKey = encryptionKey self.readOnly = readOnly self.schemaVersion = schemaVersion self.migrationBlock = migrationBlock self.objectTypes = objectTypes } // MARK: Configuration Properties /// The path to the realm file. /// Mutually exclusive with `inMemoryIdentifier`. public var path: String? { set { _inMemoryIdentifier = nil _path = newValue } get { return _path } } private var _path: String? /// A string used to identify a particular in-memory Realm. /// Mutually exclusive with `path`. public var inMemoryIdentifier: String? { set { _path = nil _inMemoryIdentifier = newValue } get { return _inMemoryIdentifier } } private var _inMemoryIdentifier: String? = nil /// 64-byte key to use to encrypt the data. public var encryptionKey: NSData? = nil /// Whether the Realm is read-only (must be true for read-only files). public var readOnly: Bool = false /// The current schema version. public var schemaVersion: UInt64 = 0 /// The block which migrates the Realm to the current version. public var migrationBlock: MigrationBlock? = nil /// The classes persisted in the Realm. public var objectTypes: [Object.Type]? { set { self.customSchema = newValue.map { RLMSchema(objectClasses: $0) } } get { return self.customSchema.map { $0.objectSchema.map { $0.objectClass as! Object.Type } } } } /// A custom schema to use for the Realm. private var customSchema: RLMSchema? = nil /// Allows to disable automatic format upgrades when accessing the Realm. internal var disableFormatUpgrade: Bool = false // MARK: Private Methods internal var rlmConfiguration: RLMRealmConfiguration { let configuration = RLMRealmConfiguration() if path != nil { configuration.path = self.path } else if inMemoryIdentifier != nil { configuration.inMemoryIdentifier = self.inMemoryIdentifier } else { fatalError("A Realm Configuration must specify a path or an in-memory identifier.") } configuration.encryptionKey = self.encryptionKey configuration.readOnly = self.readOnly configuration.schemaVersion = self.schemaVersion configuration.migrationBlock = self.migrationBlock.map { accessorMigrationBlock($0) } configuration.customSchema = self.customSchema configuration.disableFormatUpgrade = self.disableFormatUpgrade return configuration } internal static func fromRLMRealmConfiguration(rlmConfiguration: RLMRealmConfiguration) -> Configuration { var configuration = Configuration() configuration._path = rlmConfiguration.path configuration._inMemoryIdentifier = rlmConfiguration.inMemoryIdentifier configuration.encryptionKey = rlmConfiguration.encryptionKey configuration.readOnly = rlmConfiguration.readOnly configuration.schemaVersion = rlmConfiguration.schemaVersion configuration.migrationBlock = rlmConfiguration.migrationBlock.map { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } } configuration.customSchema = rlmConfiguration.customSchema configuration.disableFormatUpgrade = rlmConfiguration.disableFormatUpgrade return configuration } } } // MARK: CustomStringConvertible extension Realm.Configuration: CustomStringConvertible { /// Returns a human-readable description of the configuration. public var description: String { return gsub("\\ARLMRealmConfiguration", template: "Realm.Configuration", string: rlmConfiguration.description) ?? "" } }
40.356383
114
0.617635
e6425ed04cde73b986a56366266713e55607b6f6
1,076
import UIKit import Family class ContainerController: FamilyViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white title = "Loading" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) performBatchUpdates(withDuration: 0, { _ in for x in 0..<25 { let layout = UICollectionViewFlowLayout() layout.sectionInset = .init(top: 10, left: 10, bottom: 10, right: 10) layout.minimumLineSpacing = 10 layout.minimumInteritemSpacing = 10 layout.itemSize.height = 50 let viewController = CollectionViewController(numberOfItemsInSection: 12 * 2, layout: layout) let background = x % 2 == 0 ? UIColor.white : UIColor.lightGray.withAlphaComponent(0.5) viewController.view.backgroundColor = background viewController.collectionView.backgroundColor = background add(viewController) title = "Loaded \(x)" } }) { (_) in self.title = "All done!" } } }
28.315789
101
0.655204
5d7a72a85782e029d8eb6ef30f6c742cc38c8fef
7,752
// // AMUITableViewDatasourcerer.swift // // Created with 💪 by Alessandro Manilii // Copyright © 2019 Alessandro Manilii. All rights reserved. // import UIKit //MARK: - Class UITableViewDatasourcerer public class AMUITableViewDatasourcerer<T, U: AMConfigurableCell>: NSObject, UITableViewDataSource { //MARK: - Properties /// An enum that describes the possible datasource kind of the Datasoucerer /// /// - singleSection: the datasource is an array of elements /// - multiSection: the datasource is an array of DatasourcererMultisectionItem /// - unknown: the datasource is not set (default case to avoid optionals) enum DatasourceType { case singleSection case multiSection case unknown } typealias DatasourcererItem = U.T fileprivate var items = [DatasourcererItem]() fileprivate var cellClass: U.Type fileprivate var multiSectionsItems = [DatasourcererMultisectionItem<DatasourcererItem>]() fileprivate var datasourceType = DatasourceType.unknown var onCanEditRow: ((IndexPath) -> Bool)? // If extra behaviours are needed var onCanMoveRow: ((IndexPath) -> Bool)? // If extra behaviours are needed //MARK: - Initializers /// Datasourcer initializer - Single Section /// - Note: the cell class must conform the AMConfigurableCell protocol in order to use automatically the item object. /// - Parameters: /// - items: array of items. Are inferred since it' a double step generic /// - cellClass: Class for the custom cell init(items: [U.T], cellClass: U.Type) { self.datasourceType = .singleSection self.items = items self.cellClass = cellClass } /// Datasourcer initializer - Multi Sections /// - Note: the cell class must conform the AMConfigurableCell protocol in order to use automatically the item object. /// - Parameters: /// - multiSectionItems: the array of DatasourcererMultisectionItems /// - cellClass: Class for the custom cell init(multiSectionItems: [DatasourcererMultisectionItem<DatasourcererItem>], cellClass: U.Type) { self.datasourceType = .multiSection self.multiSectionsItems = multiSectionItems self.cellClass = cellClass } //MARK: - UITableViewDataSource //MARK: - Sections, cells and rendering public func numberOfSections(in tableView: UITableView) -> Int { switch self.datasourceType { case .singleSection : return 1 case .multiSection : return multiSectionsItems.count case .unknown : return 0 } } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.datasourceType { case .singleSection : return items.count case .multiSection : return multiSectionsItems[section].items.count case .unknown : return 0 } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: U.reuseIdentifier, for: indexPath) as? U else { return UITableViewCell() } switch self.datasourceType { case .singleSection : cell.configure(items[indexPath.row], at: indexPath) case .multiSection : cell.configure(multiSectionsItems[indexPath.section].items[indexPath.row], at: indexPath) case .unknown : break } guard let returnableCell = cell as? UITableViewCell else { return UITableViewCell() } return returnableCell } //MARK: - Header and Footer titles public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch datasourceType { case .multiSection : return multiSectionsItems[section].headerTitle default : return nil } } public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch datasourceType { case .multiSection : return multiSectionsItems[section].footerTitle default : return nil } } //MARK: - Sections Indexes public func sectionIndexTitles(for tableView: UITableView) -> [String]? { switch datasourceType { case .multiSection : return multiSectionsItems.compactMap { $0.sectionIndexTitle } default : return nil } } public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { switch datasourceType { case .multiSection : return multiSectionsItems.firstIndex{$0.sectionIndexTitle ?? "" == title} ?? 0 default : return 0 } } // TODO:- Handle reorder only //MARK: - Editing and Reordering public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if let onCanEditRow = onCanEditRow { return onCanEditRow(indexPath) } return true } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { if let onCanMoveRow = onCanMoveRow { return onCanMoveRow(indexPath) } return true } //MARK: - Data manupulation public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { switch datasourceType { case .singleSection: items.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) case .multiSection: multiSectionsItems[indexPath.section].items.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) case .unknown: break } } } public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { switch datasourceType { case .singleSection: let movedItem = items[sourceIndexPath.row] items.remove(at: sourceIndexPath.row) items.insert(movedItem, at: destinationIndexPath.row) reloadWithAnimation(tableView: tableView) case .multiSection : let movedItem = multiSectionsItems[sourceIndexPath.section].items[sourceIndexPath.row] multiSectionsItems[sourceIndexPath.section].items.remove(at: sourceIndexPath.row) multiSectionsItems[destinationIndexPath.section].items.insert(movedItem, at: destinationIndexPath.row) reloadWithAnimation(tableView: tableView) case .unknown : break } } } //MARK: - Private private extension AMUITableViewDatasourcerer { /// Create an animation for the reload of the tableview /// /// - Parameter tableView: the table to update func reloadWithAnimation(tableView: UITableView) { UIView.transition(with: tableView, duration: 0.25, options: .transitionCrossDissolve, animations: {tableView.reloadData() }) } } //MARK: - Class DatasourcererMultisectionItem public class DatasourcererMultisectionItem<T> { //MARK: - Properties let headerTitle: String let footerTitle: String? let sectionIndexTitle: String? var items: [T] //MARK: - Initializer init(headerTitle: String, footerTitle: String? = nil, sectionIndexTitle: String? = nil, items: [T]) { self.headerTitle = headerTitle self.footerTitle = footerTitle self.sectionIndexTitle = sectionIndexTitle self.items = items } }
38.76
145
0.666925
e25d60031786c85496b8cd315fb7eb1a8acd4ce4
1,537
// // DebugFpsLabel.swift // ScheduleChart // // Created by Alexander Graschenkov on 10/03/2019. // Copyright © 2019 Alex the Best. All rights reserved. // import UIKit class DebugFpsLabel: UILabel { var callTimes: [TimeInterval] = [] var timer: Timer? var onPrevDrawCalled = false override var isEnabled: Bool { didSet { if !isEnabled { text = "Redraw per/sec" } } } func startCapture() { if timer != nil { return } timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateLabel), userInfo: nil, repeats: true) } func stopCapture() { timer?.invalidate() timer = nil } func drawCalled() { callTimes.append(CFAbsoluteTimeGetCurrent()) if callTimes.count > 10 { callTimes.remove(at: 0) } if !onPrevDrawCalled { updateLabel() } onPrevDrawCalled = !onPrevDrawCalled } @objc func updateLabel() { guard let last = callTimes.last, CFAbsoluteTimeGetCurrent() - last < 1.0 else { if isEnabled { text = "-" } callTimes.removeAll() return } if callTimes.count < 2 { return } if isEnabled { let fps = Double(callTimes.count-1) / (callTimes.last! - callTimes.first!) text = NSString(format: "%.2lf", fps) as String } } }
24.015625
133
0.532856
bb532bedef822857b232ac2473e27386ee60456e
530
// // MacRestrictedSoftware.swift // KMART // // Created by Nindi Gill on 15/2/21. // import Foundation struct MacRestrictedSoftware: Codable { // swiftlint:disable:next identifier_name var id: Int = -1 var name: String = "" var macTargets: MacTargets = MacTargets() var macExclusions: MacExclusions = MacExclusions() var scope: Bool { macTargets.scope || macExclusions.scope } var dictionary: [String: Any] { [ "id": id, "name": name ] } }
20.384615
54
0.598113
6114bab86b4e22fba1520eecc3aa4b0b7315199d
5,600
// // Sort.swift // swiftAlgorithm // // Created by 孟庆祥 on 2022/2/15. // public class BubbleSort<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { for var idx in 0..<array.count { var endIndex = array.count-1 for jdx in 1..<array.count-idx { if cmp(array[jdx], ele1: array[jdx-1]) == .orderedDescending { swapValue(leftIndex: jdx, rightIndex: jdx-1) endIndex = jdx } } idx = endIndex } return nil } } public class SelectSort<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { for idx in 0..<array.count { var maxIndex = 0 for jdx in 1..<array.count-idx { if cmp(array[maxIndex], ele1: array[jdx]) == .orderedDescending { maxIndex = jdx } } swapValue(leftIndex: maxIndex, rightIndex: array.count-1-idx) } return nil } } public class insetSort1<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { // guard var array = self.array else { return nil } for idx in 1..<array.count { let insetValue = array[idx] var cur = idx while cur > 0,array[cur-1]>insetValue { array[cur] = array[cur-1] cur -= 1 } array[cur] = insetValue } return array } } public class insetSort<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { // guard var array = self.array else { return nil } for idx in 1..<array.count { let insetValue = array[idx] var cur = idx let insetIndex = searchInsetIndex(value: insetValue, startIndex: 0, endIndex: idx) while cur > insetIndex { array[cur] = array[cur-1] cur -= 1 } array[insetIndex] = insetValue } return array } private func searchInsetIndex(value:E,startIndex:Int,endIndex:Int)->Int { var beginIndex = startIndex,endIndex = endIndex var mindIndex = array.count while beginIndex < endIndex { mindIndex = (beginIndex + endIndex)/2 if cmp(value, ele1: array[mindIndex]) == .orderedAscending { beginIndex = mindIndex + 1 }else { endIndex = mindIndex } } return beginIndex } public func binarySearch(array:[E],value:E)->Int { var beginIndex = 0,endIndex = array.count-1 var mindIndex = -1 while beginIndex < endIndex { mindIndex = (beginIndex + endIndex)/2 if cmp(array[mindIndex], ele1: value) == .orderedAscending { beginIndex = mindIndex + 1 }else if cmp(array[mindIndex], ele1: value) == .orderedDescending { endIndex = mindIndex }else { return mindIndex } } return -1 } } public class QuickSort<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { sort(begin: 0, end: array.count) return array } private func sort(begin:Int,end:Int) { if end - begin < 2 { return } let middleIndex = poivetIndex(begin: begin, end: end) sort(begin: begin, end: middleIndex) sort(begin: middleIndex+1, end: end) } private func poivetIndex(begin:Int,end:Int)->Int { var statrIndex:Int = begin, endIndex:Int = end-1 let poiteValue = array[begin] while statrIndex < endIndex { while statrIndex < endIndex { if cmp(poiteValue, ele1: array[endIndex]) == .orderedAscending { array[statrIndex] = array[endIndex] statrIndex += 1 break } endIndex -= 1 } while statrIndex < endIndex { if cmp(poiteValue, ele1: array[statrIndex]) == .orderedDescending { array[endIndex] = array[statrIndex] endIndex -= 1 break } statrIndex += 1 } } array[statrIndex] = poiteValue return statrIndex } } public class mergeSort<E:Comparable>:SortAbstract<E> { override internal func sort()->[E]? { sort(begin: 0, end: array.count) return array } private func sort(begin:Int,end:Int) { if end - begin < 2 { return } let middle:Int = (end+begin)/2 sort(begin: begin, end: middle) sort(begin: middle, end: end) merge(begin: begin, minddle: middle, end: end) } private func merge(begin:Int,minddle:Int, end:Int) { var tempArray = [E]() for num in begin...minddle { tempArray.append(array[num]) } var leftIndex = 0,rightIndex = minddle var writeIndex = begin let length = minddle - begin while leftIndex < length { if rightIndex<end,cmp(tempArray[leftIndex], ele1: array[rightIndex]) == .orderedAscending { array[writeIndex] = array[rightIndex] rightIndex += 1 }else { array[writeIndex] = tempArray[leftIndex] leftIndex += 1 } writeIndex += 1 } } }
30.107527
103
0.514107
c1f6612d28eeacd37acdd12ce846e937a8df5d15
504
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class a<T where T: A : b.Type) -> T : (n: b { """ enum A : Collection where S() -> { } typealias e = b(a)
36
79
0.706349
6248ab390afead1c5f606927b1df8582302323d7
12,108
// // ViewController.swift // KeepItOpen // // Created by Loïs Di Qual on 4/30/15. // Copyright (c) 2015 Scoop. All rights reserved. // import UIKit import CoreLocation import class FlatUIKit.FUIButton let LocationNotificationReceived = "LocationNotificationReceived" class ViewController: GAITrackedViewController, CLLocationManagerDelegate { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var mapView: GMSMapView! @IBOutlet private weak var actionButton: FUIButton! private var locationManager: CLLocationManager! enum LocationState: String { case Inactive = "inactive" case WaitingForLocation = "waitingForLocation" case Active = "active" } enum State: String { case Inactive = "inactive" case Active = "active" case Warning = "warning" } enum MapState: String { case Reduced = "reduced" case Expanded = "expanded" } private var isMaskInitted: Bool = false private var viewDidAppearOnce = false private var locationState: LocationState = .Inactive { didSet { CLS_LOG_SWIFT("Location state: \(oldValue.rawValue) => \(locationState.rawValue)") } } private var mapState: MapState = .Reduced { didSet { CLS_LOG_SWIFT("Map state: \(oldValue.rawValue) => \(mapState.rawValue)") } } private var state: State = .Inactive { didSet { CLS_LOG_SWIFT("State: \(oldValue.rawValue) => \(state.rawValue)") } } private var anchorLocation: CLLocation? private var regionBeingMonitored: CLRegion? private var cardMarker: GMSMarker? private var shouldShowOnboarding: Bool { return OnboardingVC.locationPermissionRequest.permissionState() != .Authorized || OnboardingVC.notificationPermissionRequest.permissionState() != .Authorized } private let RegionRadius: CLLocationDistance = 30 override func viewDidLoad() { super.viewDidLoad() actionButton.backgroundColor = UIColor.clearColor() actionButton.buttonColor = Color.yellowColor actionButton.cornerRadius = 5 actionButton.setTitleColor(Color.brownColor, forState: .Normal) actionButton.addTarget(self, action: "actionButtonPressed:", forControlEvents: .TouchUpInside) mapView.myLocationEnabled = true mapView.layer.mask = CAShapeLayer() mapView.layer.borderColor = Color.brownColor.CGColor mapView.layer.borderWidth = 4 locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters if CLLocationManager.authorizationStatus() == .AuthorizedAlways { locationManager.startUpdatingLocation() } updateUI(animated: false) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationWillEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: LocationNotificationReceived, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !viewDidAppearOnce && shouldShowOnboarding { let identifier = UIScreen.mainScreen().bounds.height < 600 ? "SmallOnboardingVC" : "OnboardingVC" let onboardingVC = storyboard!.instantiateViewControllerWithIdentifier(identifier) as! OnboardingVC presentViewController(onboardingVC, animated: true, completion: nil) } viewDidAppearOnce = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onLocalNotificationReceived:", name: LocationNotificationReceived, object: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } private var reducedPath: CGPath { return maskPath(false) } private var expandedPath: CGPath { return maskPath(true) } private func maskPath(expanded: Bool) -> CGPath { let mapViewFrame = mapView.frame let hypotenuse = sqrt(pow(mapViewFrame.width, 2) + pow(mapViewFrame.height, 2)) let circleRadius = expanded ? hypotenuse / 2 : min(mapViewFrame.height / 2 - 8, mapViewFrame.width * 1 / 3) let center = CGPointMake(mapViewFrame.width / 2, mapViewFrame.height / 2) let path = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: 0, endAngle: 2.0 * CGFloat(M_PI), clockwise: true).CGPath return path } override func viewDidLayoutSubviews() { if !isMaskInitted { (mapView.layer.mask as! CAShapeLayer).path = state == .Inactive ? reducedPath : expandedPath isMaskInitted = true } } private func updateUI(animated: Bool = true) { CLS_LOG_SWIFT("Updating UI for state \(state.rawValue)") if state == .Inactive { mapView.clear() cardMarker = nil mapView.userInteractionEnabled = false self.view.backgroundColor = Color.blueColor actionButton.setTitle("drop_card".localize(), forState: .Normal) subtitleLabel.text = "subtitle_inactive".localize() } else if state == .Active { mapView.userInteractionEnabled = true self.view.backgroundColor = Color.blueColor actionButton.setTitle("pickup_card".localize(), forState: .Normal) subtitleLabel.text = "subtitle_active".localize() } else if state == .Warning { mapView.userInteractionEnabled = true self.view.backgroundColor = Color.redColor actionButton.setTitle("pickup_card".localize(), forState: .Normal) subtitleLabel.text = "subtitle_warning".localize() } if animated { let animation = CABasicAnimation(keyPath: "path") animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false animation.fromValue = state == .Inactive ? expandedPath : reducedPath animation.toValue = state == .Inactive ? reducedPath : expandedPath animation.duration = 0.2 (mapView.layer.mask as! CAShapeLayer).addAnimation(animation, forKey: "path") } } // MARK: - Events @objc private func actionButtonPressed(button: UIButton) { CLS_LOG_SWIFT("Action button pressed while state was \(state.rawValue)") if state == .Active { stopMonitoringRegion() state = .Inactive updateUI() return } if state == .Warning { state = .Inactive updateUI() return } locationManager.requestAlwaysAuthorization() let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) if let location = locationManager.location { onAnchorLocationDetermined(location) } else { locationManager.startUpdatingLocation() state = .Active locationState = .WaitingForLocation } updateUI() } @objc private func onLocalNotificationReceived(notification: NSNotification) { let localNotification = notification.object as! UILocalNotification CLS_LOG_SWIFT("Got local notification: \(localNotification)") } @objc private func onApplicationDidEnterBackground(notification: NSNotification) { if state == .Inactive { CLS_LOG_SWIFT("Stopping location updates") locationManager.stopUpdatingLocation() } } @objc private func onApplicationWillEnterForeground(notification: NSNotification) { if presentedViewController == nil && state != .Active { CLS_LOG_SWIFT("Starting location updates") locationManager.startUpdatingLocation() } } // MARK: - Location private func onAnchorLocationDetermined(location: CLLocation) { CLS_LOG_SWIFT("Anchor location: \(location)") anchorLocation = location regionBeingMonitored = CLCircularRegion(center: anchorLocation!.coordinate, radius: RegionRadius, identifier: "myCardRegion") locationManager.stopUpdatingLocation() locationManager.startMonitoringForRegion(regionBeingMonitored) locationState = .Inactive state = .Active cardMarker = GMSMarker(position: location.coordinate) cardMarker!.appearAnimation = kGMSMarkerAnimationPop cardMarker!.title = "My Card" cardMarker!.map = mapView mapView.selectedMarker = cardMarker } private func onLocationDeterminedInWarningState(location: CLLocation) { let padding: CGFloat = 30.0 let bounds = GMSCoordinateBounds(coordinate: location.coordinate, coordinate: cardMarker!.position) let cameraPosition = mapView.cameraForBounds(bounds, insets: UIEdgeInsetsMake(padding, padding, padding, padding)) mapView.animateToCameraPosition(cameraPosition) locationState = .Active } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let location = locations[0] as! CLLocation if locationState == .WaitingForLocation { if state == .Active { onAnchorLocationDetermined(location) } else if state == .Warning { onLocationDeterminedInWarningState(location) } } if state == .Inactive { mapView.camera = GMSCameraPosition.cameraWithTarget(location.coordinate, zoom: 15) } } // MARK: - Region Monitoring private func stopMonitoringRegion() { CLS_LOG_SWIFT("Stopping region monitoring") if let regionBeingMonitored = regionBeingMonitored { locationManager.stopMonitoringForRegion(regionBeingMonitored) } regionBeingMonitored = nil if CLLocationManager.authorizationStatus() == .AuthorizedAlways { locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { if regionBeingMonitored == nil { CLS_LOG_SWIFT("Ignoring region exit: \(region)") return } CLS_LOG_SWIFT("Went out of region \(region)") locationState = .WaitingForLocation state = .Warning updateUI() locationManager.startUpdatingLocation() let notification = UILocalNotification() notification.alertTitle = "Don't forget your card!" notification.alertBody = "Hey you! Don't forget your credit card!" notification.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().scheduleLocalNotification(notification) stopMonitoringRegion() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
36.802432
174
0.645606
d786a8c8a9275e58ac0bf636d1e213314797a7bf
1,665
// // CustomListHeaderRow.swift // MovieSwift // // Created by Josh Naylor on 08/07/2019. // Copyright © 2019 Josh Naylor. All rights reserved. // import SwiftUI import SwiftUIFlux import Backend struct CustomListHeaderRow : View { @EnvironmentObject var store: Store<AppState> @Binding var sorting: MoviesSort let listId: Int var list: CustomList { return store.state.moviesState.customLists[listId]! } var coverBackdropMovie: Movie? { guard let id = list.cover else { return nil } return store.state.moviesState.movies[id] } var body: some View { ZStack(alignment: .bottomLeading) { MovieTopBackdropImage(imageLoader: ImageLoaderCache.shared.loaderFor(path: coverBackdropMovie?.backdrop_path ?? coverBackdropMovie?.poster_path, size: .original), height: 200) VStack(alignment: .leading, spacing: 8) { Text(list.name) .font(.FjallaOne(size: 40)) .foregroundColor(.steam_gold) Text("\(list.movies.count) movies sorted \(sorting.title())") .font(.subheadline) .foregroundColor(.white) }.padding() } .frame(height: 200) .listRowInsets(EdgeInsets()) } } #if DEBUG struct CustomListHeaderRow_Previews : PreviewProvider { static var previews: some View { CustomListHeaderRow(sorting: .constant(.byAddedDate), listId: 0).environmentObject(sampleStore) } } #endif
30.833333
156
0.583183
28f324c850fd1c450723425dcae7038793743a1a
2,732
// // HelpingFunctions.swift // corectl // // Created by Rimantas Mocevicius on 06/07/2016. // Copyright © 2016 The New Normal. All rights reserved. // import Foundation import Cocoa // check if corectl blobs exist func check_that_corectl_blobs_are_in_place() { // Get App's resource folder let resoucesPathFromApp = Bundle.main.resourcePath! let bin_folder = resoucesPathFromApp + "/bin" // check for corectl files in user's home folder let filePath1 = NSHomeDirectory() + "/bin/corectl" if (FileManager.default.fileExists(atPath: filePath1)) { print("corectl available"); } else { print("corectl not available"); runScript("copy_corectl_blobs.command", arguments: bin_folder ) } // let filePath2 = NSHomeDirectory() + "/bin/corectld" if (FileManager.default.fileExists(atPath: filePath2)) { print("corectld available"); } else { print("corectld not available"); runScript("copy_corectl_blobs.command", arguments: bin_folder ) } // let filePath3 = NSHomeDirectory() + "/bin/corectld.runner" if (FileManager.default.fileExists(atPath: filePath3)) { print("corectld.runner available"); } else { print("corectld.runner not available"); runScript("copy_corectl_blobs.command", arguments: bin_folder ) } // let filePath4 = NSHomeDirectory() + "/bin/qcow-tool" if (FileManager.default.fileExists(atPath: filePath4)) { print("qcow-tool available"); } else { print("qcow-tool not available"); runScript("copy_corectl_blobs.command", arguments: bin_folder ) } } // start local docker registry func startDockerRegistry() { let resoucesPathFromApp = Bundle.main.resourcePath! runScript("start_docker_registry.command", arguments: resoucesPathFromApp ) } // Adds the app to the system's list of login items. // NOTE: This is a relatively janky way of doing this. Using a // bundled helper app is Apple's recommended approach, but that // has a lot of configuration overhead to get right. func addToLoginItems() { Process.launchedProcess( launchPath: "/usr/bin/osascript", arguments: [ "-e", "tell application \"System Events\" to make login item at end with properties {path:\"/Applications/corectl.app\", hidden:false, name:\"Corectl\"}" ] ) } // send notification to screen func notifyUserWithTitle(_ title: String, text: String) { let notification: NSUserNotification = NSUserNotification() notification.title = title notification.informativeText = text NSUserNotificationCenter.default.deliver(notification) }
29.06383
159
0.672401
20138a4e31bd667944b2b95560d254e224537d46
4,303
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic class SyncronizedQueueTests: XCTestCase { func testSingleProducerConsumer() { let queue = SynchronizedQueue<Int?>() let queueElements = Set(0..<10) var consumed = Set<Int>() let producer = Thread { for element in queueElements { queue.enqueue(element) } queue.enqueue(nil) } let consumer = Thread { while let element = queue.dequeue() { consumed.insert(element) } } consumer.start() producer.start() consumer.join() producer.join() XCTAssertEqual(consumed, queueElements) } func testMultipleProducerConsumer() { let queue = SynchronizedQueue<Int?>() let queueElementsOne = Set(0..<100) let queueElementsTwo = Set(100..<500) var consumed = Set<Int>() let consumedLock = TSCBasic.Lock() // Create two producers. let producers = [queueElementsOne, queueElementsTwo].map { queueElements in return Thread { for element in queueElements { queue.enqueue(element) } queue.enqueue(nil) } } // Create two consumers. let consumers = [0, 1].map { _ in return Thread { while let element = queue.dequeue() { consumedLock.withLock { _ = consumed.insert(element) } } } } consumers.forEach { $0.start() } producers.forEach { $0.start() } // Block until all producers and consumers are done. consumers.forEach { $0.join() } producers.forEach { $0.join() } // Make sure everything was consumed. XCTAssertEqual(consumed, queueElementsOne.union(queueElementsTwo)) } // Stress test for queue. Can produce an element only when current element gets consumed so // the consumer will get repeatedly blocked waiting to be singaled before start again. func testMultipleProducerConsumer2() { let queue = SynchronizedQueue<Int?>() let queueElementsOne = Set(0..<1000) let queueElementsTwo = Set(1000..<5000) var consumed = Set<Int>() let canProduceCondition = Condition() // Initially we should be able to produce. var canProduce = true // Create two producers. let producers = [queueElementsOne, queueElementsTwo].map { queueElements in return Thread { for element in queueElements { canProduceCondition.whileLocked { // If we shouldn't produce, block. while !canProduce { canProduceCondition.wait() } // We're producing one element so don't produce next until its consumed. canProduce = false queue.enqueue(element) } } queue.enqueue(nil) } } // Create two consumers. let consumers = [0, 1].map { _ in return Thread { while let element = queue.dequeue() { canProduceCondition.whileLocked { consumed.insert(element) canProduce = true canProduceCondition.signal() } } } } consumers.forEach { $0.start() } producers.forEach { $0.start() } // Block until all producers and consumers are done. consumers.forEach { $0.join() } producers.forEach { $0.join() } // Make sure everything was consumed. XCTAssertEqual(consumed, queueElementsOne.union(queueElementsTwo)) } }
31.181159
96
0.543109
9b97df5874336f9735f0ea60d9efb8a9e29ed8e2
594
// // BaseViewControllerModels.swift // PRODUCTNAME // // Created by LEADDEVELOPER on 03/06/2017. // Copyright © 2017 ORGANIZATION. All rights reserved. // import Foundation import UIKit protocol BaseViewControllerProtocol { func showError(error: BaseError) func showLoadingIndicator() func hideLoadingIndicator() func transtitionToNextViewController(fromViewController: UIViewController, destinationViewController: UIViewController?, transitionType: ViewControllerPresentationType?) } protocol BasePresenterProtocol { func bindUI(viewController: UIViewController) }
27
173
0.796296
3af728b02d9aaf8d14fda86a15977ba12fe83f4d
826
// // _UIApplication.swift // Appt // // Created by Yurii Kozlov on 6/4/21. // Copyright © 2021 Stichting Appt. All rights reserved. // import UIKit extension UIApplication { class func topViewController(_ viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = viewController as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = viewController as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = viewController?.presentedViewController { return topViewController(presented) } return viewController } }
30.592593
145
0.66707
5b76b19acb11e0c951586d107c420669dec8d34c
945
// // Copyright © 2021 Toby O'Connell. All rights reserved. // import UIKit public struct ScenarioID: CaseIterable, RawRepresentable { var scenarioType: Scenario.Type init(type: Scenario.Type) { scenarioType = type } public init?(rawValue: String) { guard let type = NSClassFromString(rawValue) else { return nil } guard let conformingType = type as? Scenario.Type else { return nil } scenarioType = conformingType } public var rawValue: String { scenarioType.id } public static let allCases: [ScenarioID] = { var count: UInt32 = 0 let classes = objc_copyClassList(&count) let buffer = UnsafeBufferPointer(start: classes, count: Int(count)) return Array( (0 ..< Int(count)) .lazy .compactMap { buffer[$0] as? Scenario.Type } .map { ScenarioID(type: $0) } ) }() }
26.25
77
0.595767
cc8250e379580bb27cdc593604d9ebdefc047db8
874
// Copyright © 2019 Lohan Marques. All rights reserved. import Foundation import CoreData @objc(Favorite) public class Favorite: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<Favorite> { return NSFetchRequest<Favorite>(entityName: "Favorite") } @NSManaged public var id: Int32 @NSManaged public var image: String? @NSManaged public var categoryName: String @NSManaged public var title: String @NSManaged public var author: String @NSManaged public var postDate: String @NSManaged public var content: String } extension Favorite { func toArticle() -> Article { return Article(id: id, image: image ?? "", categoryName: categoryName, title: title, author: author, postDate: postDate, content: content, isFavorite: true) } }
29.133333
78
0.670481
9bd45141d8ecf0a68a0c0bb6ef9d9fdc953ddd55
1,138
// // CustomItem_ActionSheetTests.swift // Sheeeeeeeeet // // Created by Daniel Saidi on 2019-09-17. // Copyright © 2019 Daniel Saidi. All rights reserved. // import Quick import Nimble import Sheeeeeeeeet import UIKit class CustomItem_ActionSheetTests: QuickSpec { override func spec() { describe("action sheet") { describe("height") { it("is cell type's default height") { let item = CustomItem(itemType: TestType.self, itemSetupAction: { _ in }) let expected = Double(TestType.preferredSize.height) expect(item.actionSheetCellHeight).to(equal(expected)) } } describe("cell") { it("registers nib, dequeues cell and sets up cell") { // TODO: How to test this in SPM, which doesn't support bundles? } } } } } private class TestType: ActionSheetItemCell, CustomItemType { static let preferredSize = CGSize(width: 100, height: 400) }
26.465116
93
0.54833
9b19fb2ece791189dc20cee5443529bd685ccd3b
1,525
// // DataDragonSummonerSpellBusiness.swift // LeagueAPI // // Created by Antoine Clop on 8/23/18. // Copyright © 2018 Antoine Clop. All rights reserved. // import Foundation internal class DataDragonSummonerSpellBusiness { public static func getSummonerSpells(completion: @escaping ([SummonerSpell]?, String?) -> Void) { DataDragonRequester.instance.getSummonerSpells() { (summonerSpellFile, error) in completion(summonerSpellFile?.summonerSpells, error) } } public static func getSummonerSpell(by id: SummonerSpellId, completion: @escaping (SummonerSpell?, String?) -> Void) { getSummonerSpells() { (summonerSpells, error) in if let summonerSpells = summonerSpells { summonerSpells.firstMatch(where: { $0.id == id }, notFoundMessage: "Summoner spell with id=\(id) not found.", completion: completion) } else { completion(nil, error) } } } public static func getSummonerSpell(byName name: String, completion: @escaping (SummonerSpell?, String?) -> Void) { getSummonerSpells() { (summonerSpells, error) in if let summonerSpells = summonerSpells { summonerSpells.firstMatch(where: { $0.name.equals(name) || $0.nameId.equals(name) }, notFoundMessage: "Summoner spell with name=\(name) not found.", completion: completion) } else { completion(nil, error) } } } }
37.195122
188
0.62623
ef7f121346a3862b447c01340bd500b815252593
994
// // Awesome_ResumeTests.swift // Awesome ResumeTests // // Created by Hien Tran on 3/9/17. // Copyright © 2017 Awesome Team. All rights reserved. // import XCTest @testable import Awesome_Resume class Awesome_ResumeTests: 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.864865
111
0.639839
1a4f4cd9e5bc0f78c4327614d5ff0bada11b607c
1,349
// // AppDelegate.swift // SwiftBoilterplate // // Created by Wataru Maeda on 2020/12/27. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. print("🚀 environment: \(AppEnv.env)") 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. } }
42.15625
177
0.771683
c19a94080db4e1e1220a957318e27cbf84b7b5a3
886
// // tipsTests.swift // tipsTests // // Created by Jiaqi Wu on 12/23/15. // Copyright (c) 2015 Jiaqi Wu. All rights reserved. // import UIKit import XCTest class tipsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
23.945946
111
0.607223
01e0252f12f5ec9426cb9e215ab218597a2cd752
3,137
import Foundation import azureSwiftRuntime public protocol RecordSetsGet { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var zoneName : String { get set } var relativeRecordSetName : String { get set } var recordType : RecordTypeEnum { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (RecordSetProtocol?, Error?) -> Void) -> Void ; } extension Commands.RecordSets { // Get gets a record set. internal class GetCommand : BaseCommand, RecordSetsGet { public var resourceGroupName : String public var zoneName : String public var relativeRecordSetName : String public var recordType : RecordTypeEnum public var subscriptionId : String public var apiVersion = "2017-10-01" public init(resourceGroupName: String, zoneName: String, relativeRecordSetName: String, recordType: RecordTypeEnum, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.zoneName = zoneName self.relativeRecordSetName = relativeRecordSetName self.recordType = recordType self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{zoneName}"] = String(describing: self.zoneName) self.pathParameters["{relativeRecordSetName}"] = String(describing: self.relativeRecordSetName) self.pathParameters["{recordType}"] = String(describing: self.recordType) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(RecordSetData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (RecordSetProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: RecordSetData?, error: Error?) in completionHandler(result, error) } } } }
47.530303
178
0.642971
6a19f205c83a3d004df495349a7c8df690cd838b
9,630
// YatTransactionModel.swift /* Package MobileWallet Created by Adrian Truszczynski on 21/10/2021 Using Swift 5.0 Running on macOS 12.0 Copyright 2019 The Tari Project Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Combine import YatLib import Foundation enum YatTransactionViewState { case idle case initial(transaction: String, yatID: String) case playVideo(url: URL, scaleToFill: Bool) case completion case failed } enum TransactionError: Error { case noConnection case general } final class YatTransactionModel { struct InputData { let publicKey: PublicKey let amount: MicroTari let message: String let yatID: String } // MARK: - View Model @Published private(set) var viewState: YatTransactionViewState = .idle @Published private(set) var error: TransactionError? // MARK: - Constants private let connectionTimeout = 30 // MARK: - Properties private let inputData: InputData private let cacheManager = YatCacheManager() private var txId: UInt64? private var cancellables = Set<AnyCancellable>() private var walletEventsCancellables = Set<AnyCancellable>() // MARK: - Initializers init(inputData: InputData) { self.inputData = inputData } // MARK: - Actions func start() { guard case .idle = viewState else { return } self.setupInitialViewState() waitForConnection { [weak self] in self?.verifyWalletStateAndSendTransactionToBlockchain() self?.fetchAnimation() } } private func setupInitialViewState() { let amount = "\(inputData.amount.formatted) \(NetworkManager.shared.selectedNetwork.tickerSymbol)" viewState = .initial(transaction: localized("yat_transaction.label.transaction.sending", arguments: amount), yatID: inputData.yatID) } private func show(error: TransactionError) { self.error = error viewState = .failed } private func waitForConnection(completed: @escaping () -> Void) { let connectionState = ConnectionMonitor.shared.state switch connectionState.reachability { case .offline, .unknown: show(error: .noConnection) default: break } let startDate = Date() Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in if connectionState.torStatus == .connected, connectionState.torBootstrapProgress == 100 { timer.invalidate() completed() return } guard let self = self, Int(-startDate.timeIntervalSinceNow) > self.connectionTimeout else { return } timer.invalidate() self.show(error: .general) } } // MARK: - Yat Visualisation private func fetchAnimation() { Yat.api.fetchFromKeyValueStorePublisher(forYat: inputData.yatID, dataType: VisualizerFileLocations.self) .map(\.data) .sink( receiveCompletion: { _ in }, receiveValue: { [weak self] in self?.handle(fileLocations: $0) } ) .store(in: &cancellables) } private func handle(fileLocations: VisualizerFileLocations) { guard let path = fileLocations.verticalVideo ?? fileLocations.video, let url = URL(string: path) else { return } guard let cachedFileData = cacheManager.fetchFileData(name: url.lastPathComponent) else { download(assetURL: url) return } play(fileData: cachedFileData) TariLogger.info("Play Yat visualisation from local cache") } private func download(assetURL: URL) { URLSession.shared.dataTaskPublisher(for: assetURL) .map(\.data) .sink( receiveCompletion: { _ in }, receiveValue: { [weak self] data in self?.save(videoData: data, name: assetURL.lastPathComponent) } ) .store(in: &cancellables) } private func save(videoData: Data, name: String) { guard let fileData = cacheManager.save(data: videoData, name: name) else { return } play(fileData: fileData) TariLogger.info("Play Yat visualisation from web") } private func play(fileData: YatCacheManager.FileData) { let scaleToFill = fileData.identifier == .verticalVideo viewState = .playVideo(url: fileData.url, scaleToFill: scaleToFill) } // MARK: - Wallet private func verifyWalletStateAndSendTransactionToBlockchain() { var cancel: AnyCancellable? cancel = TariLib.shared.walletStatePublisher .receive(on: RunLoop.main) .sink { [weak self] walletState in switch walletState { case .started: cancel?.cancel() self?.sendTransactionToBlockchain() case .startFailed: cancel?.cancel() self?.show(error: .general) case .notReady, .starting: break } } cancel?.store(in: &cancellables) } private func sendTransactionToBlockchain() { guard let wallet = TariLib.shared.tariWallet else { return } do { txId = try wallet.sendTx(destination: inputData.publicKey, amount: inputData.amount, feePerGram: Wallet.defaultFeePerGram, message: inputData.message) startListeningForWalletEvents() } catch { show(error: .general) } } private func startListeningForWalletEvents() { let directSendPublisher = TariEventBus.events(forType: .directSend) .compactMap { $0.object as? CallbackTxResult } .filter { [weak self] in $0.id == self?.txId } let storeAndForwardPublisher = TariEventBus.events(forType: .storeAndForwardSend) .compactMap { $0.object as? CallbackTxResult } .filter { [weak self] in $0.id == self?.txId } directSendPublisher .filter(\.success) .sink { [weak self] _ in self?.cancelWalletEvents() self?.sendPushNotificationToRecipient() TariLogger.info("Direct send successful.") Tracker.shared.track(eventWithCategory: "Transaction", action: "Transaction Accepted - Synchronous") } .store(in: &walletEventsCancellables) storeAndForwardPublisher .filter(\.success) .sink { [weak self] _ in self?.cancelWalletEvents() self?.sendPushNotificationToRecipient() TariLogger.info("Store and forward send successful.") Tracker.shared.track(eventWithCategory: "Transaction", action: "Transaction Stored") } .store(in: &walletEventsCancellables) Publishers.CombineLatest(directSendPublisher, storeAndForwardPublisher) .filter { $0.success == false && $1.success == false} .sink { [weak self] _ in self?.cancelWalletEvents() self?.show(error: .general) } .store(in: &walletEventsCancellables) } private func sendPushNotificationToRecipient() { do { try NotificationManager.shared.sendToRecipient( inputData.publicKey, onSuccess: { TariLogger.info("Recipient has been notified") }, onError: { TariLogger.error("Failed to notify recipient", error: $0) } ) } catch { TariLogger.error("Failed to notify recipient", error: error) } viewState = .completion } private func cancelWalletEvents() { walletEventsCancellables.forEach { $0.cancel() } } }
34.028269
162
0.619107
75ddfaf679d533c8a93f682e2e6e7e8526f080c7
210
// // Copyright © 2019 An Tran. All rights reserved. // import SuperArcCoreUI class DashboardViewController: TabBarController<ViewModel>, StoryboardInitiable { static var storyboardName = "Dashboard" }
19.090909
81
0.761905
e026a1b31f5dc74f925ee4a3104c0a00ef47e6dc
8,167
// // BRAPIClient+Wallet.swift // breadwallet // // Created by Samuel Sutch on 4/2/17. // Copyright © 2017 breadwallet LLC. All rights reserved. // import Foundation enum RatesResult { case success([Rate]) case error(String) } extension BRAPIClient { func me() { let req = URLRequest(url: url("/me")) let task = dataTaskWithRequest(req, authenticated: true, handler: { data, _, _ in if let data = data { print("me: \(String(describing: String(data: data, encoding: .utf8)))") } }) task.resume() } func feePerKb(code: String, _ handler: @escaping (_ fees: Fees, _ error: String?) -> Void) { let param = code == Currencies.bch.code ? "?currency=BCH" : "" // print(param) // let req = URLRequest(url: url("/fee-per-kb\(param)")) let req = URLRequest(url: URL(string: "https://stage2.breadwallet.com/fee-per-kb\(param)")!) let task = self.dataTaskWithRequest(req) { (data, _, err) -> Void in var regularFeePerKb: uint_fast64_t = 0 var economyFeePerKb: uint_fast64_t = 0 var errStr: String? if err == nil { do { let parsedObject: Any? = try JSONSerialization.jsonObject( with: data!, options: JSONSerialization.ReadingOptions.allowFragments) if let top = parsedObject as? NSDictionary, let regular = top["fee_per_kb"] as? NSNumber, let economy = top["fee_per_kb_economy"] as? NSNumber { regularFeePerKb = regular.uint64Value economyFeePerKb = economy.uint64Value } } catch (let e) { self.log("fee-per-kb: error parsing json \(e)") } if regularFeePerKb == 0 || economyFeePerKb == 0 { errStr = "invalid json" } } else { self.log("fee-per-kb network error: \(String(describing: err))") errStr = "bad network connection" } handler(Fees(regular: regularFeePerKb, economy: economyFeePerKb, timestamp: Date().timeIntervalSince1970), errStr) } task.resume() } /// Fetches Bitcoin exchange rates in all available fiat currencies func bitcoinExchangeRates(isFallback: Bool = false, _ handler: @escaping (RatesResult) -> Void) { let code = Currencies.btc.code let strURL = "\(bitpayAPI)/rates/\(code)" let task = dataTaskWithRequest(URLRequest(url: URL(string: strURL)!)) { (data, _, error) in if error == nil, let data = data, let parsedData = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) { if isFallback { guard let array = parsedData as? [Any] else { return handler(.error("/rates didn't return an array")) } handler(.success(array.compactMap { Rate(data: $0, reciprocalCode: code) })) } else { guard let dict = parsedData as? [String: Any], let array = dict["body"] as? [Any] else { return self.bitcoinExchangeRates(isFallback: true, handler) } handler(.success(array.compactMap { Rate(data: $0, reciprocalCode: code) })) } } else { if isFallback { handler(.error("Error fetching from fallback url")) } else { self.bitcoinExchangeRates(isFallback: true, handler) } } } task.resume() } /// Fetches all token exchange rates in BTC from CoinMarketCap func tokenExchangeRates(_ handler: @escaping (RatesResult) -> Void) { let request = URLRequest(url: URL(string: "\(coinmarketAPI)/ticker/?convert=BTC")!) dataTaskWithRequest(request, handler: { data, _, error in if error == nil, let data = data { do { let codes = Store.state.currencies.map({ $0.code.lowercased() }) let tickers = try JSONDecoder().decode([Ticker].self, from: data) let rates: [Rate] = tickers.compactMap({ ticker in guard ticker.btcRate != nil, let rate = Double(ticker.btcRate!) else { return nil } guard codes.contains(ticker.symbol.lowercased()) else { return nil } return Rate(code: Currencies.btc.code, name: ticker.name, rate: rate, reciprocalCode: ticker.symbol.lowercased()) }) handler(.success(rates)) } catch let e { handler(.error(e.localizedDescription)) } } else { handler(.error(error?.localizedDescription ?? "unknown error")) } }).resume() } func savePushNotificationToken(_ token: Data) { var req = URLRequest(url: url("/me/push-devices")) req.httpMethod = "POST" req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.setValue("application/json", forHTTPHeaderField: "Accept") let reqJson = [ "token": token.hexString, "service": "apns", "data": [ "e": pushNotificationEnvironment(), "b": Bundle.main.bundleIdentifier!] ] as [String: Any] do { let dat = try JSONSerialization.data(withJSONObject: reqJson, options: .prettyPrinted) req.httpBody = dat } catch (let e) { log("JSON Serialization error \(e)") return } dataTaskWithRequest(req as URLRequest, authenticated: true, retryCount: 0) { (dat, resp, _) in let dat2 = String(data: dat ?? Data(), encoding: .utf8) self.log("save push token resp: \(String(describing: resp)) data: \(String(describing: dat2))") }.resume() } func deletePushNotificationToken(_ token: Data) { var req = URLRequest(url: url("/me/push-devices/apns/\(token.hexString)")) req.httpMethod = "DELETE" dataTaskWithRequest(req as URLRequest, authenticated: true, retryCount: 0) { (_, resp, _) in self.log("delete push token resp: \(String(describing: resp))") if let statusCode = resp?.statusCode { if statusCode >= 200 && statusCode < 300 { UserDefaults.pushToken = nil self.log("deleted old token") } } }.resume() } func fetchUTXOS(address: String, currency: CurrencyDef, completion: @escaping ([[String: Any]]?) -> Void) { let path = currency.matches(Currencies.btc) ? "/q/addrs/utxo" : "/q/addrs/utxo?currency=bch" var req = URLRequest(url: url(path)) req.httpMethod = "POST" req.httpBody = "addrs=\(address)".data(using: .utf8) dataTaskWithRequest(req, handler: { data, _, error in guard error == nil else { completion(nil); return } guard let data = data, let jsonData = try? JSONSerialization.jsonObject(with: data, options: []), let json = jsonData as? [[String: Any]] else { completion(nil); return } completion(json) }).resume() } } struct BTCRateResponse: Codable { let body: [BTCRate] struct BTCRate: Codable { let code: String let name: String let rate: Double } } struct Ticker: Codable { let symbol: String let name: String let usdRate: String? let btcRate: String? enum CodingKeys: String, CodingKey { case symbol case name case usdRate = "price_usd" case btcRate = "price_btc" } } private func pushNotificationEnvironment() -> String { return E.isDebug ? "d" : "p" //development or production }
41.456853
164
0.544263
896b81ffefa4a9e97595926731276353136c2201
1,739
/** * (C) Copyright IBM Corp. 2019, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. */ public struct Interpretation: Codable, Equatable { /** The value that was located in the normalized text. */ public var value: String? /** An integer or float expressing the numeric value of the `value` key. */ public var numericValue: Double? /** A string listing the unit of the value that was found in the normalized text. **Note:** The value of `unit` is the [ISO-4217 currency code](https://www.iso.org/iso-4217-currency-codes.html) identified for the currency amount (for example, `USD` or `EUR`). If the service cannot disambiguate a currency symbol (for example, `$` or `£`), the value of `unit` contains the ambiguous symbol as-is. */ public var unit: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case value = "value" case numericValue = "numeric_value" case unit = "unit" } }
34.098039
116
0.691777
3332cec3243b6ab587f2736e05853f9b2ed2f54e
3,057
// // Wrap.swift // Pods // // Created by Siarhei Fedartsou on 03.05.17. // // import Foundation import Result public func wrap<T, ErrorType: Error>(_ function: @escaping (@escaping (Result<T, ErrorType>) -> Void) -> Void) -> Job<T> { return Job { onSuccess, onFailure in function { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } public func wrap<A, T, ErrorType: Error>(_ function: @escaping (A, @escaping (Result<T, ErrorType>) -> Void) -> Void) -> ((A) -> Job<T>) { return { a in return Job { onSuccess, onFailure in function(a) { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } } public func wrap<A, B, T, ErrorType: Error>(_ function: @escaping (A, B, @escaping (Result<T, ErrorType>) -> Void) -> Void) -> ((A, B) -> Job<T>) { return { a, b in return Job { onSuccess, onFailure in function(a, b) { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } } public func wrap<A, B, C, T, ErrorType: Error>(_ function: @escaping (A, B, C, @escaping (Result<T, ErrorType>) -> Void) -> Void) -> ((A, B, C) -> Job<T>) { return { a, b, c in return Job { onSuccess, onFailure in function(a, b, c) { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } } public func wrap<A, B, C, D, T, ErrorType: Error>(_ function: @escaping (A, B, C, D, @escaping (Result<T, ErrorType>) -> Void) -> Void) -> ((A, B, C, D) -> Job<T>) { return { a, b, c, d in return Job { onSuccess, onFailure in function(a, b, c, d) { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } } public func wrap<A, B, C, D, E, T, ErrorType: Error>(_ function: @escaping (A, B, C, D, E, @escaping (Result<T, ErrorType>) -> Void) -> Void) -> ((A, B, C, D, E) -> Job<T>) { return { a, b, c, d, e in return Job { onSuccess, onFailure in function(a, b, c, d, e) { result in switch result { case .success(let value): onSuccess(value) case .failure(let error): onFailure(error) } } } } }
30.878788
174
0.464181
de1093dc529a1a31ce2df0948232764267cdbb70
527
// // HomeActions.swift // Pokedex // // Created by Ronan on 09/05/2019. // Copyright © 2019 Sonomos. All rights reserved. // import Common public protocol HomeActions { func ballButtonAction() func backpackButtonAction() } extension Actions: HomeActions { public func ballButtonAction() { coordinator.showCatchScene() } public func backpackButtonAction() { coordinator.showBackpackScene() } } import SwiftUI public protocol HomeUIScenes { func mainView() -> AnyView }
17
50
0.681214
64c19ddc50c32ff36656575784b9a43683995faa
5,628
// // KeyStorageAdapterTests.swift // TwilioVerifyTests // // Copyright © 2020 Twilio. // // 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 XCTest @testable import TwilioVerifySDK // swiftlint:disable force_cast class KeyStorageAdapterTests: XCTestCase { var signer: SignerMock! var keyManager: KeyManagerMock! var keyStorage: KeyStorage! override func setUpWithError() throws { try super.setUpWithError() signer = SignerMock() keyManager = KeyManagerMock() keyStorage = KeyStorageAdapter(keyManager: keyManager) } func testCreateKey_errorGettingSigner_shouldThrow() { keyManager.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.createKey(withAlias: Constants.alias), "Create key should throw") { error in XCTAssertEqual((error as! TestError), TestError.operationFailed) } } func testCreateKey_errorGettingPublicKey_shouldThrow() { keyManager.signer = signer signer.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.createKey(withAlias: Constants.alias), "Create key should throw") { error in XCTAssertEqual((error as! TestError), TestError.operationFailed) } } func testCreateKey_withoutErrors_shouldReturnPublicKey() { var key: String! let expectedKey = Constants.data.base64EncodedString() signer.operationresult = Constants.data keyManager.signer = signer XCTAssertNoThrow(key = try keyStorage.createKey(withAlias: Constants.alias), "Create key shouldn't throw") XCTAssertEqual(key, expectedKey, "Key should be \(expectedKey) but was \(key!)") } func testSign_errorGettingSigner_shouldThrow() { let expectedError = TwilioVerifyError.keyStorageError(error: TestError.operationFailed as NSError) keyManager.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.sign(withAlias: Constants.alias, message: Constants.message), "Create key should throw") { error in XCTAssertEqual((error as! TwilioVerifyError).originalError, expectedError.originalError) } } func testSign_errorGettingPublicKey_shouldThrow() { let expectedError = TwilioVerifyError.keyStorageError(error: TestError.operationFailed as NSError) keyManager.signer = signer signer.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.sign(withAlias: Constants.alias, message: Constants.message), "Create key should throw") { error in XCTAssertEqual((error as! TwilioVerifyError).originalError, expectedError.originalError) } } func testSign_withoutErrors_shouldReturnSignature() { var signature: Data! signer.operationresult = Constants.data keyManager.signer = signer XCTAssertNoThrow( signature = try keyStorage.sign(withAlias: Constants.alias, message: Constants.message), "Create key shouldn't throw" ) XCTAssertEqual(signature, Constants.data, "Key should be \(Constants.data) but was \(signature!)") } func testSignAndEncode_errorGettingSigner_shouldThrow() { let expectedError = TwilioVerifyError.keyStorageError(error: TestError.operationFailed as NSError) keyManager.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.signAndEncode(withAlias: Constants.alias, message: Constants.message), "Create key should throw") { error in XCTAssertEqual((error as! TwilioVerifyError).originalError, expectedError.originalError) } } func testSignAndEncode_errorGettingPublicKey_shouldThrow() { let expectedError = TwilioVerifyError.keyStorageError(error: TestError.operationFailed as NSError) keyManager.signer = signer signer.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.signAndEncode(withAlias: Constants.alias, message: Constants.message), "Create key should throw") { error in XCTAssertEqual((error as! TwilioVerifyError).originalError, expectedError.originalError) } } func testSignAndEncode_withoutErrors_shouldReturnSignature() { var signature: String! let expectedSignature = Constants.data.base64EncodedString() signer.operationresult = Constants.data keyManager.signer = signer XCTAssertNoThrow( signature = try keyStorage.signAndEncode(withAlias: Constants.alias, message: Constants.message), "Create key shouldn't throw" ) XCTAssertEqual(signature, expectedSignature, "Key should be \(expectedSignature) but was \(signature!)") } func testDelete_successfully_shouldNotThrow() { XCTAssertNoThrow(try keyStorage.deleteKey(withAlias: Constants.alias), "Delete key should not throw") } func testRemoveValue_unsuccessfully_shouldThrow() { keyManager.error = TestError.operationFailed XCTAssertThrowsError(try keyStorage.deleteKey(withAlias: Constants.alias), "Delete key should throw") { error in XCTAssertEqual((error as! TestError), TestError.operationFailed) } } } private extension KeyStorageAdapterTests { struct Constants { static let alias = "alias" static let message = "message" static let data = "data".data(using: .utf8)! } }
41.080292
148
0.757285
e0538043e36053efe309a296b5da84fc003abf23
1,962
//: ## Ring Modulator //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var ringModulator = AKRingModulator(player) ringModulator.frequency1 = 440 // Hz ringModulator.frequency2 = 660 // Hz ringModulator.balance = 0.5 ringModulator.mix = 0.5 AudioKit.output = ringModulator try AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Ring Modulator") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKButton(title: "Stop Ring Modulator") { button in let node = ringModulator node.isStarted ? node.stop() : node.play() button.title = node.isStarted ? "Stop Ring Modulator" : "Start Ring Modulator" }) addView(AKSlider(property: "Frequency 1", value: ringModulator.frequency1, range: 0.5 ... 8_000, format: "%0.2f Hz" ) { sliderValue in ringModulator.frequency1 = sliderValue }) addView(AKSlider(property: "Frequency 2", value: ringModulator.frequency2, range: 0.5 ... 8_000, format: "%0.2f Hz" ) { sliderValue in ringModulator.frequency2 = sliderValue }) addView(AKSlider(property: "Balance", value: ringModulator.balance) { sliderValue in ringModulator.balance = sliderValue }) addView(AKSlider(property: "Mix", value: ringModulator.mix) { sliderValue in ringModulator.mix = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
29.727273
96
0.632518
fe5873e0d4793a1642ec90d8a564833b696cee03
465
// // UIViewController+Chainable.swift // Webtoon.clone // // Created by Stat.So on 2020/11/15. // import UIKit extension UIViewController: Chainable { } extension Chain where Origin: UIViewController { @discardableResult func title(_ by: String?) -> Chain { self.origin.title = by return self } @discardableResult func setTabBarItem(_ tabBarItem: UITabBarItem) -> Chain { self.origin.tabBarItem = tabBarItem return self } }
17.884615
59
0.692473
9b094642a2f09911080284c352224cdee0683186
641
// // galleryTableViewCell.swift // Lady Elisabeth // // Created by philip mackie on 01/06/16. // Copyright © 2016 vilet studios. All rights reserved. // import UIKit class galleryTableViewCell: UITableViewCell { @IBOutlet var Picture: UIImageView! @IBOutlet var author: UILabel! @IBOutlet var profile: UIImageView! 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 } }
19.424242
63
0.659906
230d5495187543139d044a4a9ac1259ed8c469ff
1,333
// // NSNumberExtension.swift // SwiftyExtension // // Created by Khoi Nguyen on 7/25/18. // Copyright © 2018 Nguyen. All rights reserved. // import UIKit struct Number { static let formatterWithSepator: NumberFormatter = { let formatter = NumberFormatter() formatter.groupingSeparator = "," formatter.decimalSeparator = "." formatter.numberStyle = .decimal return formatter }() } extension NSInteger { var stringFormatedWithSepator: String { let number = NSNumber(integerLiteral: hashValue) return Number.formatterWithSepator.string(from: number) ?? "" } } extension Double{ func stringWithSeparator(minimumFractionDigits: Int=0, maximumFractionDigits: Int=8) -> String{ let formatter = NumberFormatter() formatter.groupingSeparator = "," formatter.decimalSeparator = "." formatter.numberStyle = .decimal formatter.minimumFractionDigits = minimumFractionDigits formatter.maximumFractionDigits = maximumFractionDigits formatter.minimumIntegerDigits = 1 return formatter.string(from: NSNumber.init(value: self)) ?? "" } func toString(maximumFractionDigits: Int=0) -> String { return String(format: "%.\(maximumFractionDigits)f", self) } }
28.978261
99
0.667667
8aacff0a0146d661e554c68c647edf7657f99556
4,079
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: __shared NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: __shared NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: __shared NSString) { self.init(string: aString as String) } } extension NSString : _CustomPlaygroundQuickLookable { @available(*, deprecated, message: "NSString.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
35.163793
116
0.658004
b96c5ebb2502602807a2541d552f52c7a09c1bea
2,880
// // IndexPathCache.swift // // Copyright © 2017 Zeeshan Mian // // 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 /// A helper struct to cache index path values for `UITableView` and `UICollectionView`. struct IndexPathCache<Value> { private var dictionary = [String: Value]() private let defaultValue: Value init(defaultValue: Value) { self.defaultValue = defaultValue } private func key(for indexPath: IndexPath) -> String { return "\(indexPath.section)-\(indexPath.row)" } /// Set estimated cell value to cache. /// /// - Parameters: /// - value: The value to cache for the given index path. /// - indexPath: The index path to cache. private mutating func set(value: Value, for indexPath: IndexPath) { dictionary[key(for: indexPath)] = value } /// Get estimated cell value from cache. /// /// - Parameter indexPath: The index path to get the cached value for. /// - Returns: The cached value if exists; otherwise, `defaultValue`. private func get(indexPath: IndexPath) -> Value { guard let estimatedValue = dictionary[key(for: indexPath)] else { return defaultValue } return estimatedValue } func exists(for indexPath: IndexPath) -> Bool { return dictionary[key(for: indexPath)] != nil } subscript(indexPath: IndexPath) -> Value { get { return get(indexPath: indexPath) } set { set(value: newValue, for: indexPath) } } mutating func removeAll() { dictionary.removeAll(keepingCapacity: false) } mutating func remove(at indexPath: IndexPath) { dictionary[key(for: indexPath)] = nil } var count: Int { return dictionary.count } var isEmpty: Bool { return dictionary.isEmpty } }
33.488372
88
0.681944
7106750b72551db8e313106372ac4e28c951b1ad
4,228
// // AppDelegate.swift // InvestLog // // Created by timofey makhlay on 1/19/19. // Copyright © 2019 Timofey Makhlay. All rights reserved. // import UIKit import Firebase import GoogleSignIn @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Configure Firebase FirebaseApp.configure() // Google account logIn GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID GIDSignIn.sharedInstance().delegate = self // Override point for customization after application launch. let initialViewController = BackgroundViewController() window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() // Check name of fonts // for family: String in UIFont.familyNames // { // print("\(family)") // for names: String in UIFont.fontNames(forFamilyName: family) // { // print("== \(names)") // } // } return true } //For Google Sign in func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: [:]) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { // ... if let error = error { print("Problem at signing in with google with error : \(error)") return } guard let authentication = user.authentication else { return } // let credentials _ = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) // ... } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // Perform any operations when the user disconnects from app here. // ... } 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:. } }
43.142857
285
0.659413
9184f99e9801c22efa3eb3b95e49a96528b959f6
604
// // Hello.swift // instrumens // // Created by fenomeno69 on 04/01/2017. // Copyright © 2017 Fotis Kalaitzidis. All rights reserved. // import Foundation class WelcomeVC: UIViewController { @IBOutlet weak var Open: UIBarButtonItem! override func viewDidLoad() { if revealViewController() != nil { Open.target = self.revealViewController() Open.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } }
21.571429
90
0.63245
91bc0e7bfc09ead17bb8b67f00a8f35419e0e05a
8,842
import Foundation import Prch public extension Releases { /** Return a list of releases for a given organization. */ enum ListAnOrganizationsReleases { public static let service = APIService<Response>(id: "List an Organization's Releases", tag: "Releases", method: "GET", path: "/api/0/organizations/{organization_slug}/releases/", hasBody: false, securityRequirements: [SecurityRequirement(type: "auth_token", scopes: ["project:releases"])]) public final class Request: APIRequest<Response> { public struct Options { /** The slug of the organization. */ public var organizationSlug: String /** This parameter can be used to create a "starts with" filter for the version. */ public var query: String? public init(organizationSlug: String, query: String? = nil) { self.organizationSlug = organizationSlug self.query = query } } public var options: Options public init(options: Options) { self.options = options super.init(service: ListAnOrganizationsReleases.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(organizationSlug: String, query: String? = nil) { let options = Options(organizationSlug: organizationSlug, query: query) self.init(options: options) } override public var path: String { super.path.replacingOccurrences(of: "{" + "organization_slug" + "}", with: "\(self.options.organizationSlug)") } override public var queryParameters: [String: Any] { var params: [String: Any] = [:] if let query = options.query { params["query"] = query } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { /** Return a list of releases for a given organization. */ public struct Status200: Model { public var authors: [[String: AnyCodable]] public var commitCount: Int public var data: [String: AnyCodable] public var dateCreated: DateTime public var dateReleased: DateTime? public var deployCount: Int public var firstEvent: DateTime? public var lastCommit: [String: AnyCodable]? public var lastDeploy: [String: AnyCodable]? public var lastEvent: DateTime? public var newGroups: Int public var owner: [String: AnyCodable]? public var projects: [Projects] public var ref: String? public var shortVersion: String public var version: String public var url: String? /** Return a list of releases for a given organization. */ public struct Projects: Model { public var name: String? public var slug: String? public init(name: String? = nil, slug: String? = nil) { self.name = name self.slug = slug } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) name = try container.decodeIfPresent("name") slug = try container.decodeIfPresent("slug") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(name, forKey: "name") try container.encodeIfPresent(slug, forKey: "slug") } } public init(authors: [[String: AnyCodable]], commitCount: Int, data: [String: AnyCodable], dateCreated: DateTime, dateReleased: DateTime?, deployCount: Int, firstEvent: DateTime?, lastCommit: [String: AnyCodable]?, lastDeploy: [String: AnyCodable]?, lastEvent: DateTime?, newGroups: Int, owner: [String: AnyCodable]?, projects: [Projects], ref: String?, shortVersion: String, version: String, url: String?) { self.authors = authors self.commitCount = commitCount self.data = data self.dateCreated = dateCreated self.dateReleased = dateReleased self.deployCount = deployCount self.firstEvent = firstEvent self.lastCommit = lastCommit self.lastDeploy = lastDeploy self.lastEvent = lastEvent self.newGroups = newGroups self.owner = owner self.projects = projects self.ref = ref self.shortVersion = shortVersion self.version = version self.url = url } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) authors = try container.decodeAny("authors") commitCount = try container.decode("commitCount") data = try container.decodeAny("data") dateCreated = try container.decode("dateCreated") dateReleased = try container.decodeIfPresent("dateReleased") deployCount = try container.decode("deployCount") firstEvent = try container.decodeIfPresent("firstEvent") lastCommit = try container.decodeAnyIfPresent("lastCommit") lastDeploy = try container.decodeAnyIfPresent("lastDeploy") lastEvent = try container.decodeIfPresent("lastEvent") newGroups = try container.decode("newGroups") owner = try container.decodeAnyIfPresent("owner") projects = try container.decodeArray("projects") ref = try container.decodeIfPresent("ref") shortVersion = try container.decode("shortVersion") version = try container.decode("version") url = try container.decodeIfPresent("url") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeAny(authors, forKey: "authors") try container.encode(commitCount, forKey: "commitCount") try container.encodeAny(data, forKey: "data") try container.encode(dateCreated, forKey: "dateCreated") try container.encodeIfPresent(dateReleased, forKey: "dateReleased") try container.encode(deployCount, forKey: "deployCount") try container.encodeIfPresent(firstEvent, forKey: "firstEvent") try container.encodeAnyIfPresent(lastCommit, forKey: "lastCommit") try container.encodeAnyIfPresent(lastDeploy, forKey: "lastDeploy") try container.encodeIfPresent(lastEvent, forKey: "lastEvent") try container.encode(newGroups, forKey: "newGroups") try container.encodeAnyIfPresent(owner, forKey: "owner") try container.encode(projects, forKey: "projects") try container.encodeIfPresent(ref, forKey: "ref") try container.encode(shortVersion, forKey: "shortVersion") try container.encode(version, forKey: "version") try container.encodeIfPresent(url, forKey: "url") } } public typealias SuccessType = [Status200] /** Success */ case status200([Status200]) /** Permission Denied */ case status401 /** Forbidden */ case status403 /** Not Found */ case status404 public var success: [Status200]? { switch self { case let .status200(response): return response default: return nil } } public var response: Any { switch self { case let .status200(response): return response default: return () } } public var statusCode: Int { switch self { case .status200: return 200 case .status401: return 401 case .status403: return 403 case .status404: return 404 } } public var successful: Bool { switch self { case .status200: return true case .status401: return false case .status403: return false case .status404: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode([Status200].self, from: data)) case 401: self = .status401 case 403: self = .status403 case 404: self = .status404 default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
35.653226
416
0.629043
691bb12fcaf5c82678be1723acd81fc853ee8dad
234
// // UINib+Loading.swift // FBSnapshotTestCase // // Created by abuzeid ibrahim on 6/1/18. // import UIKit extension UINib { class func from(name: String) -> UINib { return UINib(nibName: name, bundle: nil) } }
15.6
49
0.632479
e6dd4b9edbd2850206aaf05b8d038f5e80758148
3,118
import UIKit protocol SearchViewControllerDelegate { func didSelectQuote(_ quote:IEXQuote) } class SearchTableViewController: TableViewController { //MARK: - Header Variables //var results = [IEXQuote]() var delegate: SearchViewControllerDelegate? let searchBar = UISearchBar() var symbols = [Symbol]() var filteredSymbols = [Symbol]() //MARK: - Override Methods override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "SymbolTableViewCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "ResultCell") tableView.separatorColor = UITheme.main.secondaryBackgroundColor searchBar.delegate = self searchBar.showsCancelButton = true searchBar.placeholder = "Search" searchBar.showsCancelButton = true navigationItem.prompt = "Type a company name or stock symbol." navigationItem.titleView = searchBar StocksAPI.shared.getSymbols { symbols, error in if let syms = symbols { self.symbols = syms } if let e = error { print(e) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) searchBar.becomeFirstResponder() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredSymbols.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as! SymbolTableViewCell let symbol = filteredSymbols[indexPath.row] cell.nameLabel.text = symbol.name cell.symbolLabel.text = symbol.symbol cell.marketLabel.text = "" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let symbol = filteredSymbols[indexPath.row] StocksAPI.shared.getQuote(for: symbol.symbol){ data, error in guard let res = data else { return } DispatchQueue.main.async { self.delegate?.didSelectQuote(res) } } searchBar.resignFirstResponder() dismiss(animated: true, completion: nil) } } //MARK: - UISearchBarDelegate extension SearchTableViewController: UISearchBarDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() dismiss(animated: true, completion: nil) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filteredSymbols = symbols.filter({ $0.name.contains(searchText) || $0.symbol.contains(searchText.uppercased()) }) tableView.reloadData() } }
30.271845
121
0.638871
f7018ff0effba25078a2cefc8e3f6fc16424afb1
15,590
// // InputTextFieldViewSpec.swift // ShopAppTests // // Created by Radyslav Krechet on 3/20/18. // Copyright © 2018 RubyGarage. All rights reserved. // import Nimble import Quick @testable import ShopApp class InputTextFieldViewSpec: QuickSpec { override func spec() { var view: InputTextFieldView! var textField: UITextField! var errorMessageLabel: UILabel! var showPasswordButton: UIButton! var underlineView: UIView! var underlineViewHeightConstraint: NSLayoutConstraint! beforeEach { view = InputTextFieldView() textField = self.findView(withAccessibilityLabel: "textField", in: view) as? UITextField errorMessageLabel = self.findView(withAccessibilityLabel: "errorMessage", in: view) as? UILabel showPasswordButton = self.findView(withAccessibilityLabel: "showPassword", in: view) as? UIButton underlineView = self.findView(withAccessibilityLabel: "underline", in: view) underlineViewHeightConstraint = underlineView.constraints.filter({ $0.accessibilityLabel == "underlineHeight" }).first } describe("when view initialized") { it("should have correct delegate of text field") { expect(textField.delegate) === view } it("should have correct background color") { expect(view.backgroundColor) == .clear } it("should have correct text color of error message label") { expect(errorMessageLabel.textColor) == UIColor(displayP3Red: 0.89, green: 0.31, blue: 0.31, alpha: 1) } it("should have correct alpha of underline view") { expect(underlineView.alpha) ≈ 0.2 } it("should have correct height of underline view") { expect(underlineViewHeightConstraint.constant) == 1 } it("should have correct background color of underline view") { expect(underlineView.backgroundColor) == .black } it("should have hidden error message label") { expect(errorMessageLabel.isHidden) == true } } describe("when keyboard type value changed") { context("and it's email") { beforeEach { view.keyboardType = InputTextFieldViewKeybordType.email.rawValue } it("needs to setup keyboard type of text field") { expect(textField.keyboardType.rawValue) == UIKeyboardType.emailAddress.rawValue } it("needs to setup autocapitalization type of text field") { expect(textField.autocapitalizationType.rawValue) == UITextAutocapitalizationType.none.rawValue } it("needs to setup secure text entry of text field") { expect(textField.isSecureTextEntry) == false } it("needs to show/hide show password button") { expect(showPasswordButton.isHidden) == true } } context("and it's cvv") { beforeEach { view.keyboardType = InputTextFieldViewKeybordType.cvv.rawValue } it("needs to setup keyboard type of text field") { expect(textField.keyboardType.rawValue) == UIKeyboardType.numberPad.rawValue } it("needs to setup autocapitalization type of text field") { expect(textField.autocapitalizationType.rawValue) == UITextAutocapitalizationType.sentences.rawValue } it("needs to setup secure text entry of text field") { expect(textField.isSecureTextEntry) == true } it("needs to show/hide show password button") { expect(showPasswordButton.isHidden) == true } } context("and it's phone") { beforeEach { view.keyboardType = InputTextFieldViewKeybordType.phone.rawValue } it("needs to setup keyboard type of text field") { expect(textField.keyboardType.rawValue) == UIKeyboardType.phonePad.rawValue } it("needs to setup autocapitalization type of text field") { expect(textField.autocapitalizationType.rawValue) == UITextAutocapitalizationType.sentences.rawValue } it("needs to setup secure text entry of text field") { expect(textField.isSecureTextEntry) == false } it("needs to show/hide show password button") { expect(showPasswordButton.isHidden) == true } } context("and it's name") { beforeEach { view.keyboardType = InputTextFieldViewKeybordType.name.rawValue } it("needs to setup keyboard type of text field") { expect(textField.keyboardType.rawValue) == UIKeyboardType.default.rawValue } it("needs to setup autocapitalization type of text field") { expect(textField.autocapitalizationType.rawValue) == UITextAutocapitalizationType.words.rawValue } it("needs to setup secure text entry of text field") { expect(textField.isSecureTextEntry) == false } it("needs to show/hide show password button") { expect(showPasswordButton.isHidden) == true } } } describe("when hide show password button value changed") { beforeEach { view.keyboardType = InputTextFieldViewKeybordType.password.rawValue } context("and it's true") { it("needs to setup security") { view.hideShowPasswordButton = true expect(textField.isSecureTextEntry) == true expect(showPasswordButton.isHidden) == true } } context("and it's false") { it("needs to setup security") { view.hideShowPasswordButton = false expect(textField.isSecureTextEntry) == true expect(showPasswordButton.isHidden) == false } } } describe("when text of view changed") { context("and it's empty") { it("needs to change font size and text color of placeholder label") { view.text = nil expect(view.placeholderLabel.font) == .systemFont(ofSize: 12) expect(view.placeholderLabel.textColor) == .black } } context("and it's not empty") { it("needs to change font size and text color of placeholder label") { view.text = "text" expect(view.placeholderLabel.font) == UIFont.systemFont(ofSize: 11) expect(view.placeholderLabel.textColor) == UIColor.black.withAlphaComponent(0.5) } } } describe("when state of view changed") { beforeEach { view.state = .highlighted } it("needs to setup alpha of underline view") { expect(underlineView.alpha) == 1 } it("needs to setup height of underline view") { expect(underlineViewHeightConstraint.constant) == 2 } it("needs to setup background color of underline view") { expect(underlineView.backgroundColor) == .black } it("needs to hide error message label") { expect(errorMessageLabel.isHidden) == true } } describe("when error message changed") { beforeEach { view.errorMessage = "error" } it("needs to setup state of view") { expect(view.state.rawValue) == InputTextFieldViewState.error.rawValue } it("needs to setup text of error message label") { expect(errorMessageLabel.text) == view.errorMessage } it("needs to setup alpha of underline view") { expect(underlineView.alpha) == 1 } it("needs to setup height of underline view") { expect(underlineViewHeightConstraint.constant) == 2 } it("needs to setup background color of underline view") { expect(underlineView.backgroundColor) == UIColor(displayP3Red: 0.89, green: 0.31, blue: 0.31, alpha: 1) } it("needs to show error message label") { expect(errorMessageLabel.isHidden) == false } } describe("when text field editing began") { beforeEach { textField.sendActions(for: .editingDidBegin) } it("needs to setup correct state") { expect(view.state.rawValue) == InputTextFieldViewState.highlighted.rawValue } it("needs to change font size and text color of placeholder label") { expect(view.placeholderLabel.font) == UIFont.systemFont(ofSize: 11) expect(view.placeholderLabel.textColor) == UIColor.black.withAlphaComponent(0.5) } } describe("when text field editing changed") { let delegateMock = InputTextFieldViewDelegateMock() beforeEach { view.delegate = delegateMock textField.sendActions(for: .editingDidBegin) view.keyboardType = InputTextFieldViewKeybordType.cardNumber.rawValue view.state = .normal textField.text = "12345678" textField.sendActions(for: .editingChanged) } it("needs to setup correct state") { expect(view.state.rawValue) == InputTextFieldViewState.highlighted.rawValue } it("needs to setup text of text field in needed") { expect(textField.text) == "1234 5678" } it("needs to notify delegate") { expect(delegateMock.isViewDidUpdate) == true expect(delegateMock.view) === view expect(delegateMock.text) == "1234 5678" } } describe("when text field editing ended") { let delegateMock = InputTextFieldViewDelegateMock() beforeEach { view.delegate = delegateMock textField.sendActions(for: .editingDidBegin) textField.text = "" textField.sendActions(for: .editingDidEnd) } it("needs to setup correct state") { expect(view.state.rawValue) == InputTextFieldViewState.normal.rawValue } it("needs to notify delegate") { expect(delegateMock.isViewDidEndUpdate) == true expect(delegateMock.view) === view expect(delegateMock.text) == "" } it("needs to change font size and text color of placeholder label") { expect(view.placeholderLabel.font) == .systemFont(ofSize: 12) expect(view.placeholderLabel.textColor) == .black } } describe("when show password button pressed") { beforeEach { showPasswordButton.sendActions(for: .touchUpInside) } it("needs to select button") { expect(showPasswordButton.isSelected) == true } it("needs to disable secure text entry") { expect(textField.isSecureTextEntry) == false } } describe("when text field should change characters") { context("if keyboard type is not cvv and not card number") { it("needs to add character in any case") { view.keyboardType = InputTextFieldViewKeybordType.phone.rawValue textField.sendActions(for: .editingDidBegin) textField.text = "1" let range = NSRange(location: 1, length: 0) let isShouldChangeCharacters = view.textField(textField, shouldChangeCharactersIn: range, replacementString: "2") expect(isShouldChangeCharacters) == true } } context("if keyboard type is card number") { it("needs to check length of text") { view.keyboardType = InputTextFieldViewKeybordType.cardNumber.rawValue textField.sendActions(for: .editingDidBegin) textField.text = "1234 5678" let range = NSRange(location: 9, length: 0) let isShouldChangeCharacters = view.textField(textField, shouldChangeCharactersIn: range, replacementString: "9") expect(isShouldChangeCharacters) == true } } context("if keyboard type is cvv") { it("needs to check length of text") { view.keyboardType = InputTextFieldViewKeybordType.cvv.rawValue textField.sendActions(for: .editingDidBegin) textField.text = "12" let range = NSRange(location: 2, length: 0) let isShouldChangeCharacters = view.textField(textField, shouldChangeCharactersIn: range, replacementString: "3") expect(isShouldChangeCharacters) == true } } } describe("when user press done button on keyboard when text field editing") { it("needs to end editing of text field") { textField.sendActions(for: .editingDidBegin) let isShouldReturn = view.textFieldShouldReturn(textField) expect(textField.isEditing) == false expect(isShouldReturn) == true } } } }
40.180412
133
0.510327
79018dd8a0b15f9d274cd2e23b46fb61f01b150f
9,551
import KsApi import Prelude import ReactiveSwift import UserNotifications /** Determines if the personalization data in the project implies that the current user is backing the reward passed in. Because of the many ways in which we can get this data we have multiple ways of determining this. - parameter reward: A reward. - parameter project: A project. - returns: A boolean. */ internal func userIsBacking(reward: Reward, inProject project: Project) -> Bool { guard let backing = project.personalization.backing else { return false } return backing.reward?.id == reward.id || backing.rewardId == reward.id || (backing.reward == nil && backing.rewardId == nil && reward == Reward.noReward) } /** Determines if the current user is the creator for a given project. - parameter project: A project. - returns: A boolean. */ public func currentUserIsCreator(of project: Project) -> Bool { guard let user = AppEnvironment.current.currentUser else { return false } return project.creator.id == user.id } /** Returns a reward from a backing in a given project - parameter backing: A backing - parameter project: A project - returns: A reward */ internal func reward(from backing: Backing, inProject project: Project) -> Reward { let noRewardFromProject = project.rewards.filter { $0.id == Reward.noReward.id }.first return backing.reward ?? project.rewards.filter { $0.id == backing.rewardId }.first ?? noRewardFromProject ?? Reward.noReward } /** Computes the pledge context (i.e. new pledge, managing reward, changing reward) from a project and reward. - parameter project: A project. - parameter reward: A reward. - returns: A pledge context. */ internal func pledgeContext(forProject project: Project, reward: Reward) -> Koala.PledgeContext { if project.personalization.isBacking == .some(true) { return userIsBacking(reward: reward, inProject: project) ? .manageReward : .changeReward } return .newPledge } /** Computes the minimum and maximum amounts that can be pledge to a reward. For the "no reward" reward, this looks up values in the table of launched countries, since the values depend on the currency. - parameter project: A project. - parameter reward: A reward. - returns: A pair of the minimum and maximum amount that can be pledged to a reward. */ internal func minAndMaxPledgeAmount(forProject project: Project, reward: Reward?) -> (min: Double, max: Double) { // The country on the project cannot be trusted to have the min/max values, so first try looking // up the country in our launched countries array that we get back from the server config. let country = AppEnvironment.current.launchedCountries.countries .filter { $0 == project.country } .first .coalesceWith(project.country) switch reward { case .none, .some(Reward.noReward): return (Double(country.minPledge ?? 1), Double(country.maxPledge ?? 10_000)) case let .some(reward): return (reward.minimum, Double(country.maxPledge ?? 10_000)) } } /** Computes the minimum amount needed to pledge to a reward. For the "no reward" reward, this looks up values in the table of launched countries, since the values depend on the currency. - parameter project: A project. - parameter reward: A reward. - returns: The minimum amount needed to pledge to the reward. */ internal func minPledgeAmount(forProject project: Project, reward: Reward?) -> Double { return minAndMaxPledgeAmount(forProject: project, reward: reward).min } /** Returns the full currency symbol for a country. Special logic is added around prefixing currency symbols with country/currency codes based on a variety of factors. - parameter country: The country. - parameter omitCurrencyCode: Safe to omit the US currencyCode - parameter env: Current Environment. - returns: The currency symbol that can be used for currency display. */ public func currencySymbol( forCountry country: Project.Country, omitCurrencyCode: Bool = true, env: Environment = AppEnvironment.current ) -> String { guard env.launchedCountries.currencyNeedsCode(country.currencySymbol) else { // Currencies that dont have ambigious currencies can just use their symbol. return country.currencySymbol } if country == .us && env.countryCode == Project.Country.us.countryCode && omitCurrencyCode { // US people looking at US projects just get the currency symbol return country.currencySymbol } else if country == .sg { // Singapore projects get a special currency prefix return "\(String.nbsp)S\(country.currencySymbol)\(String.nbsp)" } else if country.currencySymbol == "kr" || country.currencySymbol == "Fr" { // Kroner projects use the currency code prefix return "\(String.nbsp)\(country.currencyCode)\(String.nbsp)" } else { // Everything else uses the country code prefix. return "\(String.nbsp)\(country.countryCode)\(country.currencySymbol)\(String.nbsp)" } } /// Returns a signal producer that emits, every second, the number of days/hours/minutes/seconds until /// a date is reached, at which point it completes. /// /// - parameter untilDate: The date to countdown to. /// /// - returns: A signal producer. public func countdownProducer(to date: Date) -> SignalProducer<(day: String, hour: String, minute: String, second: String), Never> { func formattedComponents(dateComponents: DateComponents) -> (day: String, hour: String, minute: String, second: String) { return ( day: String(format: "%02d", max(0, dateComponents.day ?? 0)), hour: String(format: "%02d", max(0, dateComponents.hour ?? 0)), minute: String(format: "%02d", max(0, dateComponents.minute ?? 0)), second: String(format: "%02d", max(0, dateComponents.second ?? 0)) ) } let now = AppEnvironment.current.scheduler.currentDate let timeUntilNextRoundSecond = ceil(now.timeIntervalSince1970) - now.timeIntervalSince1970 // A timer that emits every second, but with a small delay so that it emits on a roundeded second. let everySecond = SignalProducer<(), Never>(value: ()) .ksr_delay(.milliseconds(Int(timeUntilNextRoundSecond * 1_000)), on: AppEnvironment.current.scheduler) .flatMap { SignalProducer.timer(interval: .seconds(1), on: AppEnvironment.current.scheduler) } return SignalProducer.merge( SignalProducer<Date, Never>(value: now), everySecond ) .map { currentDate in AppEnvironment.current.calendar.dateComponents( [.day, .hour, .minute, .second], from: currentDate, to: Date(timeIntervalSince1970: ceil(date.timeIntervalSince1970)) ) } .take(while: { ($0.second ?? 0) >= 0 }) .map(formattedComponents(dateComponents:)) } internal func is1PasswordButtonHidden(_ isHidden: Bool) -> Bool { guard AppEnvironment.current.is1PasswordSupported() else { return true } return isHidden } public func ksr_is1PasswordSupported() -> Bool { if #available(iOS 12.0, *) { return false } return true } public func updatedUserWithClearedActivityCountProducer() -> SignalProducer<User, Never> { return AppEnvironment.current.apiService.clearUserUnseenActivity(input: .init()) .filter { _ in AppEnvironment.current.currentUser != nil } .map { $0.activityIndicatorCount } .map { count in AppEnvironment.current.currentUser ?|> User.lens.unseenActivityCount .~ count } .skipNil() .demoteErrors() } public func defaultShippingRule(fromShippingRules shippingRules: [ShippingRule]) -> ShippingRule? { let shippingRuleFromCurrentLocation = shippingRules .filter { shippingRule in shippingRule.location.country == AppEnvironment.current.config?.countryCode } .first if let shippingRuleFromCurrentLocation = shippingRuleFromCurrentLocation { return shippingRuleFromCurrentLocation } let shippingRuleInUSA = shippingRules .filter { shippingRule in shippingRule.location.country == "US" } .first return shippingRuleInUSA ?? shippingRules.first } public func formattedAmountForRewardOrBacking( project: Project, rewardOrBacking: Either<Reward, Backing> ) -> String { switch rewardOrBacking { case let .left(reward): let min = minPledgeAmount(forProject: project, reward: reward) return Format.currency( min, country: project.country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) case let .right(backing): return Format.formattedCurrency( backing.amount, country: project.country, omitCurrencyCode: project.stats.omitUSCurrencyCode ) } } internal func classNameWithoutModule(_ class: AnyClass) -> String { return `class` .description() .components(separatedBy: ".") .dropFirst() .joined(separator: ".") } typealias SanitizedPledgeParams = (pledgeTotal: String, rewardId: String, locationId: String?) internal func sanitizedPledgeParameters( from reward: Reward, pledgeAmount: Double, shippingRule: ShippingRule? ) -> SanitizedPledgeParams { let pledgeAmountDecimal = Decimal(pledgeAmount) var shippingAmountDecimal: Decimal = Decimal() var shippingLocationId: String? if let shippingRule = shippingRule { shippingAmountDecimal = Decimal(shippingRule.cost) shippingLocationId = String(shippingRule.location.id) } let pledgeTotal = NSDecimalNumber(decimal: pledgeAmountDecimal + shippingAmountDecimal) let formattedPledgeTotal = Format.decimalCurrency(for: pledgeTotal.doubleValue) let rewardId = reward.graphID return (formattedPledgeTotal, rewardId, shippingLocationId) }
34.857664
107
0.732593
6af699de134a8d5542b8898a99db9aab8dbb9ea1
964
// // ADLaunchViewController.swift // AppDuplicator2 // // Created by iMokhles on 21/07/2017. // Copyright © 2017 iMokhles. All rights reserved. // import Foundation import UIKit import Colours class ADLaunchViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupTheme() } func setupTheme() -> Void { // view.backgroundColor = ADTheme.getMainBgColor() } @IBAction func signupTapped(_ sender: Any) { let signupVC = ADHelper.getViewControllerWithId(name: "SignupVC") as! ADSignupViewController self.navigationController?.pushViewController(signupVC, animated: true) } @IBAction func loginTapped(_ sender: Any) { let loginVC = ADHelper.getViewControllerWithId(name: "LoginVC") as! ADLoginViewController self.navigationController?.pushViewController(loginVC, animated: true) } }
24.717949
100
0.662863
feebf8f7f59c15f96726bd403a409e9e610b2a74
4,528
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// An optional type that allows implicit member access (via compiler /// magic). /// /// The compiler has special knowledge of the existence of /// `ImplicitlyUnwrappedOptional<Wrapped>`, but always interacts with it using /// the library intrinsics below. public enum ImplicitlyUnwrappedOptional<Wrapped> : NilLiteralConvertible { case None case Some(Wrapped) @available(*, unavailable, renamed="Wrapped") public typealias T = Wrapped /// Construct a `nil` instance. public init() { self = .None } /// Construct a non-`nil` instance that stores `some`. public init(_ some: Wrapped) { self = .Some(some) } /// Construct an instance from an explicitly unwrapped optional /// (`Wrapped?`). public init(_ v: Wrapped?) { switch v { case .Some(let some): self = .Some(some) case .None: self = .None } } /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { self = .None } /// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`. @warn_unused_result public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> ImplicitlyUnwrappedOptional<U> { switch self { case .Some(let y): return .Some(try f(y)) case .None: return .None } } /// Returns `nil` if `self` is `nil`, `f(self!)` otherwise. @warn_unused_result public func flatMap<U>( @noescape f: (Wrapped) throws -> ImplicitlyUnwrappedOptional<U> ) rethrows -> ImplicitlyUnwrappedOptional<U> { switch self { case .Some(let y): return try f(y) case .None: return .None } } } extension ImplicitlyUnwrappedOptional : CustomStringConvertible { /// A textual representation of `self`. public var description: String { switch self { case .Some(let value): return String(value) case .None: return "nil" } } } /// Directly conform to CustomDebugStringConvertible to support /// optional printing. Implementation of that feature relies on /// _isOptional thus cannot distinguish ImplicitlyUnwrappedOptional /// from Optional. When conditional conformance is available, this /// outright conformance can be removed. extension ImplicitlyUnwrappedOptional : CustomDebugStringConvertible { public var debugDescription: String { return description } } @_transparent @warn_unused_result public // COMPILER_INTRINSIC func _getImplicitlyUnwrappedOptionalValue<Wrapped>(v: Wrapped!) -> Wrapped { switch v { case .Some(let x): return x case .None: _preconditionFailure( "unexpectedly found nil while unwrapping an Optional value") } } @_transparent @warn_unused_result public // COMPILER_INTRINSIC func _injectValueIntoImplicitlyUnwrappedOptional<Wrapped>( v: Wrapped ) -> Wrapped! { return .Some(v) } @_transparent @warn_unused_result public // COMPILER_INTRINSIC func _injectNothingIntoImplicitlyUnwrappedOptional<Wrapped>() -> Wrapped! { return .None } #if _runtime(_ObjC) extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return Swift._getBridgedObjectiveCType(Wrapped.self)! } public func _bridgeToObjectiveC() -> AnyObject { switch self { case .None: _preconditionFailure("attempt to bridge an implicitly unwrapped optional containing nil") case .Some(let x): return Swift._bridgeToObjectiveC(x)! } } public static func _forceBridgeFromObjectiveC( x: AnyObject, inout result: Wrapped!? ) { result = Swift._forceBridgeFromObjectiveC(x, Wrapped.self) } public static func _conditionallyBridgeFromObjectiveC( x: AnyObject, inout result: Wrapped!? ) -> Bool { let bridged: Wrapped? = Swift._conditionallyBridgeFromObjectiveC(x, Wrapped.self) if let value = bridged { result = value } return false } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Wrapped.self) } } #endif
26.952381
95
0.675574
3ab084ffacf95fe04ebac245006f99467141e77b
367
// // AppUtils+UIRotationGestureRecognizer.swift // AppUtils // // Created by Quan Li on 2019/9/24. // Copyright © 2019 williamoneilchina. All rights reserved. // import UIKit public extension AppUtils where Base:UIRotationGestureRecognizer{ func rotation(_ rotation: CGFloat) -> AppUtils { self.base.rotation = rotation return self } }
21.588235
65
0.705722
d984b4a7f8005bd3fcb0a747d0739c0e5f987730
13,570
// // CalendarView.swift // FSCalendarBootstrap // // Created by Daniel on 2017-09-07. // Copyright © 2017 danielbogomazov. All rights reserved. // import UIKit import FSCalendar // TODO : Get rid of the CalendarTextColor Protocol things and add { get, set } to the color vars in the class itself @objc protocol CalendarDelegate { @objc optional func didSelect(date: Date) @objc optional func maximumDate() -> Date @objc optional func minimumDate() -> Date } class CalendarView: UIView, FSCalendarDataSource { /* Views */ var view: UIView! fileprivate var topPadding: UIView! fileprivate var calendar: FSCalendar! fileprivate var yearTextField: UITextField! /* FSCalendar Variables */ var headerDateFormat: String = "MMMM" { didSet { self.calendar.appearance.headerDateFormat = headerDateFormat } } var scrollDirection: FSCalendarScrollDirection = .horizontal { didSet { self.calendar.scrollDirection = scrollDirection } } var allowsMultipleSelection: Bool = false { didSet { self.calendar.allowsMultipleSelection = allowsMultipleSelection } } var firstWeekday: UInt = 1 { didSet { self.calendar.firstWeekday = firstWeekday } } var weekdayTextColor: UIColor = UIColor.black { didSet { self.calendar.appearance.weekdayTextColor = weekdayTextColor } } var headerTitleColor: UIColor = UIColor.white { didSet { self.calendar.appearance.headerTitleColor = headerTitleColor } } var eventDefaultColor: UIColor = UIColor.clear { didSet { self.calendar.appearance.eventDefaultColor = eventDefaultColor } } var eventSelectionColor: UIColor = UIColor.clear { didSet { self.calendar.appearance.eventSelectionColor = eventSelectionColor } } var selectionColor: UIColor = UIColor(red: 220/255, green: 95/255, blue: 70/255, alpha: 1.0) { didSet { self.calendar.appearance.selectionColor = selectionColor } } var todayColor: UIColor = UIColor.white { didSet { self.calendar.appearance.todayColor = todayColor } } var todaySelectionColor: UIColor = UIColor(red: 220/255, green: 95/255, blue: 70/255, alpha: 1.0) { didSet { self.calendar.appearance.todaySelectionColor = todaySelectionColor } } var yearTextColor: UIColor = UIColor.white.withAlphaComponent(0.5) { didSet { self.yearTextField.textColor = yearTextColor } } var titleTodayColor: UIColor = UIColor(red: 220/255, green: 95/255, blue: 70/255, alpha: 1.0) { didSet { self.calendar.appearance.titleTodayColor = titleTodayColor } } var borderRadius: CGFloat = 1 { didSet { self.calendar.appearance.borderRadius = borderRadius } } /* Additional Calendar Variables */ var calendarColor: UIColor = UIColor.white { didSet { self.calendar.backgroundColor = calendarColor } } var headerColor: UIColor = UIColor(red: 220/255, green: 95/255, blue: 70/255, alpha: 1.0) { didSet { self.calendar.calendarHeaderView.backgroundColor = headerColor self.view.backgroundColor = headerColor } } /* Functionalities/Parameters */ fileprivate var minimumDate: Date! fileprivate var maximumDate: Date! fileprivate var dateFormatter: DateFormatter! /* Misc. */ var delegate: CalendarDelegate? { didSet { calendar.reloadData() selectDefaultDate() } } /* Constants */ fileprivate let kMaxYearCharactersCount: Int = 4 init(frame: CGRect, minimumDate: Date!, maximumDate: Date!) { super.init(frame: frame) /* Initialize Variables */ self.minimumDate = minimumDate self.maximumDate = maximumDate self.dateFormatter = DateFormatter() /* Build Calendar View */ let viewWidth = frame.width let viewHeight = frame.height let topPaddingHeight: CGFloat = 15.0 let yearLabelHeight: CGFloat = 20.0 let calendarHeight = viewHeight - topPaddingHeight self.view = UIView(frame: frame) self.calendar = FSCalendar(frame: CGRect(x: 0, y: topPaddingHeight, width: viewWidth, height: calendarHeight)) self.calendar.delegate = self self.calendar.dataSource = self self.calendar.appearance.headerMinimumDissolvedAlpha = 0 self.calendar.clipsToBounds = true selectDefaultDate() self.view.addSubview(self.calendar) self.topPadding = UIView(frame: CGRect(x: 0, y: 0, width: viewWidth, height: topPaddingHeight)) self.view.addSubview(self.topPadding) self.dateFormatter.dateFormat = "yyyy" self.yearTextField = UITextField(frame: CGRect(x: viewWidth / 3, y: topPaddingHeight / 2, width: viewWidth / 3, height: yearLabelHeight)) self.yearTextField.textAlignment = .center self.yearTextField.text = self.dateFormatter.string(from: Date()) self.yearTextField.delegate = self self.view.addSubview(self.yearTextField) /* Change Initial Colors */ initializeAppearance() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* Textfield Delegate Functions */ func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField != self.yearTextField { return true } let newSubjectString = (textField.text! as NSString).replacingCharacters(in: range, with: string) let newCharacters = CharacterSet(charactersIn: newSubjectString as String) if !CharacterSet.decimalDigits.isSuperset(of: newCharacters) { /* New characters are not numeric characters */ return false } else if newSubjectString.count > 4 { /* Year field too long - should only be 4 characters */ return false } else if newSubjectString.count == self.kMaxYearCharactersCount { /* Checks if the year is valid */ textField.text = newSubjectString self.view.endEditing(true) return shouldDisplayYear() } else { return true } } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { if textField != self.yearTextField { return true } let _ = shouldDisplayYear() return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField != self.yearTextField { return true } self.view.endEditing(true) return true } ////////////////////////////// PRIVATE ////////////////////////////// /* Initializes all colors and formats */ fileprivate func initializeAppearance() { self.calendar.appearance.headerDateFormat = headerDateFormat self.calendar.scrollDirection = scrollDirection self.calendar.allowsMultipleSelection = allowsMultipleSelection self.calendar.firstWeekday = firstWeekday self.calendar.appearance.weekdayTextColor = weekdayTextColor self.calendar.appearance.headerTitleColor = headerTitleColor self.calendar.appearance.eventDefaultColor = eventDefaultColor self.calendar.appearance.eventSelectionColor = eventSelectionColor self.calendar.appearance.selectionColor = selectionColor self.calendar.appearance.todayColor = todayColor self.calendar.appearance.todaySelectionColor = todaySelectionColor self.yearTextField.textColor = yearTextColor self.calendar.appearance.titleTodayColor = titleTodayColor self.calendar.appearance.borderRadius = borderRadius self.calendar.backgroundColor = calendarColor self.calendar.calendarHeaderView.backgroundColor = headerColor self.view.backgroundColor = headerColor } /* Checks if yearTextField's text is a valid year * If it is, calendar will automatically transition to that year * If it is not, it will trigger the textField to shake and will not change the calendar's year */ fileprivate func shouldDisplayYear() -> Bool { self.dateFormatter.dateFormat = "yyyy" let pageYear = dateFormatter.string(from: self.calendar.currentPage) let maxYear = dateFormatter.string(from: self.maximumDate) let minYear = dateFormatter.string(from: self.minimumDate) self.dateFormatter.dateFormat = "MM" let pageMonth = dateFormatter.string(from: self.calendar.currentPage) /* Year must be 'kMaxYearCharactersCount' characters long */ if self.yearTextField.text?.count != self.kMaxYearCharactersCount { shakeTextFieldAnimation(textField: self.yearTextField) self.yearTextField.text = pageYear return false } self.dateFormatter.dateFormat = "yyyy-MM-dd" let newDate: Date! = self.dateFormatter.date(from: "\(self.yearTextField.text!)-\(pageMonth)-01") /* Check if the newDate is within maximumDate/minimumDate * Set the page accordingly * If the newDate is not whithing the maximumDate/minimumDate, shake the textField and return false */ if newDate <= self.maximumDate && newDate >= self.minimumDate { self.calendar.setCurrentPage(newDate, animated: true) } else if newDate > self.maximumDate && self.yearTextField.text == maxYear { self.calendar.setCurrentPage(self.maximumDate, animated: true) } else if newDate < self.minimumDate && yearTextField.text == minYear { self.calendar.setCurrentPage(self.minimumDate, animated: true) } else { shakeTextFieldAnimation(textField: yearTextField) yearTextField.text = pageYear return false } return true } /* TextField Animation */ fileprivate func shakeTextFieldAnimation(textField: UITextField) { let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.07 animation.repeatCount = 4 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: textField.center.x - 10, y: textField.center.y)) animation.toValue = NSValue(cgPoint: CGPoint(x: textField.center.x + 10, y: textField.center.y)) textField.layer.add(animation, forKey: "position") } ////////////////////////////// PUBLIC ////////////////////////////// func selectDefaultDate() { let currentDate = Date() if currentDate > self.minimumDate && currentDate < self.maximumDate { self.calendar.select(currentDate) } else { self.calendar.select(self.maximumDate) } } func selectDate(date: Date) { calendar.select(date) } func selectedDate() -> Date { return self.calendar.selectedDate! } } extension CalendarView: UITextFieldDelegate { private func checkTextInputLimit(_ string: String, limit: Int, charSet: CharacterSet, allowAlpha: Bool) -> Bool { if !allowAlpha { if !CharacterSet.decimalDigits.isSuperset(of: charSet) { return false } } if string.count > limit { return false } return true } } extension CalendarView: FSCalendarDelegate { /* FSCalendar Delegate Functions */ func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { if let _ = delegate { delegate!.didSelect?(date: date) } } func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) { // This function is run multiple times when the calendar transitions (for every day of the month) // If you display Jan. 2017, the page will also display some dates from Dec. 2016 which can cause the logic to print "2016" instead of "2017" // depending on the last cell that this function calls // Because of this, we have to check for a date somewhere in the middle of the month to pull the page's year // We force the year to only change when this function hits the 20th day cell of the page to guarantee the correct year to be printed self.dateFormatter.dateFormat = "dd" if self.dateFormatter.string(from: date) == "20" { self.dateFormatter.dateFormat = "yyyy" self.yearTextField.text = dateFormatter.string(from: date) } } func maximumDate(for calendar: FSCalendar) -> Date { if let date = delegate?.maximumDate?() { self.maximumDate = date return date } return self.maximumDate } func minimumDate(for calendar: FSCalendar) -> Date { if let date = delegate?.minimumDate?() { self.minimumDate = date return date } return self.minimumDate } }
37.590028
149
0.634783
7951abd28b04b7452fe8186e115b7c93b43ec538
1,742
// ------------------------------------------------------------------------------------------------- // Copyright (C) 2016-2020 HERE Europe B.V. // // 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. // // SPDX-License-Identifier: Apache-2.0 // License-Filename: LICENSE // // ------------------------------------------------------------------------------------------------- internal class ColorConverter { static func convertFromInternal(_ internalColor: PseudoColor_internal) -> PseudoColor { let alpha = UInt64((internalColor.alpha * 255).rounded()) << 24 let red = UInt64((internalColor.red * 255).rounded()) << 16 let green = UInt64((internalColor.green * 255).rounded()) << 8 let blue = UInt64((internalColor.blue * 255).rounded()) return PseudoColor(alpha + red + green + blue) } static func convertToInternal(_ systemColor: PseudoColor) -> PseudoColor_internal { return PseudoColor_internal( red: Float((systemColor.value >> 16) & 0xFF) / 255.0, green: Float((systemColor.value >> 8) & 0xFF) / 255.0, blue: Float(systemColor.value & 0xFF) / 255.0, alpha: Float((systemColor.value >> 24) & 0xFF) / 255.0 ) } }
44.666667
100
0.592997
fe17514774af86efdb9837f595f6726bd653503a
2,118
// // AppDelegate.swift // Pomme's Adventure tvOS // // Created by Renaud JENNY on 12/03/2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the 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.043478
285
0.753069
dbd2c24d07b740afdb31b0d1dcd71f7ee01d726b
347
// // prefixPredicate.swift // KeyPathKit // // Created by Vincent on 31/03/2018. // Copyright © 2018 Vincent. All rights reserved. // import Foundation extension Sequence { public func prefix(while predicate: KeyPathSingleTypePredicate<Element>) -> [Self.Element] { return prefix(while: { predicate.evaluate(for: $0) }) } }
21.6875
96
0.685879
0982800430183de2e6d7aa8b56c2020c750f6082
5,834
// // HTTPRequestRetrier.swift // ApptentiveKit // // Created by Frank Schmitt on 2/8/21. // Copyright © 2021 Apptentive, Inc. All rights reserved. // import Foundation /// Used by payload sender in place of the class below for better testability. protocol HTTPRequestStarting { func start<T: Decodable>(_ endpoint: HTTPEndpoint, identifier: String, completion: @escaping (Result<T, Error>) -> Void) } /// Retries HTTP requests until they either succeed or permanently fail. class HTTPRequestRetrier: HTTPRequestStarting { /// The policy to use for retrying requests. private(set) var retryPolicy: HTTPRetryPolicy /// The HTTP client to use for requests. let client: HTTPClient /// The queue to use for calling completion handlers. let dispatchQueue: DispatchQueue /// The list of in-progress requests (either active, waiting for response, or waiting to retry). private var requests: [String: RequestWrapper] /// Creates a new request retrier. /// - Parameters: /// - retryPolicy: The policy to use for retrying requests. /// - client: The HTTP client to use for requests. /// - queue: The queue to use for calling completion handlers. internal init(retryPolicy: HTTPRetryPolicy, client: HTTPClient, queue: DispatchQueue) { self.retryPolicy = retryPolicy self.client = client self.dispatchQueue = queue self.requests = [String: RequestWrapper]() } /// Starts a new request with the given parameters. /// - Parameters: /// - endpoint: The HTTP endpoint of the request. /// - identifier: A string that identifies the request. /// - completion: A completion handler to call when the request either succeeds or fails permanently. func start<T: Decodable>(_ endpoint: HTTPEndpoint, identifier: String, completion: @escaping (Result<T, Error>) -> Void) { let wrapper = RequestWrapper(endpoint: endpoint) let request = self.client.request(endpoint) { (result: Result<T, Error>) in self.dispatchQueue.async { self.processResult(result, identifier: identifier, completion: completion) } } wrapper.request = request self.requests[identifier] = wrapper } /// Starts a new request with the given parameters if another request with the same identifier is not already in progress. /// /// This is useful for instances where the same request might be triggered multiple times but only one request is desirable. /// The completion handler for a duplicate request will not be called. /// - Parameters: /// - endpoint: The HTTP endpoint of the request. /// - identifier: A string that identifies the request. /// - completion: A completion handler to call when the request either succeeds or fails permanently. func startUnlessUnderway<T: Decodable>(_ endpoint: HTTPEndpoint, identifier: String, completion: @escaping (Result<T, Error>) -> Void) { if self.requests[identifier] != nil { ApptentiveLogger.network.info("A request with identifier \(identifier) is already underway. Skipping.") return } self.start(endpoint, identifier: identifier, completion: completion) } /// Processes the response created by the HTTP client to determine if the request should be retried. /// - Parameters: /// - result: The result of the HTTP client's request. /// - identifier: The identifier of the request that may be retried. /// - completion: The completion handler supplied by the original caller for this retrying request, to be called when the request succeeds or fails permanently. private func processResult<T: Decodable>(_ result: Result<T, Error>, identifier: String, completion: @escaping (Result<T, Error>) -> Void) { switch result { case .success: self.retryPolicy.resetRetryDelay() self.requests[identifier] = nil completion(result) case .failure(let error as HTTPClientError): if self.retryPolicy.shouldRetry(inCaseOf: error) { self.retryPolicy.incrementRetryDelay() let retryDelayMilliseconds = Int(self.retryPolicy.retryDelay) * 1000 ApptentiveLogger.network.info("Retriable error sending API request with identifier ”\(identifier)”: \(error.localizedDescription). Retrying in \(retryDelayMilliseconds) ms.") self.dispatchQueue.asyncAfter(deadline: .now() + .milliseconds(retryDelayMilliseconds)) { guard let wrapper = self.requests[identifier] else { ApptentiveLogger.network.warning("Request with identifier \(identifier) cancelled or missing when attempting to retry.") return } wrapper.request = self.client.request( wrapper.endpoint, completion: { (result: Result<T, Error>) in self.processResult(result, identifier: identifier, completion: completion) }) } } else { ApptentiveLogger.network.info("Permanent failure when sending request with identifier “\(identifier)”: \(error.localizedDescription).") fallthrough } default: completion(result) self.requests[identifier] = nil } } /// Describes a request's endpoint and in-flight HTTP request. class RequestWrapper { let endpoint: HTTPEndpoint var request: HTTPCancellable? internal init(endpoint: HTTPEndpoint, request: HTTPCancellable? = nil) { self.endpoint = endpoint self.request = request } } }
44.19697
190
0.652383
ab98e6e36548541a2e571437ab1d684065c7f7f6
1,854
// // AuthViewController.swift // VIT FREE SLOTS // // Created by Devang Patel on 09/03/19. // Copyright © 2019 Devang Patel. All rights reserved. import UIKit import Firebase class AuthViewController: UIViewController { @IBOutlet weak var Email: UITextField! @IBOutlet weak var Pass: UITextField! @IBOutlet weak var load: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() self.load.isHidden = true } @IBAction func Sign(_ sender: UIButton) { self.load.isHidden = false load.startAnimating() let email = Email.text let pass = Pass.text Auth.auth().signIn(withEmail: email!, password: pass!, completion: { user, error in if let firebaseError = error { self.load.isHidden = true print(firebaseError.localizedDescription) let alert = UIAlertController(title: "Authentication failed", message: "Invalid password please try again", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true) return } let homeView = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController self.present(homeView, animated: true, completion: nil) print("Success!") }) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
31.965517
147
0.623517
8a8fbf6b3333a93aacecd4edd3f4a610116c5ba2
3,379
// // KeyboardObserver.swift // Gears // // Created by Candid Cod3r on 5/9/19. // Copyright © 2019 Sparkles. All rights reserved. // /** Keyboard observer that listens on keyboard notifications and activates the observation block with or without animation. Typically this is intialized in a UIViewController and would call stopObserving on viewWillDisapper. */ open class KeyboardObserver { public static let defaultKeyboardHeight: CGFloat = 335 public typealias KeyboardNotificationObservation = (KeyboardNotification) -> Void public static let notifications: [NSNotification.Name] = [ UIResponder.keyboardWillShowNotification, UIResponder.keyboardDidShowNotification, UIResponder.keyboardWillHideNotification, UIResponder.keyboardDidHideNotification, UIResponder.keyboardWillChangeFrameNotification, UIResponder.keyboardDidChangeFrameNotification] // Last known keyboard notification public private(set) var lastKnownNotification: KeyboardNotification? // MARK: - Private properties private var observation: KeyboardNotificationObservation? private var isObserving: Bool = false deinit { stopObserving() } public init(observation: KeyboardNotificationObservation? = nil) { self.observation = observation } open func startObserving() { // stop the previous observers if any, just to be safe stopObserving() isObserving = true // subscribe to keyboard notifications KeyboardObserver.notifications.forEach { NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: $0, object: nil) } } open func stopObserving() { isObserving = false // unsubscribe from keyboard notifications KeyboardObserver.notifications.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) } } open func observation(_ inAnimation: Bool = false, _ observation: @escaping KeyboardNotificationObservation) { if inAnimation { self.observation = KeyboardObserver.animationObservation(observation) } else { self.observation = observation } } // MARK: - Private methods @objc private func handleNotification(_ notification: Notification) { guard isObserving, let keyboardNotification = KeyboardNotification(notification: notification) else { return } lastKnownNotification = keyboardNotification observation?(keyboardNotification) } fileprivate static func animationObservation(_ observation: KeyboardNotificationObservation?) -> KeyboardNotificationObservation { return { (notification: KeyboardNotification) in UIView.animate( withDuration: notification.animationDuration, delay: 0, options: [notification.animationOptions, .beginFromCurrentState], animations: { observation?(notification) }, completion: nil) } } public static func animate(_ notification: KeyboardNotification, _ block: @escaping (KeyboardNotification) -> Void) { let animation = animationObservation(block) animation(notification) } }
33.455446
134
0.687777
015ee51dda0acb73c5196009d2a45f51d98d680c
8,112
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // #if !os(watchOS) #if SWIFT_PACKAGE import ProcedureKit import Foundation #endif import SystemConfiguration public protocol NetworkResilience { /** The number of attempts to make for the network request. It represents the total number of attempts which should be made. - returns: a Int */ var maximumNumberOfAttempts: Int { get } /** The timeout backoff wait strategy defines the time between retry attempts in the event of a network timout. Use `.Immediate` to indicate no time between retry attempts. - returns: a WaitStrategy */ var backoffStrategy: WaitStrategy { get } /** A request timeout, which if specified indicates the maximum amount of time to wait for a response. - returns: a TimeInterval */ var requestTimeout: TimeInterval? { get } /** Some HTTP status codes should be treated as errors, and retried - parameter statusCode: an Int - returns: a Bool, to indicate that the */ func shouldRetry(forResponseWithHTTPStatusCode statusCode: HTTPStatusCode) -> Bool } public struct DefaultNetworkResilience: NetworkResilience { public let maximumNumberOfAttempts: Int public let backoffStrategy: WaitStrategy public let requestTimeout: TimeInterval? public init(maximumNumberOfAttempts: Int = 3, backoffStrategy: WaitStrategy = .incrementing(initial: 2, increment: 2), requestTimeout: TimeInterval? = 8.0) { self.maximumNumberOfAttempts = maximumNumberOfAttempts self.backoffStrategy = backoffStrategy self.requestTimeout = requestTimeout } public func shouldRetry(forResponseWithHTTPStatusCode statusCode: HTTPStatusCode) -> Bool { switch statusCode { case let code where code.isServerError: return true case .requestTimeout, .tooManyRequests: return true default: return false } } } public enum ProcedureKitNetworkResiliencyError: Error { case receivedErrorStatusCode(HTTPStatusCode) } class NetworkReachabilityWaitProcedure: Procedure { let reachability: SystemReachability let connectivity: Reachability.Connectivity init(reachability: SystemReachability, via connectivity: Reachability.Connectivity = .any) { self.reachability = reachability self.connectivity = connectivity super.init() } override func execute() { reachability.whenReachable(via: connectivity) { [weak self] in self?.finish() } } } class NetworkRecovery<T: Procedure> where T: NetworkOperation { let resilience: NetworkResilience let connectivity: Reachability.Connectivity var reachability: SystemReachability = Reachability.Manager.shared var max: Int { return resilience.maximumNumberOfAttempts } var wait: WaitStrategy { return resilience.backoffStrategy } init(resilience: NetworkResilience, connectivity: Reachability.Connectivity) { self.resilience = resilience self.connectivity = connectivity } func recover(withInfo info: RetryFailureInfo<T>, payload: RepeatProcedurePayload<T>) -> RepeatProcedurePayload<T>? { let networkResponse = info.operation.makeNetworkResponse() // Check to see if we should wait for a network reachability change before retrying if shouldWaitForReachabilityChange(givenNetworkResponse: networkResponse) { let waiter = NetworkReachabilityWaitProcedure(reachability: reachability, via: connectivity) payload.operation.add(dependency: waiter) info.addOperations(waiter) return RepeatProcedurePayload(operation: payload.operation, delay: nil, configure: payload.configure) } // Check if the resiliency behavior indicates a retry guard shouldRetry(givenNetworkResponse: networkResponse) else { return nil } return payload } func shouldWaitForReachabilityChange(givenNetworkResponse networkResponse: ProcedureKitNetworkResponse) -> Bool { guard let networkError = networkResponse.error else { return false } return networkError.waitForReachabilityChangeBeforeRetrying } func shouldRetry(givenNetworkResponse networkResponse: ProcedureKitNetworkResponse) -> Bool { // Check that we've actually got a network error & suggested delay if let networkError = networkResponse.error { // Check to see if we have a transient or timeout network error - retry with suggested delay if networkError.isTransientError || networkError.isTimeoutError { return true } } // Check to see if we have an http error code guard let statusCode = networkResponse.httpStatusCode, statusCode.isClientError || statusCode.isServerError else { return false } // Query the network resilience type to determine the behavior. return resilience.shouldRetry(forResponseWithHTTPStatusCode: statusCode) } } open class NetworkProcedure<T: Procedure>: RetryProcedure<T>, OutputProcedure where T: NetworkOperation, T: OutputProcedure, T.Output: HTTPPayloadResponseProtocol { public typealias Output = T.Output let recovery: NetworkRecovery<T> internal var reachability: SystemReachability { get { return recovery.reachability } set { recovery.reachability = newValue } } public init<OperationIterator>(dispatchQueue: DispatchQueue? = nil, resilience: NetworkResilience = DefaultNetworkResilience(), connectivity: Reachability.Connectivity = .any, iterator base: OperationIterator) where OperationIterator: IteratorProtocol, OperationIterator.Element == T { recovery = NetworkRecovery<T>(resilience: resilience, connectivity: connectivity) super.init(dispatchQueue: dispatchQueue, max: recovery.max, wait: recovery.wait, iterator: base, retry: recovery.recover(withInfo:payload:)) if let timeout = resilience.requestTimeout { appendConfigureBlock { $0.add(observer: TimeoutObserver(by: timeout)) } } } public convenience init(dispatchQueue: DispatchQueue = DispatchQueue.default, resilience: NetworkResilience = DefaultNetworkResilience(), connectivity: Reachability.Connectivity = .any, body: @escaping () -> T?) { self.init(dispatchQueue: dispatchQueue, resilience: resilience, connectivity: connectivity, iterator: AnyIterator(body)) } open override func child(_ child: Procedure, willFinishWithErrors errors: [Error]) { var networkErrors = errors // Ultimately, always call super to correctly manage the operation lifecycle. defer { super.child(child, willFinishWithErrors: networkErrors) } // Check that the operation is the current one. guard child == current else { return } // If we have any errors let RetryProcedure (super) deal with it by returning here guard errors.isEmpty else { return } // Create a network response from the network operation let networkResponse = current.makeNetworkResponse() // Check to see if this network response should be retried guard recovery.shouldRetry(givenNetworkResponse: networkResponse), let statusCode = networkResponse.httpStatusCode else { return } // Create resiliency error let error: ProcedureKitNetworkResiliencyError = .receivedErrorStatusCode(statusCode) // Set the network errors networkErrors = [error] } } #endif public extension InputProcedure where Input: Equatable { @discardableResult func injectPayload<Dependency: OutputProcedure>(fromNetwork dependency: Dependency) -> Self where Dependency.Output: HTTPPayloadResponseProtocol, Dependency.Output.Payload == Input { return injectResult(from: dependency) { http in guard let payload = http.payload else { throw ProcedureKitError.requirementNotSatisfied() } return payload } } }
37.041096
289
0.714497
50efe072711c1ff9183a2cae00cc93339a39290b
4,054
@testable import HAKit import XCTest internal class HAWebSocketResponseTests: XCTestCase { func testAuthRequired() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.authRequired) XCTAssertEqual(response, .auth(.required)) } func testAuthOK() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.authOK) XCTAssertEqual(response, .auth(.ok(version: "2021.3.0.dev0"))) } func testAuthOKMissingVersion() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.authOKMissingVersion) XCTAssertEqual(response, .auth(.ok(version: "unknown"))) } func testAuthInvalid() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.authInvalid) XCTAssertEqual(response, .auth(.invalid)) } func testResponseEmpty() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.responseEmptyResult) XCTAssertEqual(response, .result(identifier: 1, result: .success(.empty))) } func testResponseDictionary() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.responseDictionaryResult) XCTAssertEqual(response, .result( identifier: 2, result: .success(.dictionary(["id": "76ce52a813c44fdf80ee36f926d62328"])) )) } func testResponseEvent() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.responseEvent) XCTAssertEqual(response, .event( identifier: 5, data: .dictionary(["result": "ok"]) )) } func testResponseError() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.responseError) XCTAssertEqual(response, .result(identifier: 4, result: .failure(.external(.init( code: "unknown_command", message: "Unknown command." ))))) } func testResponseArray() throws { let response = try HAWebSocketResponse(dictionary: HAWebSocketResponseFixture.responseArrayResult) XCTAssertEqual(response, .result( identifier: 3, result: .success(.array([ .init(value: ["1": true]), .init(value: ["2": true]), .init(value: ["3": true]), ])) )) } func testMissingID() throws { XCTAssertThrowsError(try HAWebSocketResponse( dictionary: HAWebSocketResponseFixture .responseMissingID )) { error in switch error as? HAWebSocketResponse.ParseError { case .unknownId: break // pass default: XCTFail("expected different error") } } } func testInvalidID() throws { XCTAssertThrowsError(try HAWebSocketResponse( dictionary: HAWebSocketResponseFixture .responseInvalidID )) { error in switch error as? HAWebSocketResponse.ParseError { case .unknownId: break // pass default: XCTFail("expected different error") } } } func testMissingType() throws { XCTAssertThrowsError(try HAWebSocketResponse( dictionary: HAWebSocketResponseFixture .responseMissingType )) { error in switch error as? HAWebSocketResponse.ParseError { case .unknownType: break // pass default: XCTFail("expected different error") } } } func testInvalidType() throws { XCTAssertThrowsError(try HAWebSocketResponse( dictionary: HAWebSocketResponseFixture .responseInvalidType )) { error in switch error as? HAWebSocketResponse.ParseError { case .unknownType: break // pass default: XCTFail("expected different error") } } } }
35.561404
111
0.632215
dea44afd01c3a969004069f38f5ca32eb7c75c75
40,972
/* file: mismatch_of_edges.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY mismatch_of_edges SUBTYPE OF ( a3m_equivalence_criterion_of_shape_data_structure ); SELF\a3m_equivalence_criterion.assessment_specification : a3m_equivalence_assessment_by_logical_test; DERIVE SELF\a3m_equivalence_criterion.compared_element_types : LIST [1 : 1] OF a3ms_element_type_name := [ etns_connected_edge_set]; SELF\a3m_equivalence_criterion.measured_data_type : a3ms_measured_data_type_name := mdns_boolean_value; SELF\a3m_equivalence_criterion.detected_difference_types : LIST [2 : 2] OF a3ms_detected_difference_type_name := [ddns_edge, ddns_several_edges]; SELF\a3m_equivalence_criterion.accuracy_types : LIST [0 : 0] OF a3ms_accuracy_type_name := []; END_ENTITY; -- mismatch_of_edges (line:21442 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) representation_item ATTR: name, TYPE: label -- EXPLICIT SUPER- ENTITY(2) data_equivalence_criterion (no local attributes) SUPER- ENTITY(3) data_equivalence_inspection_requirement (no local attributes) SUPER- ENTITY(4) a3m_equivalence_criterion ATTR: assessment_specification, TYPE: a3m_equivalence_assessment_specification_select -- EXPLICIT -- possibly overriden by ENTITY: different_length_of_assembly_constraint, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_assembly_centroid_using_notional_solid, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: mismatch_of_component, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_number_of_closed_shell, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_curve_length, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: mismatch_of_underlying_face_geometry, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: missing_assembly_constraint, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_angle_of_assembly_constraint, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_number_of_topological_elements_wireframe_model, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: missing_edge, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_number_of_geometric_elements, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: missing_face, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: mismatch_of_points, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: missing_component, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_placement_of_component, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_volume, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_component_identification_via_multi_level_reference, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_surface_area, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_centroid, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_bounding_box, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_assembly_volume, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: mismatch_of_underlying_edge_geometry, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: a3m_equivalence_criterion_of_component_property_difference, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_number_of_geometric_elements_wireframe_model, TYPE: a3m_equivalence_assessment_by_logical_test *** ENTITY: mismatch_of_edges, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: mismatch_of_faces, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_surface_normal, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_number_of_topological_elements, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_assembly_centroid, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: mismatch_of_arcwise_connected_curves, TYPE: a3m_equivalence_assessment_by_numerical_test ENTITY: different_component_type, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_number_of_components, TYPE: a3m_equivalence_assessment_by_logical_test ENTITY: different_assembly_constraint_type, TYPE: a3m_equivalence_assessment_by_logical_test ATTR: comparing_element_types, TYPE: LIST [1 : ?] OF a3m_element_type_name -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: a3m_equivalence_criterion_of_representative_shape_property_value, TYPE: LIST [1 : ?] OF a3m_element_type_name (as DERIVED) ENTITY: mismatch_of_underlying_face_geometry, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_detailed_assembly_data_content, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: mismatch_of_points, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_component_shape, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: LIST [2 : 2] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_representative_assembly_property_value, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) *** ENTITY: a3m_equivalence_criterion_of_shape_data_structure, TYPE: LIST [1 : ?] OF a3m_element_type_name (as DERIVED) ENTITY: mismatch_of_underlying_edge_geometry, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_assembly_data_structure, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: different_surface_normal, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_curves, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_for_shape, TYPE: LIST [1 : ?] OF a3ms_element_type_name ENTITY: a3m_equivalence_criterion_for_assembly, TYPE: LIST [1 : ?] OF a3ma_element_type_name ATTR: compared_element_types, TYPE: LIST [1 : ?] OF a3m_element_type_name -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: different_number_of_closed_shell, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_curve_length, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_underlying_face_geometry, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_detailed_assembly_data_content, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: different_number_of_topological_elements_wireframe_model, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: missing_edge, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements, TYPE: LIST [2 : 2] OF a3ms_element_type_name (as DERIVED) ENTITY: missing_face, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_points, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_component_shape, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: different_volume, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_surface_area, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_centroid, TYPE: LIST [3 : 3] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_representative_assembly_property_value, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: different_bounding_box, TYPE: LIST [3 : 3] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_underlying_edge_geometry, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements_wireframe_model, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) *** ENTITY: mismatch_of_edges, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_assembly_data_structure, TYPE: LIST [1 : 1] OF a3ma_element_type_name (as DERIVED) ENTITY: mismatch_of_faces, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_surface_normal, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: different_number_of_topological_elements, TYPE: LIST [2 : 2] OF a3ms_element_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_curves, TYPE: LIST [1 : 1] OF a3ms_element_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_for_shape, TYPE: LIST [1 : ?] OF a3ms_element_type_name ENTITY: a3m_equivalence_criterion_for_assembly, TYPE: LIST [1 : ?] OF a3ma_element_type_name ATTR: measured_data_type, TYPE: a3m_measured_data_type_name -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: different_length_of_assembly_constraint, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_assembly_centroid_using_notional_solid, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_component, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_number_of_closed_shell, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_curve_length, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_underlying_face_geometry, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: missing_assembly_constraint, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_angle_of_assembly_constraint, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_number_of_topological_elements_wireframe_model, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: missing_edge, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: missing_face, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_points, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: missing_component, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_placement_of_component, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_volume, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_component_identification_via_multi_level_reference, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_surface_area, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_centroid, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_bounding_box, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_assembly_volume, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_underlying_edge_geometry, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_of_component_property_difference, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements_wireframe_model, TYPE: a3ms_measured_data_type_name (as DERIVED) *** ENTITY: mismatch_of_edges, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_faces, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_surface_normal, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_number_of_topological_elements, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_assembly_centroid, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_curves, TYPE: a3ms_measured_data_type_name (as DERIVED) ENTITY: different_component_type, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_for_shape, TYPE: a3ms_measured_data_type_name ENTITY: a3m_equivalence_criterion_for_assembly, TYPE: a3ma_measured_data_type_name ENTITY: different_number_of_components, TYPE: a3ma_measured_data_type_name (as DERIVED) ENTITY: different_assembly_constraint_type, TYPE: a3ma_measured_data_type_name (as DERIVED) ATTR: detected_difference_types, TYPE: LIST [0 : ?] OF a3m_detected_difference_type_name -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: different_length_of_assembly_constraint, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_assembly_centroid_using_notional_solid, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_component, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_number_of_closed_shell, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_curve_length, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_underlying_face_geometry, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: missing_assembly_constraint, TYPE: LIST [2 : 2] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_angle_of_assembly_constraint, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_number_of_topological_elements_wireframe_model, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: missing_edge, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: missing_face, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_points, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: missing_component, TYPE: LIST [2 : 2] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_placement_of_component, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_component_shape, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_volume, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_component_identification_via_multi_level_reference, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_surface_area, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_centroid, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: LIST [3 : 3] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_bounding_box, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_assembly_volume, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_underlying_edge_geometry, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements_wireframe_model, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) *** ENTITY: mismatch_of_edges, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_faces, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_surface_normal, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_number_of_topological_elements, TYPE: LIST [1 : 1] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_assembly_centroid, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_curves, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name (as DERIVED) ENTITY: different_component_type, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_for_shape, TYPE: LIST [1 : ?] OF a3ms_detected_difference_type_name ENTITY: a3m_equivalence_criterion_for_assembly, TYPE: LIST [1 : ?] OF a3ma_detected_difference_type_name ENTITY: different_number_of_components, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ENTITY: different_assembly_constraint_type, TYPE: LIST [1 : 1] OF a3ma_detected_difference_type_name (as DERIVED) ATTR: accuracy_types, TYPE: LIST [0 : ?] OF a3m_accuracy_type_name -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: different_number_of_closed_shell, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_curve_length, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_underlying_face_geometry, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_number_of_topological_elements_wireframe_model, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: missing_edge, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: missing_face, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_points, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_volume, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces_boundary, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_surface_area, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_centroid, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_point_cloud_and_related_geometry, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_bounding_box, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_underlying_edge_geometry, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_surfaces, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_number_of_geometric_elements_wireframe_model, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) *** ENTITY: mismatch_of_edges, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_faces, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_surface_normal, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: different_number_of_topological_elements, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: mismatch_of_arcwise_connected_curves, TYPE: LIST [1 : 1] OF a3ms_accuracy_type_name (as DERIVED) ENTITY: a3m_equivalence_criterion_for_shape, TYPE: LIST [0 : ?] OF a3ms_accuracy_type_name ENTITY: a3m_equivalence_criterion_for_assembly, TYPE: LIST [0 : 0] OF a3ma_accuracy_type_name (as DERIVED) SUPER- ENTITY(5) a3m_equivalence_criterion_for_shape REDCR: comparing_element_types, TYPE: LIST [1 : ?] OF a3ms_element_type_name -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: compared_element_types, TYPE: LIST [1 : ?] OF a3ms_element_type_name -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: measured_data_type, TYPE: a3ms_measured_data_type_name -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: detected_difference_types, TYPE: LIST [1 : ?] OF a3ms_detected_difference_type_name -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: accuracy_types, TYPE: LIST [0 : ?] OF a3ms_accuracy_type_name -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion SUPER- ENTITY(6) a3m_equivalence_criterion_of_shape_data_structure REDCR: comparing_element_types, TYPE: LIST [1 : ?] OF a3m_element_type_name -- DERIVED (DYNAMIC) := SELF\a3m_equivalence_criterion.compared_element_types -- OVERRIDING ENTITY: a3m_equivalence_criterion ENTITY(SELF) mismatch_of_edges REDCR: assessment_specification, TYPE: a3m_equivalence_assessment_by_logical_test -- EXPLICIT -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: compared_element_types, TYPE: LIST [1 : 1] OF a3ms_element_type_name -- DERIVED (DYNAMIC) := [etns_connected_edge_set] -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: measured_data_type, TYPE: a3ms_measured_data_type_name -- DERIVED (DYNAMIC) := mdns_boolean_value -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: detected_difference_types, TYPE: LIST [2 : 2] OF a3ms_detected_difference_type_name -- DERIVED (DYNAMIC) := [ddns_edge, ddns_several_edges] -- OVERRIDING ENTITY: a3m_equivalence_criterion REDCR: accuracy_types, TYPE: LIST [0 : 0] OF a3ms_accuracy_type_name -- DERIVED (DYNAMIC) := [] -- OVERRIDING ENTITY: a3m_equivalence_criterion */ //MARK: - Partial Entity public final class _mismatch_of_edges : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eMISMATCH_OF_EDGES.self } //ATTRIBUTES /* override var _assessment_specification: eA3M_EQUIVALENCE_ASSESSMENT_BY_LOGICAL_TEST //EXPLICIT REDEFINITION(eA3M_EQUIVALENCE_CRITERION) */ /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - attribute value provider protocol conformance wrapper internal func _compared_element_types__getter(complex: SDAI.ComplexEntity) -> SDAI.LIST< nA3M_ELEMENT_TYPE_NAME>/*[1:nil]*/ { let SELF = complex.entityReference( eMISMATCH_OF_EDGES.self )! return SDAI.UNWRAP( SDAI.LIST<nA3M_ELEMENT_TYPE_NAME>(SELF.COMPARED_ELEMENT_TYPES) ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - gut of derived attribute logic internal func _compared_element_types__getter(SELF: eMISMATCH_OF_EDGES) -> SDAI.LIST< nA3MS_ELEMENT_TYPE_NAME>/*[1:1]*/ { let _TEMP1 = SDAI.LIST<nA3MS_ELEMENT_TYPE_NAME>(bound1: SDAI.UNWRAP(SDAI.INTEGER(1)), bound2: SDAI.INTEGER( 1), ([SDAI.AIE(nA3MS_ELEMENT_TYPE_NAME(/*nA3M_ELEMENT_TYPE_NAME*/ETNS_CONNECTED_EDGE_SET))] as [SDAI.AggregationInitializerElement<nA3MS_ELEMENT_TYPE_NAME>])) let value = _TEMP1 return SDAI.UNWRAP( value ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - attribute value provider protocol conformance wrapper internal func _measured_data_type__getter(complex: SDAI.ComplexEntity) -> nA3M_MEASURED_DATA_TYPE_NAME { let SELF = complex.entityReference( eMISMATCH_OF_EDGES.self )! return SDAI.UNWRAP( nA3M_MEASURED_DATA_TYPE_NAME(SELF.MEASURED_DATA_TYPE) ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - gut of derived attribute logic internal func _measured_data_type__getter(SELF: eMISMATCH_OF_EDGES) -> nA3MS_MEASURED_DATA_TYPE_NAME { let value = nA3MS_MEASURED_DATA_TYPE_NAME(/*nA3M_MEASURED_DATA_TYPE_NAME*/MDNS_BOOLEAN_VALUE) return SDAI.UNWRAP( value ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - attribute value provider protocol conformance wrapper internal func _detected_difference_types__getter(complex: SDAI.ComplexEntity) -> SDAI.LIST< nA3M_DETECTED_DIFFERENCE_TYPE_NAME>/*[0:nil]*/ { let SELF = complex.entityReference( eMISMATCH_OF_EDGES.self )! return SDAI.UNWRAP( SDAI.LIST<nA3M_DETECTED_DIFFERENCE_TYPE_NAME>(SELF.DETECTED_DIFFERENCE_TYPES) ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - gut of derived attribute logic internal func _detected_difference_types__getter(SELF: eMISMATCH_OF_EDGES) -> SDAI.LIST< nA3MS_DETECTED_DIFFERENCE_TYPE_NAME>/*[2:2]*/ { let _TEMP1 = SDAI.LIST<nA3MS_DETECTED_DIFFERENCE_TYPE_NAME>(bound1: SDAI.UNWRAP(SDAI.INTEGER(2)), bound2: SDAI.INTEGER(2), ([SDAI.AIE(nA3MS_DETECTED_DIFFERENCE_TYPE_NAME(/* nA3M_DETECTED_DIFFERENCE_TYPE_NAME*/DDNS_EDGE)), SDAI.AIE(nA3MS_DETECTED_DIFFERENCE_TYPE_NAME(/*nA3M_DETECTED_DIFFERENCE_TYPE_NAME*/DDNS_SEVERAL_EDGES))] as [SDAI.AggregationInitializerElement<nA3MS_DETECTED_DIFFERENCE_TYPE_NAME>])) let value = _TEMP1 return SDAI.UNWRAP( value ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - attribute value provider protocol conformance wrapper internal func _accuracy_types__getter(complex: SDAI.ComplexEntity) -> SDAI.LIST<nA3M_ACCURACY_TYPE_NAME> /*[0:nil]*/ { let SELF = complex.entityReference( eMISMATCH_OF_EDGES.self )! return SDAI.UNWRAP( SDAI.LIST<nA3M_ACCURACY_TYPE_NAME>(SELF.ACCURACY_TYPES) ) } /// DERIVE ATTRIBUTE REDEFINITION(origin: eA3M_EQUIVALENCE_CRITERION) /// - gut of derived attribute logic internal func _accuracy_types__getter(SELF: eMISMATCH_OF_EDGES) -> SDAI.LIST<nA3MS_ACCURACY_TYPE_NAME>/*[ 0:0]*/ { let _TEMP1 = SDAI.LIST<nA3MS_ACCURACY_TYPE_NAME>(bound1: SDAI.UNWRAP(SDAI.INTEGER(0)), bound2: SDAI.INTEGER( 0), SDAI.EMPLY_AGGREGATE) let value = _TEMP1 return SDAI.UNWRAP( value ) } public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY mismatch_of_edges SUBTYPE OF ( a3m_equivalence_criterion_of_shape_data_structure ); SELF\a3m_equivalence_criterion.assessment_specification : a3m_equivalence_assessment_by_logical_test; DERIVE SELF\a3m_equivalence_criterion.compared_element_types : LIST [1 : 1] OF a3ms_element_type_name := [ etns_connected_edge_set]; SELF\a3m_equivalence_criterion.measured_data_type : a3ms_measured_data_type_name := mdns_boolean_value; SELF\a3m_equivalence_criterion.detected_difference_types : LIST [2 : 2] OF a3ms_detected_difference_type_name := [ddns_edge, ddns_several_edges]; SELF\a3m_equivalence_criterion.accuracy_types : LIST [0 : 0] OF a3ms_accuracy_type_name := []; END_ENTITY; -- mismatch_of_edges (line:21442 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eMISMATCH_OF_EDGES : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _mismatch_of_edges.self } public let partialEntity: _mismatch_of_edges //MARK: SUPERTYPES public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [1] public let super_eDATA_EQUIVALENCE_CRITERION: eDATA_EQUIVALENCE_CRITERION // [2] public let super_eDATA_EQUIVALENCE_INSPECTION_REQUIREMENT: eDATA_EQUIVALENCE_INSPECTION_REQUIREMENT // [3] public let super_eA3M_EQUIVALENCE_CRITERION: eA3M_EQUIVALENCE_CRITERION // [4] public let super_eA3M_EQUIVALENCE_CRITERION_FOR_SHAPE: eA3M_EQUIVALENCE_CRITERION_FOR_SHAPE // [5] public let super_eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE: eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE // [6] public var super_eMISMATCH_OF_EDGES: eMISMATCH_OF_EDGES { return self } // [7] //MARK: SUBTYPES //MARK: ATTRIBUTES /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SELF( ``eMISMATCH_OF_EDGES`` ) public var ACCURACY_TYPES: SDAI.LIST<nA3MS_ACCURACY_TYPE_NAME>/*[0:0]*/ { get { if let cached = cachedValue(derivedAttributeName:"ACCURACY_TYPES") { return cached.value as! SDAI.LIST<nA3MS_ACCURACY_TYPE_NAME>/*[0:0]*/ } let origin = self let value = SDAI.UNWRAP( origin.partialEntity._accuracy_types__getter(SELF: origin) ) updateCache(derivedAttributeName:"ACCURACY_TYPES", value:value) return value } } /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SELF( ``eMISMATCH_OF_EDGES`` ) public var DETECTED_DIFFERENCE_TYPES: SDAI.LIST<nA3MS_DETECTED_DIFFERENCE_TYPE_NAME>/*[2:2]*/ { get { if let cached = cachedValue(derivedAttributeName:"DETECTED_DIFFERENCE_TYPES") { return cached.value as! SDAI.LIST<nA3MS_DETECTED_DIFFERENCE_TYPE_NAME>/*[2:2]*/ } let origin = self let value = SDAI.UNWRAP( origin.partialEntity._detected_difference_types__getter(SELF: origin) ) updateCache(derivedAttributeName:"DETECTED_DIFFERENCE_TYPES", value:value) return value } } /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SELF( ``eMISMATCH_OF_EDGES`` ) public var COMPARED_ELEMENT_TYPES: SDAI.LIST<nA3MS_ELEMENT_TYPE_NAME>/*[1:1]*/ { get { if let cached = cachedValue(derivedAttributeName:"COMPARED_ELEMENT_TYPES") { return cached.value as! SDAI.LIST<nA3MS_ELEMENT_TYPE_NAME>/*[1:1]*/ } let origin = self let value = SDAI.UNWRAP( origin.partialEntity._compared_element_types__getter(SELF: origin) ) updateCache(derivedAttributeName:"COMPARED_ELEMENT_TYPES", value:value) return value } } /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SELF( ``eMISMATCH_OF_EDGES`` ) public var MEASURED_DATA_TYPE: nA3MS_MEASURED_DATA_TYPE_NAME { get { if let cached = cachedValue(derivedAttributeName:"MEASURED_DATA_TYPE") { return cached.value as! nA3MS_MEASURED_DATA_TYPE_NAME } let origin = self let value = SDAI.UNWRAP( origin.partialEntity._measured_data_type__getter(SELF: origin) ) updateCache(derivedAttributeName:"MEASURED_DATA_TYPE", value:value) return value } } /// __EXPLICIT REDEF__ attribute /// - origin: SELF( ``eMISMATCH_OF_EDGES`` ) public var ASSESSMENT_SPECIFICATION: eA3M_EQUIVALENCE_ASSESSMENT_BY_LOGICAL_TEST { get { return SDAI.UNWRAP( eA3M_EQUIVALENCE_ASSESSMENT_BY_LOGICAL_TEST( super_eA3M_EQUIVALENCE_CRITERION .partialEntity._assessment_specification ) ) } set(newValue) { let partial = super_eA3M_EQUIVALENCE_CRITERION.partialEntity partial._assessment_specification = SDAI.UNWRAP( sA3M_EQUIVALENCE_ASSESSMENT_SPECIFICATION_SELECT(newValue)) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eREPRESENTATION_ITEM`` ) public var NAME: tLABEL { get { return SDAI.UNWRAP( super_eREPRESENTATION_ITEM.partialEntity._name ) } set(newValue) { let partial = super_eREPRESENTATION_ITEM.partialEntity partial._name = SDAI.UNWRAP(newValue) } } /// __EXPLICIT REDEF(DERIVE)__ attribute /// - origin: SUPER( ``eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE`` ) public var COMPARING_ELEMENT_TYPES: SDAI.LIST<nA3M_ELEMENT_TYPE_NAME>/*[1:nil]*/ { get { if let cached = cachedValue(derivedAttributeName:"COMPARING_ELEMENT_TYPES") { return cached.value as! SDAI.LIST<nA3M_ELEMENT_TYPE_NAME>/*[1:nil]*/ } let origin = super_eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE let value = SDAI.UNWRAP( SDAI.LIST<nA3M_ELEMENT_TYPE_NAME>( origin.partialEntity._comparing_element_types__getter(SELF: origin)) ) updateCache(derivedAttributeName:"COMPARING_ELEMENT_TYPES", value:value) return value } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_mismatch_of_edges.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil } self.super_eREPRESENTATION_ITEM = super1 guard let super2 = complexEntity?.entityReference(eDATA_EQUIVALENCE_CRITERION.self) else { return nil } self.super_eDATA_EQUIVALENCE_CRITERION = super2 guard let super3 = complexEntity?.entityReference(eDATA_EQUIVALENCE_INSPECTION_REQUIREMENT.self) else { return nil } self.super_eDATA_EQUIVALENCE_INSPECTION_REQUIREMENT = super3 guard let super4 = complexEntity?.entityReference(eA3M_EQUIVALENCE_CRITERION.self) else { return nil } self.super_eA3M_EQUIVALENCE_CRITERION = super4 guard let super5 = complexEntity?.entityReference(eA3M_EQUIVALENCE_CRITERION_FOR_SHAPE.self) else { return nil } self.super_eA3M_EQUIVALENCE_CRITERION_FOR_SHAPE = super5 guard let super6 = complexEntity?.entityReference(eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE.self) else { return nil } self.super_eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE = super6 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "MISMATCH_OF_EDGES", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eREPRESENTATION_ITEM.self) entityDef.add(supertype: eDATA_EQUIVALENCE_CRITERION.self) entityDef.add(supertype: eDATA_EQUIVALENCE_INSPECTION_REQUIREMENT.self) entityDef.add(supertype: eA3M_EQUIVALENCE_CRITERION.self) entityDef.add(supertype: eA3M_EQUIVALENCE_CRITERION_FOR_SHAPE.self) entityDef.add(supertype: eA3M_EQUIVALENCE_CRITERION_OF_SHAPE_DATA_STRUCTURE.self) entityDef.add(supertype: eMISMATCH_OF_EDGES.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "ACCURACY_TYPES", keyPath: \eMISMATCH_OF_EDGES.ACCURACY_TYPES, kind: .derivedRedeclaring, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "DETECTED_DIFFERENCE_TYPES", keyPath: \eMISMATCH_OF_EDGES.DETECTED_DIFFERENCE_TYPES, kind: .derivedRedeclaring, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "COMPARED_ELEMENT_TYPES", keyPath: \eMISMATCH_OF_EDGES.COMPARED_ELEMENT_TYPES, kind: .derivedRedeclaring, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "MEASURED_DATA_TYPE", keyPath: \eMISMATCH_OF_EDGES.MEASURED_DATA_TYPE, kind: .derivedRedeclaring, source: .thisEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "ASSESSMENT_SPECIFICATION", keyPath: \eMISMATCH_OF_EDGES.ASSESSMENT_SPECIFICATION, kind: .explicitRedeclaring, source: .thisEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "NAME", keyPath: \eMISMATCH_OF_EDGES.NAME, kind: .explicit, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "COMPARING_ELEMENT_TYPES", keyPath: \eMISMATCH_OF_EDGES.COMPARING_ELEMENT_TYPES, kind: .derivedRedeclaring, source: .superEntity, mayYieldEntityReference: false) return entityDef } } } //MARK: - partial Entity Dynamic Attribute Protocol Conformances extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF._mismatch_of_edges : eA3M_EQUIVALENCE_CRITERION__COMPARED_ELEMENT_TYPES__provider, eA3M_EQUIVALENCE_CRITERION__MEASURED_DATA_TYPE__provider, eA3M_EQUIVALENCE_CRITERION__DETECTED_DIFFERENCE_TYPES__provider, eA3M_EQUIVALENCE_CRITERION__ACCURACY_TYPES__provider {}
64.01875
185
0.752587
bbe5acf97a0f0281a35ed6d5702acc0777382259
245
// Copyright © 2017 Poikile Creations. All rights reserved. import Foundation // swiftlint:disable identifier_name public protocol Unique { var id: Int { get } var resourceUrl: String { get } } // swiftlint:enable identifier_name
16.333333
60
0.722449
e9c1c043f272bae0a14b78f82a7670ae7250a2bd
2,175
// // AppDelegate.swift // Example-swift // // Created by Paul-Emmanuel on 20/10/16. // Copyright © 2016 RStudio. 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.276596
285
0.755402
d7b32c38894add6154eb70a40337be8779029634
4,156
// // VSectionListModel.swift // VComponents // // Created by Vakhtang Kontridze on 1/10/21. // import SwiftUI // MARK:- V Section List Model /// Model that describes UI public struct VSectionListModel { /// Sub-model containing layout properties public var layout: Layout = .init() /// Sub-model containing color properties public var colors: Colors = .init() /// Sub-model containing font properties public var fonts: Fonts = .init() /// Sub-model containing misc properties public var misc: Misc = .init() /// Initializes model with default values public init() {} } // MARK:- Layout extension VSectionListModel { /// Sub-model containing layout properties public struct Layout { /// Table corner radius. Defaults to `15`. public var cornerRadius: CGFloat = listReference.layout.cornerRadius /// Content margin. Defaults to `10`. public var contentMargin: CGFloat = listReference.layout.contentMargin /// Spacing between sections. Defaults to `20`. public var sectionSpacing: CGFloat = 20 /// Spacing between rows. Defaults to `18`. public var rowSpacing: CGFloat = listReference.layout.rowSpacing /// Header bottom margin. Defaults to `10`. public var headerMarginBottom: CGFloat = 10 /// Footer bottom top. Defaults to `10`. public var footerMarginTop: CGFloat = 10 /// Row divider height. Defaults to `1`. public var dividerHeight: CGFloat = listReference.layout.dividerHeight /// Initializes sub-model with default values public init() {} } } // MARK:- Colors extension VSectionListModel { /// Sub-model containing color properties public struct Colors { /// Row divider color public var divider: Color = listReference.colors.divider /// Background color public var background: Color = listReference.colors.background /// Text header color /// /// Only applicable when using init with title public var headerText: Color = ColorBook.secondary /// Text footer color /// /// Only applicable when using init with title public var footerText: Color = ColorBook.secondary /// Initializes sub-model with default values public init() {} } } // MARK:- Fonts extension VSectionListModel { /// Sub-model containing font properties public struct Fonts { /// Header font /// /// Only applicable when using init with title public var header: Font = .system(size: 13) /// Footer font /// /// Only applicable when using init with title public var footer: Font = .system(size: 13) /// Initializes sub-model with default values public init() {} } } // MARK:- Misc extension VSectionListModel { /// Sub-model containing misc properties public struct Misc { /// Indicates if scrolling indicator is shown. Defaults to `true`. public var showIndicator: Bool = true /// Initializes sub-model with default values public init() {} } } // MARK:- References extension VSectionListModel { /// Reference to `VListModel` public static let listReference: VListModel = .init() } // MARK:- Sub-Models extension VSectionListModel { var baseListSubModel: VBaseListModel { var model: VBaseListModel = .init() model.misc.showIndicator = misc.showIndicator model.layout.rowSpacing = layout.rowSpacing model.layout.dividerHeight = layout.dividerHeight model.colors.divider = colors.divider return model } var sheetSubModel: VSheetModel { var model: VSheetModel = .init() model.layout.cornerRadius = layout.cornerRadius model.layout.contentMargin = 0 model.colors.background = colors.background return model } }
28.272109
78
0.615255
264bcf20360a50dd0ff238717287f86cfb71da39
976
import Foundation public class NetworkAsserter { /** * Asserts if the device is connected to internet * - Note: works in IOS and OSX * - Fixme: ⚠️️ Needs more work, see stackoverflow https://stackoverflow.com/questions/30743408/check-for-internet-connection-with-swift */ public static func isConnectedToInternet() -> Bool { /* Fixme: Needs research let url = NSURL(string: "http://google.com/") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 var response: NSURLResponse? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData? print(data) if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == 200 { return true } } */ return false } }
30.5
139
0.681352
1101fa128e695803af2a9a470ab6a379a1289eb2
1,621
// // ViewController.swift // API Demo // // Created by Royce on 24/12/2016. // Copyright © 2016 Ryetech. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var labelDescription: UILabel! @IBOutlet weak var textFieldCity: UITextField! @IBAction func submitTapped(_ sender: UIButton) { guard let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=" + textFieldCity.text!.replacingOccurrences(of: " ", with: "%20") + ",uk&appid=\(API_KEY)") else { labelDescription.text = "Couldn't find weather for that city - please try another." return } let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let error = error { print(error) return } if let urlContent = data { do { let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject if let description = ((jsonResult["weather"] as? NSArray)?[0] as? NSDictionary)?["description"] as? String { DispatchQueue.main.sync(execute: { self.labelDescription.text = description }) } } catch { print("JSON Processing Failed") } } } task.resume() } }
31.784314
186
0.525601
e923d5ae609b568ff09b56f163601c1d18b0dc11
168
import Foundation public struct MileusWatchdogSearchData { public let type: MileusWatchdogSearchType public let location: MileusWatchdogLocation }
15.272727
47
0.761905
f914606a8f593327350da2f46f1c80aa31f53054
7,454
// // EasyLoadingShimmer.swift // EasyLoadingShimmer // // Created by sj_w on 2019/1/11. // Copyright © 2019年 sj_w. All rights reserved. // import UIKit open class EasyLoadingShimmer: NSObject { /// 拿来遮盖 toCoveriView 的覆盖层 private lazy var viewCover: UIView = { let v = UIView.init() v.tag = 1987 v.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) return v }() /// 颜色渐变层 private var colorLayer: CAGradientLayer? /// 用于显示建层层的mask private var maskLayer: CAShapeLayer? /// 总的覆盖路径 private lazy var totalCoverablePath: UIBezierPath = { let p = UIBezierPath.init() return p }() private var addOffsetflag: Bool? /// 开始覆盖子控件 如果view是UITableView才传identifiers public static func startCovering(for view: UIView?, with identifiers: [String]? = ["Cell1", "Cell1", "Cell1", "Cell1", "Cell1"]) { EasyLoadingShimmer.init().coverSubviews(view: view, with: identifiers) } /// 停止覆盖子控件 public static func stopCovering(for view: UIView?) { EasyLoadingShimmer.init().removeSubviews(view: view) } private func coverSubviews(view: UIView?, with identifiers: [String]?) { guard let v = view else { NSException(name: NSExceptionName(rawValue: "coverSubviews"), reason: "[(void)coverSubviews:(UIView *)view]:view is nil", userInfo: nil).raise() return } for subV in v.subviews { if subV.tag == 1987 { return } } // let coverableCellsIds: [String] = ["Cell1", "Cell1", "Cell1", "Cell1", "Cell1"] if let coverableCellsIds = identifiers { if v.isMember(of: UITableView.self) { for (index, _) in coverableCellsIds.enumerated() { getTableViewPath(view: v, index: index, coverableCellsIds: coverableCellsIds) } addCover(view: v) return } } v.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) if v.subviews.count > 0 { for subV in v.subviews { var defaultCoverblePath = UIBezierPath(roundedRect: subV.bounds, cornerRadius: subV.frame.size.height / 2.0) if subV.isMember(of: UILabel.self) || subV.isMember(of: UITextView.self) { defaultCoverblePath = UIBezierPath(roundedRect: subV.bounds, cornerRadius: 4) } let relativePath = defaultCoverblePath let offsetPoint = subV.convert(subV.bounds, to: v).origin subV.layoutIfNeeded() relativePath.apply(CGAffineTransform(translationX: offsetPoint.x, y: offsetPoint.y)) totalCoverablePath.append(relativePath) } addCover(view: v) } } private func removeSubviews(view: UIView?) { guard let v = view else { NSException(name: NSExceptionName(rawValue: "removeSubviews"), reason: "[(void)removeSubviews:(UIView *)view]:view is nil", userInfo: nil).raise() return } for subV in v.subviews { if subV.tag == 1987 { subV.removeFromSuperview() break } } } private func getTableViewPath(view: UIView, index: Int, coverableCellsIds: [String]) { let tableView = view as! UITableView let headerOffset = EasyLoadingShimmer.getHeaderOffset() if let cell = tableView.dequeueReusableCell(withIdentifier: coverableCellsIds[index]) { cell.frame = CGRect(x: 0, y: cell.frame.size.height * CGFloat(index) + headerOffset, width: cell.frame.size.width, height: cell.frame.size.height) cell.layoutIfNeeded() for cellSub in cell.contentView.subviews { let defaultCoverblePath = UIBezierPath(roundedRect: cellSub.bounds, cornerRadius: cellSub.frame.size.height / 2.0) var offsetPoint = cellSub.convert(cellSub.bounds, to: tableView).origin if index == 0, offsetPoint.y > cellSub.frame.origin.y { addOffsetflag = true } if let flag = addOffsetflag, flag { offsetPoint.y -= headerOffset } cellSub.layoutIfNeeded() defaultCoverblePath.apply(CGAffineTransform(translationX: offsetPoint.x, y: offsetPoint.y + headerOffset)) totalCoverablePath.append(defaultCoverblePath) } } } private func addCover(view: UIView) { viewCover.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) view.addSubview(viewCover) let colorLayer = CAGradientLayer.init() colorLayer.frame = view.bounds colorLayer.startPoint = CGPoint(x: -1.4, y: 0) colorLayer.endPoint = CGPoint(x: 1.4, y: 0) colorLayer.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.01).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 0.009).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.04).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.02).cgColor] colorLayer.locations = [NSNumber(value: Float(colorLayer.startPoint.x)), NSNumber(value: Float(colorLayer.startPoint.x)), NSNumber(value: 0), NSNumber(value: 0.2), NSNumber(value: 1.2)] viewCover.layer.addSublayer(colorLayer) let maskLayer = CAShapeLayer.init() maskLayer.path = totalCoverablePath.cgPath maskLayer.fillColor = UIColor.red.cgColor colorLayer.mask = maskLayer // 动画 animate let animation = CABasicAnimation(keyPath: "locations") animation.fromValue = colorLayer.locations animation.toValue = [NSNumber(value: 0), NSNumber(value: 1), NSNumber(value: 1), NSNumber(value: 1.2), NSNumber(value: 1.2)] animation.duration = 0.9 animation.repeatCount = HUGE animation.isRemovedOnCompletion = false colorLayer.add(animation, forKey: "locations-layer") } } extension EasyLoadingShimmer { static let kScreenHeight = UIScreen.main.bounds.size.height // X h=812,XR & XR max h=896 static let safeAreaTopHeight = (EasyLoadingShimmer.kScreenHeight == 812.0 || EasyLoadingShimmer.kScreenHeight == 896.0) ? 88.0 : 64.0 // 增加适配 x xr xr max static func getHeaderOffset() -> CGFloat { if let _ = EasyLoadingShimmer.currentViewController() { return CGFloat(EasyLoadingShimmer.safeAreaTopHeight) }else { return 0 } } static func currentViewController() -> UIViewController? { let keyWindow = UIApplication.shared.keyWindow var viewController = keyWindow?.rootViewController while let vc = viewController, vc.presentedViewController != nil { viewController = vc.presentedViewController if vc.isKind(of: UINavigationController.self) { viewController = (vc as! UINavigationController).visibleViewController }else if vc.isKind(of: UITabBarController.self) { viewController = (vc as! UITabBarController).selectedViewController } } return viewController } }
42.112994
313
0.610276
169edc4b348f354e6506e573ebe07c59b33557e2
249
// // WebBridgeConstants.swift // import Foundation public struct WebBridgeConstants { //TODO: phongtest - alllow passing this as header dict static let userAgent = "Custom-User-Agent" static let defaultTimeout = 5 //in seconds }
20.75
58
0.710843
e90cf73bab1950a6d9e63e29e8d2057299f3dca7
912
// // MenuButtonType.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-30. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit enum MenuButtonType { case security case support case settings case lock var title: String { switch self { case .security: return S.MenuButton.security case .support: return S.MenuButton.support case .settings: return S.MenuButton.settings case .lock: return S.MenuButton.lock } } var image: UIImage { switch self { case .security: return UIImage(named: "Shield")! case .support: return UIImage(named: "FaqFill")! case .settings: return UIImage(named: "Settings")! case .lock: return UIImage(named: "Lock")! } } }
21.209302
58
0.557018
4ad179acb1208736dc999de27cc88038d75a3e5a
2,290
// // SceneDelegate.swift // foodpin // // Created by Tsuen Hsueh on 2021/11/1. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not 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. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.207547
147
0.712664
dea5d1ce33636db49337f36d5695327b5dc15aa8
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing a ( { class a { let d { enum A { let c = [ { case { struct A { class case ,
16.333333
87
0.697959
bb4a5d1b7c5723103a9467fce3dee8e7b2b9cfc5
2,760
// // HashtagCollectionViewCell.swift // Hashtags // // Created by Oscar Götting on 6/8/18. // Copyright © 2018 Oscar Götting. All rights reserved. // import Foundation import UIKit open class HashtagCollectionViewCell: UICollectionViewCell { static let cellIdentifier = "HashtagCollectionViewCell" var paddingLeftConstraint: NSLayoutConstraint? var paddingRightConstraint: NSLayoutConstraint? var paddingTopConstraint: NSLayoutConstraint? var paddingBottomConstraint: NSLayoutConstraint? lazy var wordLabel : UILabel = { let lbl = UILabel() lbl.textColor = UIColor.white lbl.textAlignment = .left lbl.numberOfLines = 0 lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() open var hashtag: HashTag? override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open func setup() { self.clipsToBounds = true self.addSubview(wordLabel) // Padding left self.paddingLeftConstraint = self.wordLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor) self.paddingLeftConstraint!.isActive = true // Padding top self.paddingTopConstraint = self.wordLabel.topAnchor.constraint(equalTo: self.topAnchor) self.paddingTopConstraint!.isActive = true // Padding bottom self.paddingBottomConstraint = self.wordLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor) self.paddingBottomConstraint!.isActive = true // Padding right self.paddingRightConstraint = self.wordLabel.rightAnchor.constraint(equalTo: self.rightAnchor) self.paddingRightConstraint!.isActive = true } open override func prepareForInterfaceBuilder() { self.wordLabel.text = "" super.prepareForInterfaceBuilder() } open func configureWithTag(tag: HashTag, configuration: HashtagConfiguration) { self.hashtag = tag wordLabel.text = tag.text self.paddingLeftConstraint!.constant = configuration.paddingLeft self.paddingTopConstraint!.constant = configuration.paddingTop self.paddingBottomConstraint!.constant = -1 * configuration.paddingBottom self.paddingRightConstraint!.constant = -1 * configuration.paddingRight self.layer.cornerRadius = configuration.cornerRadius self.backgroundColor = configuration.backgroundColor self.wordLabel.textColor = configuration.textColor self.wordLabel.font = UIFont.systemFont(ofSize: configuration.textSize) } }
33.658537
105
0.687319
22f7fdc62f0201e30d0ee99ceacaa3a0e9d11c6c
463
// // OfflineBarView.swift // Movie-DB-SwiftUI // // Created by Vidhyadharan on 29/12/20. // import SwiftUI struct OfflineBarView: View { var body: some View { VStack { Text("Offline") .padding(4) .frame(maxWidth: .infinity) } .background(Color.systemGray) } } struct OfflineBarView_Previews: PreviewProvider { static var previews: some View { OfflineBarView() } }
17.807692
49
0.578834
22a2ef702beef3658f1e27c442eff43a87ae3c68
947
// // ProfileCell.swift // eduid-iOS // // Created by Blended Learning Center on 01.02.18. // Copyright © 2018 Blended Learning Center. All rights reserved. // import UIKit /** Simple cell view class to hold the specific data to be shown on the List view (ProfileListViewController) */ class ProfileCell: UICollectionViewCell { @IBOutlet weak var keyLabel: UILabel! @IBOutlet weak var valueLabel: UILabel! override func awakeFromNib() { //print("CELL AWAKE FROM NIB") valueLabel.adjustsFontSizeToFitWidth = true keyLabel.adjustsFontSizeToFitWidth = true } private var keyStr : String?{ get{ return keyLabel.text } set { keyLabel.text = newValue } } private var valueStr : String? { get{ return valueLabel.text } set { valueLabel.text = newValue } } }
22.023256
106
0.599789
e0172365b4d8a9e31075f7c568296f4cfdca0cc5
755
import XCTest //import ASKBlinkingLabel 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. } } }
26.034483
111
0.602649
4855496119910c1da2ab240366c93c1db650737f
1,647
// // Created by Jakub Bednář on 04/11/2020. // import InfluxDBSwift @testable import InfluxDBSwiftApis import XCTest class ScraperTargetsAPITests: APIXCTestCase { override func setUp() { super.setUp() api.scraperTargetsAPI.getScrapers { scrapers, _ in scrapers? .configurations? .filter { configuration in if let name = configuration.name { return name.hasSuffix("_TEST") } return false }.forEach { configuration in self.api.scraperTargetsAPI.deleteScrapersID(scraperTargetID: configuration.id!) { _, _ in } } } } func testCreateScraperTarget() { let scraperName = generateName("scraper") let request = ScraperTargetRequest( name: scraperName, type: ScraperTargetRequest.ModelType.prometheus, url: "http://localhost:8086", orgID: Self.orgID, bucketID: Self.bucketID) var checker: (ScraperTargetResponse) -> Void = { response in XCTAssertNotNil(response.id) XCTAssertEqual(scraperName, response.name) XCTAssertEqual(Self.orgID, response.orgID) XCTAssertEqual(Self.bucketID, response.bucketID) XCTAssertEqual(ScraperTargetResponse.ModelType.prometheus, response.type) XCTAssertNotNil(response.links) } checkPost(api.scraperTargetsAPI.postScrapers, request, &checker) } }
34.3125
113
0.568913
f826f3d33b7cc044d03af04efd3d66fb74ec4dd4
3,835
// // AppDelegate.swift // MovieViewer // // Created by Dwayne Johnson on 1/29/17. // Copyright © 2017 Dwayne Johnson. 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. window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController //let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! CollectionViewController nowPlayingViewController.endpoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing") let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController //let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController let topRatedViewController = topRatedNavigationController.topViewController as! CollectionViewController topRatedViewController.endpoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() 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:. } }
50.460526
285
0.751499
46bf918876f99464c784b83e999a58e12a217fd5
3,873
/// MIT License /// /// Copyright (c) 2020 Jaesung /// /// 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. // Copyright © 2020 Jaesung Lee. All Rights reserved. import UIKit import AVFoundation class CoverView: UIView { init() { super.init(frame: WWDC.frame) // Set up UI self.backgroundColor = .init(red: 41 / 255, green: 42 / 255, blue: 48 / 255, alpha: 1.0) self.setupGuideUI() self.setupTitleUI() self.setupButton() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented.") } private func setupGuideUI() { let label = newLabel("Tap button to start", font: .preferredFont(forTextStyle: .subheadline)) label.textColor = .gray label.sizeToFit() label.center = CGPoint(x: self.frame.width / 2, y: self.frame.height - 32) label.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] self.addSubview(label) } private func setupTitleUI() { let title1 = newLabel("Taekwondo@Home", font: .boldSystemFont(ofSize: 35)) let title2 = newLabel("Jaesung Lee", font: .boldSystemFont(ofSize: 24)) let title3 = newLabel("Swift Student Challenge", font: .preferredFont(forTextStyle: .headline)) title1.frame = CGRect(x: 0, y: self.frame.height / 2 - 65, width: self.frame.width, height: 36) title2.frame = CGRect(x: 0, y: self.frame.height / 2 - 13, width: self.frame.width, height: 26) title3.frame = CGRect(x: 0, y: self.frame.height / 2 + 40, width: self.frame.width, height: 24) let titles = [title1, title2, title3] titles.forEach { title in title.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] self.addSubview(title) } } private func newLabel(_ text: String, font: UIFont) -> UILabel { let label = UILabel() label.text = text label.textColor = .white label.textAlignment = .center label.font = font return label } private func setupButton() { let button = UIButton() button.setTitle("Let's Learn", for: .normal) button.setTitleColor(.white, for: .normal) button.frame = CGRect(x: self.frame.width / 2 - 100, y: self.frame.height - 150, width: 200, height: 60) button.layer.cornerRadius = 30 button.layer.borderWidth = 2.0 button.layer.borderColor = UIColor.white.cgColor button.addTarget(self, action: #selector(didTapLearn), for: .touchUpInside) button.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin] self.addSubview(button) } @objc func didTapLearn() { WWDC.SwiftStudentChallenge.learnIn3D() } }
38.73
112
0.652982
c1d8ebdae6ea9e2c7d3a44f7020abe695202a1e4
13,196
// // YAxisRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif @objc(ChartYAxisRenderer) open class YAxisRenderer: AxisRendererBase { @objc public init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let xoffset = yAxis.xOffset let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var xPos = CGFloat(0.0) var textAlign: NSTextAlignment if dependency == .left { if labelPosition == .outsideChart { textAlign = .right xPos = viewPortHandler.offsetLeft - xoffset } else { textAlign = .left xPos = viewPortHandler.offsetLeft + xoffset } } else { if labelPosition == .outsideChart { textAlign = .left xPos = viewPortHandler.contentRight + xoffset } else { textAlign = .right xPos = viewPortHandler.contentRight - xoffset } } drawYLabels( context: context, fixedPosition: xPos, positions: transformedPositions(), offset: yoffset - yAxis.labelFont.lineHeight, textAlign: textAlign) if let title = yAxis.title { context.drawText( title, at: CGPoint( x: yAxis.titleFont.lineHeight/2, y: viewPortHandler.offsetTop + (viewPortHandler.contentHeight / 2) ), angleRadians: -.pi/2, attributes: [.font: yAxis.titleFont, .foregroundColor: yAxis.labelTextColor] ) } } open override func renderAxisLine(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if yAxis.axisLineDashLengths != nil { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if yAxis.axisDependency == .left { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position open func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat, textAlign: NSTextAlignment) { guard let yAxis = self.axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1) let xOffset = yAxis.labelXOffset for i in stride(from: from, to: to, by: 1) { let text = yAxis.getFormattedLabel(i) ChartUtils.drawText( context: context, text: text, point: CGPoint(x: fixedPosition + xOffset, y: positions[i].y + offset), align: textAlign, attributes: [.font: labelFont, .foregroundColor: labelTextColor] ) } } open override func renderGridLines(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled { return } if yAxis.drawGridLinesEnabled { let positions = transformedPositions() context.saveGState() defer { context.restoreGState() } context.clip(to: self.gridClippingRect) context.setShouldAntialias(yAxis.gridAntialiasEnabled) context.setStrokeColor(yAxis.gridColor.cgColor) context.setLineWidth(yAxis.gridLineWidth) context.setLineCap(yAxis.gridLineCap) if yAxis.gridLineDashLengths != nil { context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } // draw the grid positions.forEach { drawGridLine(context: context, position: $0) } } if yAxis.drawZeroLineEnabled { // draw zero line drawZeroLine(context: context) } } @objc open var gridClippingRect: CGRect { var contentRect = viewPortHandler.contentRect let dy = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy return contentRect } @objc open func drawGridLine( context: CGContext, position: CGPoint) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.strokePath() } @objc open func transformedPositions() -> [CGPoint] { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return [CGPoint]() } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entryCount) let entries = yAxis.entries for i in stride(from: 0, to: yAxis.entryCount, by: 1) { positions.append(CGPoint(x: 0.0, y: entries[i])) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. @objc open func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0 clippingRect.size.height += yAxis.zeroLineWidth context.clip(to: clippingRect) context.setStrokeColor(zeroLineColor.cgColor) context.setLineWidth(yAxis.zeroLineWidth) let pos = transformer.pixelForValues(x: 0.0, y: 0.0) if yAxis.zeroLineDashLengths != nil { context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: pos.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y)) context.drawPath(using: CGPathDrawingMode.stroke) } open override func renderLimitLines(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return } let limitLines = yAxis.limitLines if limitLines.count == 0 { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .topRight { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .bottomRight { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .topLeft { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } } } context.restoreGState() } }
32.185366
137
0.528493
f88a5d36b64d15e8ee6e6cc410ff60198985e4dd
643
// // BookTableViewCell.swift // LibraryManagementSystem // // Created by Rahul Zore on 4/26/18. // Copyright © 2018 Rahul Zore. All rights reserved. // import UIKit class BookTableViewCell: UITableViewCell { @IBOutlet weak var bookCellView: UIView! @IBOutlet weak var bookTitlelbl: UILabel! @IBOutlet weak var bookSubtitlelbl: UILabel! 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 } }
22.964286
65
0.688958
03cf559eada14a4dae130c8293ed818920052c9f
499
import Foundation public extension String { func ansi(_ ansi: ANSI) -> String { let reset = ANSI.Style(style: .Reset).escapeCode return "\(ansi.escapeCode)\(self)\(reset)" } public func textColor(_ color: ANSIColor) -> String { return self.ansi(.TextColor(color: color)) } public func backgroundColor(_ color: ANSIColor) -> String { return self.ansi(.BackgroundColor(color: color)) } public func style(_ style: ANSIStyle) -> String { return self.ansi(.Style(style: style)) } }
23.761905
60
0.699399
264977ac4de7d52f6a2dacf02350aa1cdb3ee6b5
1,611
// // FireTVManagerExampleViewController.swift // FireTVKit-Example // // Created by crelies on 06.06.2018. // Copyright © 2018 Christian Elies. All rights reserved. // import FireTVKit import RxSwift import UIKit final class FireTVManagerExampleViewController: UIViewController { private var fireTVManager: FireTVManager? private var disposeBag: DisposeBag? @IBOutlet private weak var firstPlayerLabel: UILabel! deinit { print("FireTVManagerExampleViewController deinit") } override func viewDidLoad() { super.viewDidLoad() let disposeBag = DisposeBag() self.disposeBag = disposeBag do { fireTVManager = try FireTVManager() try fireTVManager?.startDiscovery(forPlayerID: "amzn.thin.pl") fireTVManager?.devicesObservable .subscribe(onNext: { [weak self] player in if !player.isEmpty { self?.firstPlayerLabel?.text = player.first?.name() } else { self?.firstPlayerLabel.text = "No player found" } }, onError: { error in print(error) }).disposed(by: disposeBag) } catch { print(error) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) fireTVManager?.stopDiscovery() } @IBAction private func didPressCloseButton(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
27.775862
75
0.590937
671847036606eeaf820e69169bb922bdd9628858
8,046
// // Created by Prashant Dabhi on 08/01/19. // Copyright © 2019 Prashant Dabhi. All rights reserved. // import UIKit import CommonCrypto public typealias Parameters = [String: Any] //public typealias SimpleClickHandler = (() -> Void) public enum HttpMethod : String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } extension Data { mutating func append(string: String) { if let data = string.data(using: .utf8) { append(data) } } func toUTF8String() -> String { return String(data: self, encoding: .utf8) ?? "" } func printUTF8() { print("----- Data String UTF8 -----") print(self.toUTF8String()) } func makeSHA256(header key: String) -> String { guard let jsonData = try? JSONSerialization.jsonObject(with: self, options: .allowFragments), let jsonObject = jsonData as? Parameters else { //fatalError("Wrong Json") return "" } return jsonObject.makeSHA256(headerKey: key) } } extension Data { private static let mimeTypeSignatures: [UInt8 : String] = [ 0xFF : "image/jpeg", 0x89 : "image/png", 0x47 : "image/gif", 0x49 : "image/tiff", 0x4D : "image/tiff", 0x25 : "application/pdf", 0xD0 : "application/vnd", 0x46 : "text/plain", ] var mimeType: String { var c: UInt8 = 0 copyBytes(to: &c, count: 1) return Data.mimeTypeSignatures[c] ?? "application/octet-stream" } } extension APIManager { func mergeCommonParameters(_ param : Parameters, apiManagerProperties: APIManagerPropertySet) -> Parameters { var returnValue : Parameters = apiManagerProperties.getProperty(of: APIManagerProperty.commonParameters, parsingType: Parameters.self) ?? Parameters() returnValue.merge(dict: param) return returnValue } } extension URLResponse { var httpStatusCode: Int? { return (self as? HTTPURLResponse)?.statusCode } func printFailureLogs() { print("----- Failure Request Logs-----") print("Request URL: \(String(describing: self.url))") print("Code: \(self.httpStatusCode ?? 0)") print("----------") } } extension String { func ccSha256(header key: String) -> String{ var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, self, self.count, &digest) let data = Data(bytes: digest) return data.map { String(format: "%02hhx", $0) }.joined() } private func hexStringFromData(input: NSData) -> String { var bytes = [UInt8](repeating: 0, count: input.length) input.getBytes(&bytes, length: input.length) var hexString = "" for byte in bytes { hexString += String(format:"%02x", UInt8(byte)) } return hexString } func convertBase64WithRandomCharacters() -> String { let base64String = find10Character() + self.toBase64() + find10Character() return base64String.toBase64() } func parseFromBase64WithRandomCharacters() -> String? { let decodedBase64String: String = String(self.base64Decoded()?.dropFirst(10).dropLast(10) ?? "") return decodedBase64String.base64Decoded() } func base64Decoded() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } fileprivate func find10Character() -> String { let chars1 = "qwe=rtyui=op!lm@n=b#vcxz%=as^dfg&hj=k*lQWE=RTYUIOPL=MNBVCX=ZASDFG=HJKL12=3456=7=89" let array = Array(chars1) var finalString = String() for _ in 0..<10 { let randomChar = array.randomElement() finalString.append(randomChar!) } return finalString } func toBase64() -> String { return Data(self.utf8).base64EncodedString() } func toParameters() -> Parameters? { if let data = self.data(using: .utf8, allowLossyConversion: true), let params = try? JSONSerialization.jsonObject(with: data, options: []) as? Parameters { return params } return nil } } extension Dictionary { mutating func merge(dict: [Key: Value]){ for (k, v) in dict { updateValue(v, forKey: k) } } func toJSONString() -> String { if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: []), let jsonString = String.init(data: jsonData, encoding: .utf8) { return jsonString } return "" } func makeSHA256(headerKey key: String) -> String { guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: []), let jsonString = String.init(data: jsonData, encoding: .utf8) else { //fatalError("Wrong Json") return "" } print("----- SHA256 START -----") print("----- BODY -----") print(jsonString.filter { !"\n\t\r".contains($0) }) let json256 = jsonString.filter { !"\n\t\r".contains($0) }.ccSha256(header: key) print("----- BODY ccSha256 -----") print(json256) print("----- SHA256 END -----") return json256 } func getQueryString() -> String { var data = [String]() for(key, value) in self { data.append(String(describing: key) + "=\(String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "")") } return data.map { String($0) }.joined(separator: "&") } } extension Dictionary where Key == APIManagerProperty, Value == Any? { func getProperty<T>(of propertyKey: APIManagerProperty, parsingType: T.Type) -> T? { switch propertyKey { case .commonParameters: return self[propertyKey] as? T case .headerKey: return self[propertyKey] as? T case .jsonParameterRootKey: return self[propertyKey] as? T case .authorizationValue: return self[propertyKey] as? T case .apiFailureRetryViewParent: return self[propertyKey] as? T case .apiFailureRetryView: return self[propertyKey] as? T case .shouldParformAPIWhenInternetResume: return self[propertyKey] as? T case .defaultContentType: return self[propertyKey] as? T case .shouldShowAPIFailureRetryView: return self[propertyKey] as? T case .shouldShowProgressHUD: return self[propertyKey] as? T case .progressHUDMessage: return self[propertyKey] as? T } } func overrideProperties(from newSet: APIManagerPropertySet?) -> APIManagerPropertySet { guard let newSet = newSet else { return self } var existingSet = self for set in newSet { existingSet[set.key] = set.value } return existingSet } } extension Collection { /// Returns the element at the specified index iff it is within bounds, otherwise nil. subscript (safe index: Index?) -> Element? { guard let index = index else { return nil } return indices.contains(index) ? self[index] : nil } } extension CharacterSet { static let urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed = CharacterSet.urlQueryAllowed allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) return allowed }() }
31.307393
158
0.586875
f4a5537dba8f79f886e3112f3e228edbf38a2960
10,817
import Foundation import UIKit import QuartzCore class DatePickerDialog: UIView { typealias DatePickerCallback = (timer: NSTimeInterval) -> Void /* Consts */ private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50 private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1 private let kDatePickerDialogCornerRadius: CGFloat = 7 private let kDatePickerDialogDoneButtonTag: Int = 1 /* Views */ private var dialogView: UIView! private var titleLabel: UILabel! private var datePicker: UIDatePicker! private var cancelButton: UIButton! private var doneButton: UIButton! /* Vars */ private var defaultTime: NSTimeInterval? private var datePickerMode: UIDatePickerMode? private var callback: DatePickerCallback? /* Overrides */ init() { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) setupView() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(self.dialogView!) } /* Handle device orientation changes */ func deviceOrientationDidChange(notification: NSNotification) { // close() // For now just close it } /* Create the dialog view, and animate opening the dialog */ func show(title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultTime: NSTimeInterval = NSTimeInterval(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: DatePickerCallback) { //此处设置传入参数 self.titleLabel.text = title self.doneButton.setTitle(doneButtonTitle, forState: .Normal) self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal) self.datePickerMode = datePickerMode self.callback = callback self.defaultTime = defaultTime self.datePicker.datePickerMode = self.datePickerMode ?? .Date self.datePicker.countDownDuration = self.defaultTime ?? NSTimeInterval() /* */ UIApplication.sharedApplication().windows.first!.addSubview(self) UIApplication.sharedApplication().windows.first!.endEditing(true) NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil) /* Anim */ UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } /* Dialog close animation then cleaning and removing the view from the parent */ private func close() { NSNotificationCenter.defaultCenter().removeObserver(self) let currentTransform = self.dialogView.layer.transform let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ private func createContainerView() -> UIView { let screenSize = countScreenSize() let dialogSize = CGSizeMake( 300, 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) // For the black background self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor] let cornerRadius = kDatePickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, atIndex: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath // There is a line above the button let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30)) self.titleLabel.textAlignment = NSTextAlignment.Center self.titleLabel.font = UIFont.boldSystemFontOfSize(17) dialogContainer.addSubview(self.titleLabel) self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0)) self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin self.datePicker.frame.size.width = 300 dialogContainer.addSubview(self.datePicker) // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ private func addButtonsToView(container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton self.cancelButton.frame = CGRectMake( 0, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.cancelButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton self.doneButton.frame = CGRectMake( buttonWidth, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.doneButton.tag = kDatePickerDialogDoneButtonTag self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.doneButton) } func buttonTapped(sender: UIButton!) { if sender.tag == kDatePickerDialogDoneButtonTag { self.callback?(timer: self.datePicker.countDownDuration) } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { let screenWidth = UIScreen.mainScreen().applicationFrame.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height return CGSizeMake(screenWidth, screenHeight) } }
47.030435
251
0.647314