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
e40ffe69e61937c5109e9078b3238ae654d6d35d
3,677
// // CoreDataStack.swift // Skincare // // Created by Carolina Ortega on 14/12/21. // // import Foundation import CoreData class CoreDataStack { static let shared: CoreDataStack = CoreDataStack() private init() {} // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Model") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } // MARK: - Core Data Getting support func getAllRoutines() -> [Routine] { let fr = NSFetchRequest<Routine>(entityName: "Routine") do { return try self.persistentContainer.viewContext.fetch(fr) } catch { print(error) } return [] } // MARK: - Core Data Creating support func createRoutine(routineName: String, dataEnd: Date, dataStart: Date, seg: Bool, ter: Bool, qua: Bool, qui: Bool, sex: Bool, sab: Bool, dom: Bool) -> Routine { let routine = Routine(context: self.persistentContainer.viewContext) routine.routineName = routineName routine.dataEnd = dataEnd routine.dataStart = dataStart routine.seg = seg routine.ter = ter routine.qua = qua routine.qui = qui routine.sex = sex routine.sab = sab routine.dom = dom self.saveContext() return routine } // MARK: - Core Data deleting support func deleteObject(routine: Routine) { self.persistentContainer.viewContext.delete(routine) self.saveContext() } }
36.77
199
0.60892
0ec18aab59a3eb2988c3c37c1173c55ca18df404
407
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import flutter_secure_storage_macos import geolocator_apple func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlutterSecureStorageMacosPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageMacosPlugin")) GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin")) }
27.133333
114
0.832924
1d9ec5bbf6e1bff28f96570c5ade2b1c3da898c7
1,259
// // AddressNavigation.swift // SharedImages // // Created by Christopher G Prince on 4/6/19. // Copyright © 2019 Spastic Muffin, LLC. All rights reserved. // import Foundation import CoreLocation import UIKit import MapKit import iOSShared class AddressNavigation { let geocoder = CLGeocoder() func navigate(to address: String) { geocoder.geocodeAddressString(address) { placemarks, error in if let error = error { logger.error("\(error)") showAlert(AlertyHelper.alert(title: "Alert!", message: "Could not lookup address.")) return } guard let placemarks = placemarks, placemarks.count > 0 else { showAlert(AlertyHelper.alert(title: "Alert!", message: "Problem looking up address.")) return } let mapItems = placemarks.map { MKMapItem(placemark: MKPlacemark(placemark: $0)) } guard MKMapItem.openMaps(with: mapItems, launchOptions: nil) else { showAlert(AlertyHelper.alert(title: "Alert!", message: "Could not open maps app.")) return } } } }
29.97619
102
0.566322
dbcc0f83efbbbb450294637fb43bd8877469f041
404
// // MoedaRequest.swift // ModCommons // // Created by Leonardo Oliveira Portes on 14/04/21. // import Foundation public struct ApiRest { public static let TodasAsMoedas = "http://rest-sandbox.coinapi.io/v1/assets?apikey=1F8A5E86-F1C9-41C7-B8BB-9DB1B81FDE7C" public static let MoedaDetalhe = "http://rest-sandbox.coinapi.io/v1/assets/@@@?apikey=1F8A5E86-F1C9-41C7-B8BB-9DB1B81FDE7C" }
23.764706
126
0.732673
9cde0a265baec3a242975c1c9671cdb736dc6ff5
1,200
/* The MIT License (MIT) Copyright (c) 2016-2020 The Contributors 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 protocol Themeable { var theme : Theme! { get set } }
37.5
79
0.7725
4af73810028a7ef446a98e2762396560b3f458f9
1,904
// // allPass.swift // Ramda // // Created by TYRONE AVNIT on 2019/08/29. // import Foundation extension R { /** Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments. - parameter predicates: An array of predicates to check - returns: Bool */ public class func allPassK<T>(_ predicates: [(T) -> Bool], _ list: [T]) -> Bool { let fn = apply(predicates.compactMap(R.all)) return fn(list).filter(not).count == 0 } /** Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments. - parameter predicates: An array of predicates to check - returns: Curried function */ public class func allPassK<T>(_ predicates: [(T) -> Bool]) -> ([T]) -> Bool { return curry(allPassK)(predicates) } /** Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments. - parameter predicates: An array of predicates to check - returns: Bool */ public class func allPass<T>(_ predicates: [(T) -> Bool], _ arg: T) -> Bool { let fn = apply(predicates) return fn(arg).filter(not).count == 0 } /** Takes a list of predicates and returns a predicate that returns true for a given list of arguments if every one of the provided predicates is satisfied by those arguments. - parameter predicates: An array of predicates to check - returns: Curried function */ public class func allPass<T>(_ predicates: [(T) -> Bool]) -> (T) -> Bool { return curry(allPass)(predicates) } }
25.386667
93
0.648109
4be64043155ce2204f1b19ecc862870707dc3305
6,748
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://jessesquires.com/DefaultStringConvertible // // // GitHub // https://github.com/jessesquires/DefaultStringConvertible // // // License // Copyright © 2016 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // /** A better default implementation of `description`. Displays the type name followed by all members with labels. */ public extension CustomStringConvertible { /// Constructs and returns a detailed description of the receiver via its `Mirror`. public var defaultDescription: String { return generateDefaultDescription(self) } /// Constructs and returns a recursive description of the receiver, similar to a Playgrounds sidebar description. public var deepDescription: String { return generateDeepDescription(self) } /// Returns the value from `defaultDescription`. public var description: String { return defaultDescription } } private func generateDefaultDescription(_ any: Any) -> String { let mirror = Mirror(reflecting: any) var children = Array(mirror.children) var superclassMirror = mirror.superclassMirror repeat { if let superChildren = superclassMirror?.children { children.append(contentsOf: superChildren) } superclassMirror = superclassMirror?.superclassMirror } while superclassMirror != nil let chunks = children.map { (label: String?, value: Any) -> String in if let label = label { if value is String { return "\(label): \"\(value)\"" } return "\(label): \(value)" } return "\(value)" } if chunks.count > 0 { let chunksString = chunks.joined(separator: ", ") return "\(mirror.subjectType)(\(chunksString))" } return "\(type(of: any))" } private func generateDeepDescription(_ any: Any) -> String { func indentedString(_ string: String) -> String { return string.characters .split(separator: "\r") .map(String.init) .map { $0.isEmpty ? "" : "\r \($0)" } .joined(separator: "") } func deepUnwrap(_ any: Any) -> Any? { let mirror = Mirror(reflecting: any) if mirror.displayStyle != .optional { return any } if let child = mirror.children.first , child.label == "some" { return deepUnwrap(child.value) } return nil } guard let any = deepUnwrap(any) else { return "nil" } if any is Void { return "Void" } if let int = any as? Int { return String(int) } else if let double = any as? Double { return String(double) } else if let float = any as? Float { return String(float) } else if let bool = any as? Bool { return String(bool) } else if let string = any as? String { return "\"\(string)\"" } let mirror = Mirror(reflecting: any) var properties = Array(mirror.children) var typeName = String(describing: mirror.subjectType) if typeName.hasSuffix(".Type") { typeName = "" } else { typeName = "<\(typeName)> " } guard let displayStyle = mirror.displayStyle else { return "\(typeName)\(String(describing: any))" } switch displayStyle { case .tuple: if properties.isEmpty { return "()" } var string = "(" for (index, property) in properties.enumerated() { if property.label!.characters.first! == "." { string += generateDeepDescription(property.value) } else { string += "\(property.label!): \(generateDeepDescription(property.value))" } string += (index < properties.count - 1 ? ", " : "") } return string + ")" case .collection, .set: if properties.isEmpty { return "[]" } var string = "[" for (index, property) in properties.enumerated() { string += indentedString(generateDeepDescription(property.value) + (index < properties.count - 1 ? ",\r" : "")) } return string + "\r]" case .dictionary: if properties.isEmpty { return "[:]" } var string = "[" for (index, property) in properties.enumerated() { let pair = Array(Mirror(reflecting: property.value).children) string += indentedString("\(generateDeepDescription(pair[0].value)): \(generateDeepDescription(pair[1].value))" + (index < properties.count - 1 ? ",\r" : "")) } return string + "\r]" case .enum: if let any = any as? CustomDebugStringConvertible { return any.debugDescription } if properties.isEmpty { return "\(mirror.subjectType)." + String(describing: any) } var string = "\(mirror.subjectType).\(properties.first!.label!)" let associatedValueString = generateDeepDescription(properties.first!.value) if associatedValueString.characters.first! == "(" { string += associatedValueString } else { string += "(\(associatedValueString))" } return string case .struct, .class: if let any = any as? CustomDebugStringConvertible { return any.debugDescription } var superclassMirror = mirror.superclassMirror repeat { if let superChildren = superclassMirror?.children { properties.append(contentsOf: superChildren) } superclassMirror = superclassMirror?.superclassMirror } while superclassMirror != nil if properties.isEmpty { return "\(typeName)\(String(describing: any))" } var string = "\(typeName){" for (index, property) in properties.enumerated() { string += indentedString("\(property.label!): \(generateDeepDescription(property.value))" + (index < properties.count - 1 ? ",\r" : "")) } return string + "\r}" case .optional: return generateDefaultDescription(any) } } // Since these methods are not available in Linux #if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) /// :nodoc: extension String { /// :nodoc: public func hasPrefix(_ prefix: String) -> Bool { return prefix == String(characters.prefix(prefix.characters.count)) } /// :nodoc: public func hasSuffix(_ suffix: String) -> Bool { return suffix == String(characters.suffix(suffix.characters.count)) } } #endif
29.086207
148
0.587582
0e08985dff12b8c99e522018dd984426e6867824
9,548
// // HCLocationManager.swift // // Created by Hypercube on 10/6/17. // Copyright © 2017 Hypercube. All rights reserved. // import Foundation import CoreLocation import HCFramework /// Struct with static variables used as names for NotificationCenter for specific events public struct HCLocationManagerNotification { // MARK: Notification names /// Notification name for notification when location is updated public static let locationUpdated = "HCLocationUpdated" /// Notification name for notification whem authorization status is changed public static let authorizationStatusChanged = "HCAuthorizationStatusChanged" } /// HCLocationManager class used for handle some operations with user's location open class HCLocationManager: NSObject, CLLocationManagerDelegate { // MARK: Basic properties /// CLLocationManager instance private var locationManager: CLLocationManager = CLLocationManager() /// Boolean value which indicates if tracking location is enabled private var isTrackingLocation: Bool = false // MARK: - Shared instance /// Shared (singleton instance) open static let sharedManager: HCLocationManager = { let instance = HCLocationManager() instance.locationManager.delegate = instance return instance }() // MARK: - Authorization /// Request Always Authorization open func requestAlwaysAuthorization() { locationManager.requestAlwaysAuthorization() } /// Request When In Use Authorization open func requestWhenInUseAuthorization() { locationManager.requestWhenInUseAuthorization() } /// Returns whether the application is authorized for the location or not /// /// - Returns: Whether the application is authorized for the location or not open func isAppAutorized() -> Bool { let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus() if status == CLAuthorizationStatus.authorizedAlways || status == CLAuthorizationStatus.authorizedWhenInUse { return true } else { return false } } /// Returns whether the application is always authorized for the location or not /// /// - Returns: Whether the application is always authorized for the location or not open func isAppAlwaysAutorized() -> Bool { let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus() if status == CLAuthorizationStatus.authorizedAlways { return true } else { return false } } /// Returns whether the application is when in use authorized for the location or not /// /// - Returns: Whether the application is when in use authorized for the location or not open func isAppWhenInUseAutorized() -> Bool { let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus() if status == CLAuthorizationStatus.authorizedWhenInUse { return true } else { return false } } // MARK: - Location and Distance /// Configure locationManager object, start updating location, and request for permissions if needed. open func startTrackingLocation(allowsBackgroundLocation: Bool = false) { if !isTrackingLocation { locationManager.requestLocation() locationManager.requestWhenInUseAuthorization() if allowsBackgroundLocation { locationManager.requestAlwaysAuthorization() locationManager.allowsBackgroundLocationUpdates = allowsBackgroundLocation } locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager.startUpdatingLocation() isTrackingLocation = true } } /// Stop updating location open func stopTrackingLocation() { if isTrackingLocation { locationManager.stopUpdatingLocation() isTrackingLocation = false } } /// Return user Current Location /// /// - Returns: Current location open func getCurrentLocation() -> CLLocation? { if let currentLocation = locationManager.location { return currentLocation } else { return nil } } /// Calculate distance for current to specified location. /// /// - Parameters: /// - location: Target location /// - inMiles: Whether the distance returns in miles. Default value is false. /// - Returns: Distance form current to target location open func getDistanceFromCurrentLocation(toLocation location: CLLocation?, inMiles: Bool = false) -> Double? { if let toLocation = location { if let currentLocation = locationManager.location { let distance = currentLocation.distance(from: toLocation) if inMiles { return distance } else { return distance*0.621371 } } else { return nil } } else { return nil } } /// Calculate distance for fromLocation to specified toLocation. /// /// - Parameters: /// - from: Start Locatiom /// - to: Target location /// - inMiles: Whether the distance returns in miles. Default value is false. /// - Returns: Distance form start to target location open func getDistance(fromLocation from: CLLocation?, toLocation to: CLLocation?, inMiles: Bool = false) -> Double? { if let toLocation = to { if let fromLocation = from { let distance = toLocation.distance(from: fromLocation) if inMiles { return distance } else { return distance*0.621371 } } else { return nil } } else { return nil } } /// Get detailed information about user's location (country, city, street,...) /// /// - Parameter completion: Completion handler which will be executed when and if detailed informations about user's location are fetched open func getAdress(completion: @escaping ([CLPlacemark]) -> ()) { if CLLocationManager.locationServicesEnabled() { switch(CLLocationManager.authorizationStatus()) { case .notDetermined, .restricted, .denied: print("No access") case .authorizedAlways, .authorizedWhenInUse: print("Access") locationManager.requestWhenInUseAuthorization() if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){ if let currentLocation = locationManager.location { self.getAddress(location: currentLocation, completion: completion) } } } } else { print("Location services are not enabled") } } /// Get detailed informations (country, city, address,..) about given location /// /// - Parameters: /// - location: Location for which we need detailed informations /// - completion: Completion handler which will be executed when and if detailed informations about given location are fetched open func getAddress(location:CLLocation, completion: @escaping ([CLPlacemark]) -> ()) { let geoCoder = CLGeocoder() geoCoder.reverseGeocodeLocation(location) { (placemarks, error) -> Void in if error != nil { print("Error getting location: \(error?.localizedDescription ?? "No description")") completion([]) } else { if let placemarks = placemarks { completion(placemarks) } } } } // MARK: - Location Manager Delegate public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let myCurrentLocation: CLLocation = locations.first! // Inform all about location update event. Observe this event to collect most recently retrieved user location. HCAppNotify.postNotification(HCLocationManagerNotification.locationUpdated, object: myCurrentLocation) } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("HCLocationManager ERROR : \(error.localizedDescription)") } public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { // Inform all about Authorization Status Change event. Observe this event to register Authorization Status Change event. HCAppNotify.postNotification(HCLocationManagerNotification.authorizationStatusChanged, object: status as AnyObject) } }
34.222222
141
0.613113
28096bc90b1729fa3b71cd435b54c21340418687
746
// // BaseTableViewDelegate.swift // base-app-ios // // Created by Roberto Frontado on 2/17/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import UIKit public class BaseTableViewDelegate<T: BaseViewDataSource, U: BaseTableViewPresenter where T.ItemType == U.ItemType>: NSObject, UITableViewDelegate { private let dataSource: T private let presenter: U public init(dataSource: T, presenter: U) { self.dataSource = dataSource self.presenter = presenter } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = dataSource.itemAtIndexPath(indexPath) presenter.onItemClick(item, position: indexPath.row) } }
29.84
148
0.713137
ab924572076e38a00a9925077b7427708096c121
4,437
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation extension AVAudioSequencer: Collection { /// This is a collection of AVMusicTracls, so we define element as such public typealias Element = AVMusicTrack /// Index by an integer public typealias Index = Int /// Start Index public var startIndex: Index { return 0 } /// Ending index public var endIndex: Index { return count } /// Look up by subscript public subscript(index: Index) -> Element { return tracks[index] } /// Next index /// - Parameter index: Current Index /// - Returns: Next index public func index(after index: Index) -> Index { return index + 1 } /// Rewind the sequence public func rewind() { currentPositionInBeats = 0 } } /// Simple MIDI Player based on Apple's AVAudioSequencer which has limited capabilities public class MIDIPlayer: AVAudioSequencer { /// Tempo in beats per minute public var tempo: Double = 120.0 /// Loop control public var loopEnabled: Bool = false /// Initialize the sequence with a MIDI file /// /// - parameter filename: Location of the MIDI File /// - parameter audioEngine: AVAudioEngine to associate with /// public init(audioEngine: AVAudioEngine, filename: String) { super.init(audioEngine: audioEngine) loadMIDIFile(filename) } /// Load a sequence from data /// /// - parameter data: data to create sequence from /// public func sequence(from data: Data) { do { try load(from: data, options: []) } catch { Log("cannot load from data \(error)") return } } /// Set loop functionality of entire sequence public func toggleLoop() { (loopEnabled ? disableLooping() : enableLooping()) } /// Enable looping for all tracks - loops entire sequence public func enableLooping() { enableLooping(length) } /// Enable looping for all tracks with specified length /// /// - parameter loopLength: Loop length in beats /// public func enableLooping(_ loopLength: Duration) { forEach { $0.isLoopingEnabled = true $0.loopRange = AVMakeBeatRange(0, loopLength.beats) } loopEnabled = true } /// Disable looping for all tracks public func disableLooping() { forEach { $0.isLoopingEnabled = false } loopEnabled = false } /// Length of longest track in the sequence public var length: Duration { get { let l = lazy.map { $0.lengthInBeats }.max() ?? 0 return Duration(beats: l, tempo: tempo) } set { forEach { $0.lengthInBeats = newValue.beats $0.loopRange = AVMakeBeatRange(0, newValue.beats) } } } /// Play the sequence public func play() { do { try start() } catch _ { Log("Could not start the sequencer") } } /// Set the Audio Unit output for all tracks - on hold while technology is still unstable public func setGlobalAVAudioUnitOutput(_ audioUnit: AVAudioUnit) { forEach { $0.destinationAudioUnit = audioUnit } } /// Current Time public var currentPosition: Duration { return Duration(beats: currentPositionInBeats) } /// Current Time relative to sequencer length public var currentRelativePosition: Duration { return currentPosition % length //can switch to modTime func when/if % is removed } /// Load a MIDI file /// - Parameter filename: MIDI FIle name public func loadMIDIFile(_ filename: String) { guard let file = Bundle.main.path(forResource: filename, ofType: "mid") else { return } let fileURL = URL(fileURLWithPath: file) do { try load(from: fileURL, options: []) } catch _ { Log("failed to load MIDI into sequencer") } } /// Set the midi output for all tracks /// - Parameter midiEndpoint: MIDI Endpoint public func setGlobalMIDIOutput(_ midiEndpoint: MIDIEndpointRef) { forEach { $0.destinationMIDIEndpoint = midiEndpoint } } }
26.890909
100
0.600406
ab30fffba14a80cb8350bde72a5dbdbd54131b48
7,900
import UIKit extension UIScrollView { public func setStyle(_ style: ScrollViewStyle) { _ = style.style(self) } } public protocol ScrollViewStyleCompatability { static func contentSize(_ value: CGSize) -> Self static func contentOffset(_ value: CGPoint, animated: Bool) -> Self // static func contentInsetAdjustmentBehavior(_ value: UIScrollView.ContentInsetAdjustmentBehavior) -> Self static func isScrollEnabled(_ value: Bool) -> Self static func isDirectionalLockEnabled(_ value: Bool) -> Self static func isPagingEnabled(_ value: Bool) -> Self static func scrollsToTop(_ value: Bool) -> Self static func bounces(_ value: Bool) -> Self static func alwaysBounceVertical(_ value: Bool) -> Self static func alwaysBounceHorizontal(_ value: Bool) -> Self static func decelerationRate(_ value: UIScrollView.DecelerationRate) -> Self static func indicatorStyle(_ value: UIScrollView.IndicatorStyle) -> Self static func scrollIndicatorInsets(_ value: UIEdgeInsets) -> Self static func showsHorizontalScrollIndicator(_ value: Bool) -> Self static func showsVerticalScrollIndicator(_ value: Bool) -> Self static func refreshControl(_ value: UIRefreshControl) -> Self static func canCancelContentTouches(_ value: Bool) -> Self static func delaysContentTouches(_ value: Bool) -> Self static func zoom(to value: CGRect, _ animated: Bool) -> Self static func maximumZoomScale(_ value: CGFloat) -> Self static func minimumZoomScale(_ value: CGFloat) -> Self static func bouncesZoom(_ value: Bool) -> Self static func keyboardDismissMode(_ value: UIScrollView.KeyboardDismissMode) -> Self static func indexDisplayMode(_ value: UIScrollView.IndexDisplayMode) -> Self } public struct ScrollViewStyle: StyleProtocol, ViewStyleCompatability, ScrollViewStyleCompatability { public typealias ViewType = UIScrollView public let style: Style public init(style: @escaping Style) { self.style = style } } extension ScrollViewStyleCompatability where Self: StyleProtocol, Self.ViewType: UIScrollView { // MARK: UIScrollView public static func contentSize(_ value: CGSize) -> Self { return Self.init(style: { scrollView in scrollView.contentSize = value return scrollView }) } public static func contentOffset(_ value: CGPoint, animated: Bool = false) -> Self { return Self.init(style: { scrollView in scrollView.setContentOffset(value, animated: animated) return scrollView }) } public static func contentInset(_ value: UIEdgeInsets) -> ScrollViewStyle { return ScrollViewStyle(style: { scrollView in scrollView.contentInset = value return scrollView }) } // @available(iOS 11.0, *) // public static func contentInsetAdjustmentBehavior(_ value: UIScrollView.ContentInsetAdjustmentBehavior) -> Self { // return Self.init(style: { scrollView in // scrollView.contentInsetAdjustmentBehavior = value // return scrollView // }) // } public static func isScrollEnabled(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.isScrollEnabled = value return scrollView }) } public static func isDirectionalLockEnabled(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.isDirectionalLockEnabled = value return scrollView }) } public static func isPagingEnabled(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.isPagingEnabled = value return scrollView }) } public static func scrollsToTop(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.scrollsToTop = value return scrollView }) } public static func bounces(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.bounces = value return scrollView }) } public static func alwaysBounceVertical(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.alwaysBounceVertical = value return scrollView }) } public static func alwaysBounceHorizontal(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.alwaysBounceHorizontal = value return scrollView }) } public static func decelerationRate(_ value: UIScrollView.DecelerationRate) -> Self { return Self.init(style: { scrollView in scrollView.decelerationRate = value return scrollView }) } public static func indicatorStyle(_ value: UIScrollView.IndicatorStyle) -> Self { return Self.init(style: { scrollView in scrollView.indicatorStyle = value return scrollView }) } public static func scrollIndicatorInsets(_ value: UIEdgeInsets) -> Self { return Self.init(style: { scrollView in scrollView.scrollIndicatorInsets = value return scrollView }) } public static func showsHorizontalScrollIndicator(_ value: Bool) -> Self { return Self(style: { scrollView in scrollView.showsHorizontalScrollIndicator = value return scrollView }) } public static func showsVerticalScrollIndicator(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.showsVerticalScrollIndicator = value return scrollView }) } public static func refreshControl(_ value: UIRefreshControl) -> Self { return Self.init(style: { scrollView in scrollView.refreshControl = value return scrollView }) } public static func canCancelContentTouches(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.canCancelContentTouches = value return scrollView }) } public static func delaysContentTouches(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.delaysContentTouches = value return scrollView }) } public static func zoom(to value: CGRect, _ animated: Bool = false) -> Self { return Self.init(style: { scrollView in scrollView.zoom(to: value, animated: animated) return scrollView }) } public static func maximumZoomScale(_ value: CGFloat) -> Self { return Self.init(style: { scrollView in scrollView.maximumZoomScale = value return scrollView }) } public static func minimumZoomScale(_ value: CGFloat) -> Self { return Self.init(style: { scrollView in scrollView.minimumZoomScale = value return scrollView }) } public static func bouncesZoom(_ value: Bool) -> Self { return Self.init(style: { scrollView in scrollView.bouncesZoom = value return scrollView }) } public static func keyboardDismissMode(_ value: UIScrollView.KeyboardDismissMode) -> Self { return Self.init(style: { scrollView in scrollView.keyboardDismissMode = value return scrollView }) } public static func indexDisplayMode(_ value: UIScrollView.IndexDisplayMode) -> Self { return Self.init(style: { scrollView in scrollView.indexDisplayMode = value return scrollView }) } }
34.801762
119
0.637468
91104c699d37388eda8526db474ca52bfb8963ea
3,882
// // ViewController.swift // FolderSHA // // Created by CHENWANFEI on 26/03/2018. // Copyright © 2018 swordfish. All rights reserved. // import Cocoa extension NSTextView { func append(string: String) { self.textStorage?.append(NSAttributedString(string: string)) self.scrollToEndOfDocument(nil) } } class ViewController: NSViewController { @IBOutlet weak var fileSelectionBtn: NSButton! @IBOutlet var textView: NSTextView! @IBOutlet weak var nodesTF: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func sha256(data : Data) -> Data { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA256($0, CC_LONG(data.count), &hash) } return Data(bytes: hash) } private func isFolder(url:URL) -> Bool{ var isDir : ObjCBool = false let fm = FileManager.default if fm.fileExists(atPath: url.path, isDirectory:&isDir) { return isDir.boolValue; } else { return false; } } private func handleSingleFile(url:URL){ if let data = try? Data(contentsOf: url){ var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } let hexBytes = digest.map { String(format: "%02hhx", $0) } let hexString = hexBytes.joined() let s = url.path + " => " + hexString + "\n"; DispatchQueue.main.async { [weak self] in self?.textView.append(string: s); } } } private func handleFolder(url:URL){ if isFolder(url: url) { if let urls = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles){ for u in urls{ handleFolder(url:u); } } }else{ handleSingleFile(url: url); } } @IBAction func onOpenFile(_ sender: Any) { let dialog = NSOpenPanel(); dialog.title = "Choose a file/folder"; dialog.showsResizeIndicator = true; dialog.showsHiddenFiles = false; dialog.canChooseDirectories = true; dialog.canCreateDirectories = true; dialog.allowsMultipleSelection = false; if (dialog.runModal() == NSApplication.ModalResponse.OK) { if let result = dialog.url { self.nodesTF.stringValue = result.path; self.textView.string = ""; self.view.window?.title = "Proccessing"; self.fileSelectionBtn.isEnabled = false; DispatchQueue.global(qos: .background).async {[weak self] in // Background Thread self?.handleFolder(url: result); DispatchQueue.main.async { self?.view.window?.title = "Done"; self?.fileSelectionBtn.isEnabled = true; // Run UI Updates or call completion block } } } } else { // User clicked on "Cancel" return } } }
28.130435
181
0.511592
abe660235e345e11f8e63bb863436c6aebc4ec3b
189
// // Note.swift // MIDIKit • https://github.com/orchetect/MIDIKit // extension MIDI.Event { /// Channel Voice Message: Note events public enum Note { } }
13.5
50
0.566138
48ec13999ee790127258ca91cb4a89e3ed3863ae
257
// // TabBarState.swift // GeekMadeBySwiftUI // // Created by OFweek01 on 2021/5/20. // Copyright © 2021 xgf. All rights reserved. // import SwiftUI // TabBarState.swift class TabBarState: ObservableObject { @Published var hidden : Bool = false }
18.357143
46
0.700389
1c22dc3f968bda548ae6db24a169507ebb959f82
1,413
// // AppDelegate.swift // tippy2 // // Created by Adriana Meza on 4/4/20. // Copyright © 2020 Adriana Meza. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.184211
179
0.746638
14e4c9c04200ac0d4ce5d6fb53bcf721fb3d24fd
1,789
// // Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved // import UIKit import AGConnectAppLinking class ViewController: UIViewController { @IBOutlet weak var shortLink: UILabel! @IBOutlet weak var longLink: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func create(_ sender: Any) { let components = AGCAppLinkingComponents() components.uriPrefix = "https://example.drcn.agconnect.link" components.deepLink = "https://www.example.com" components.iosBundleId = Bundle.main.bundleIdentifier components.iosDeepLink = "example://ios/detail" components.androidDeepLink = "example://android/detail" components.androidPackageName = "com.android.demo" components.campaignName = "name" components.campaignMedium = "App" components.campaignSource = "AGC" components.socialTitle = "Title" components.socialImageUrl = "https://example.com/1.png" components.socialDescription = "Description" longLink.text = components.buildLongLink().absoluteString components.buildShortLink { (shortLink, error) in if let e = error { print(e) return } self.shortLink.text = shortLink?.url.absoluteString } } @IBAction func openShortLink(_ sender: Any) { if let url = URL(string: self.shortLink.text ?? "") { UIApplication.shared.open(url) } } @IBAction func openLongLink(_ sender: Any) { if let url = URL(string: self.longLink.text ?? "") { UIApplication.shared.open(url) } } }
31.385965
73
0.622135
1e1dd76926f1d208d2512c4332db5e3f08f5b796
2,521
// // ZJServiceAccountBookViewModel.swift // LittleBlackBear // // Created by MichaelChan on 29/3/18. // Copyright © 2018年 蘇崢. All rights reserved. // import UIKit import SwiftyJSON import RxSwift class ZJServiceAccountBookViewModel: SNBaseViewModel { var reloadDataPub = PublishSubject<(Int,String)>() var model : ZJServiceAccountJsonModel?{ didSet{ self.reloadDataPub.onNext((model!.list.count,model!.total)) } } func getData(){ SNRequest(requestType: API.serviceAccountBook(mer_id: LBKeychain.get(CURRENT_MERC_ID)), modelType: ZJServiceAccountJsonModel.self).subscribe(onNext: { (result) in switch result{ case .success(let model): self.model = model case .fail: SZHUD("获取收益失败", type: .error, callBack: nil) default: return } }).disposed(by: disposeBag) } } extension ZJServiceAccountBookViewModel : UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : ZJMerchantAccountBookCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.model = model!.list[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model == nil ? 0 : model!.list.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return fit(154) } } class ZJServiceAccountJsonModel : SNSwiftyJSONAble{ var total : String var list : [ZJMerchantAccoutBookModel] required init?(jsonData: JSON) { total = jsonData["total"].stringValue list = jsonData["list"].arrayValue.map({return ZJMerchantAccoutBookModel(jsonData: $0)!}) } } //class ZJServiceAccountCellModel : SNSwiftyJSONAble{ // var pass_pay : String // var merchant_money : String // var pay_id : String // var add_time : String // var payTotal : String // var name : String // // required init?(jsonData: JSON) { // pass_pay = jsonData["pass_pay"].stringValue // merchant_money = jsonData["merchant_money"].stringValue // pay_id = jsonData["pay_id"].stringValue // add_time = jsonData["add_time"].stringValue // payTotal = jsonData["payTotal"].stringValue // name = jsonData["name"].stringValue // } // //}
31.911392
170
0.651726
f558abd6a94dd1481c8c46d9c81e61d573226a88
109
import XCTest @testable import PerfectJWTAuthTests XCTMain([ testCase(PerfectJWTAuthTests.allTests), ])
15.571429
43
0.798165
380e02e2f1779cc2e47ca28ab2adbd00871b6224
3,278
// // SSReaderTheme.swift // SSReaderDemo // // Created by yangsq on 2021/8/10. // import Foundation import UIKit public protocol SSReaderTheme { var contentBackgroudColor: UIColor? { get } var contentTextColor: UIColor? { get } var toolBackgroudColor: UIColor? { get } var toolControlTextColor: UIColor? { get } var toolControlBorderUnSelectColor: UIColor? { get } var toolLineColor: UIColor? { get } } struct WhiteTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor.white var contentTextColor: UIColor? = UIColor.black var toolBackgroudColor: UIColor? = UIColor.white var toolControlTextColor: UIColor? = UIColor.black var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) } struct DarkTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor.black var contentTextColor: UIColor? = UIColor.white var toolBackgroudColor: UIColor? = UIColor.black var toolControlTextColor: UIColor? = UIColor.white var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) } struct YellowTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor(red: 0.89, green: 0.87, blue: 0.79, alpha: 1) var contentTextColor: UIColor? = UIColor.black var toolBackgroudColor: UIColor? = UIColor(red: 0.89, green: 0.87, blue: 0.79, alpha: 1) var toolControlTextColor: UIColor? = UIColor.black var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) } struct GreenTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor(red: 0.87, green: 0.91, blue: 0.82, alpha: 1) var contentTextColor: UIColor? = UIColor.black var toolBackgroudColor: UIColor? = UIColor(red: 0.87, green: 0.91, blue: 0.82, alpha: 1) var toolControlTextColor: UIColor? = UIColor.black var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) } struct PinkTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor(red: 1, green: 0.89, blue: 0.91, alpha: 1) var contentTextColor: UIColor? = UIColor.black var toolBackgroudColor: UIColor? = UIColor(red: 1, green: 0.89, blue: 0.91, alpha: 1) var toolControlTextColor: UIColor? = UIColor.black var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) } struct BlueTheme: SSReaderTheme { var contentBackgroudColor: UIColor? = UIColor(red: 0.8, green: 0.84, blue: 0.89, alpha: 1) var contentTextColor: UIColor? = UIColor.black var toolBackgroudColor: UIColor? = UIColor(red: 0.8, green: 0.84, blue: 0.89, alpha: 1) var toolControlTextColor: UIColor? = UIColor.black var toolControlBorderUnSelectColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) var toolLineColor: UIColor? = UIColor.lightGray.withAlphaComponent(0.5) }
43.131579
95
0.742526
461923186f289df9af9d890cda28b14162b15aa2
482
// // UserActionResponse.swift // FusionAuth Swift Client // // Created by Everaldlee Johnson on 12/11/18. // Copyright © 2018 F0rever_Johnson. All rights reserved. // import Foundation public struct UserActionResponse:Codable { public var userAction:UserAction? public var userActions:[UserAction]? public init(userAction: UserAction? = nil, userActions: [UserAction]? = nil) { self.userAction = userAction self.userActions = userActions } }
24.1
82
0.709544
b9ee3dcafde20beca33d421ecd0fb7dca610764f
1,307
import XCTest @testable import FuzzCheck class FuzzerTests: XCTestCase { func testWeightedPick() { var r = FuzzerPRNG.init(seed: 0) var weights: [UInt64] = Array.init() for i in 0 ..< 10 { weights.append(UInt64(i)) } let cumulativeWeights = [1, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20].enumerated().map { ($0.0, $0.1) } // print(weights) print(cumulativeWeights.map { $0.1 }) var timesChosen = cumulativeWeights.map { _ in 0 } for _ in 0 ..< 100_000 { timesChosen[r.weightedRandomElement(from: cumulativeWeights, minimum: 0)] += 1 } print(timesChosen) } func testRandom() { var r = FuzzerPRNG(seed: 2) var timesChosen = Array.init(repeating: 0, count: 128) for _ in 0 ..< 1_000_000 { let i = Int.random(in: 0 ..< timesChosen.count, using: &r)// timesChosen.indices.randomElement(using: &r)! timesChosen[i] += 1 } print(timesChosen) } func testBoolWithOdds() { var r = FuzzerPRNG.init(seed: 2) var timesTrue = 0 for _ in 0 ..< 1_000_000 { if r.bool(odds: 0.27) { timesTrue += 1 } } print(timesTrue) } }
29.704545
118
0.527927
f98bfd8a3a70e760d434a589749b2cc118833fe1
3,380
import Foundation import SourceKittenFramework public struct AnyObjectProtocolRule: SubstitutionCorrectableASTRule, OptInRule, ConfigurationProviderRule, AutomaticTestableRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "anyobject_protocol", name: "AnyObject Protocol", description: "Prefer using `AnyObject` over `class` for class-only protocols.", kind: .lint, minSwiftVersion: .fourDotOne, nonTriggeringExamples: [ Example("protocol SomeProtocol {}\n"), Example("protocol SomeClassOnlyProtocol: AnyObject {}\n"), Example("protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {}\n"), Example("@objc protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {}\n") ], triggeringExamples: [ Example("protocol SomeClassOnlyProtocol: ↓class {}\n"), Example("protocol SomeClassOnlyProtocol: ↓class, SomeInheritedProtocol {}\n"), Example("@objc protocol SomeClassOnlyProtocol: ↓class, SomeInheritedProtocol {}\n") ], corrections: [ Example("protocol SomeClassOnlyProtocol: ↓class {}\n"): Example("protocol SomeClassOnlyProtocol: AnyObject {}\n"), Example("protocol SomeClassOnlyProtocol: ↓class, SomeInheritedProtocol {}\n"): Example("protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {}\n"), Example("protocol SomeClassOnlyProtocol: SomeInheritedProtocol, ↓class {}\n"): Example("protocol SomeClassOnlyProtocol: SomeInheritedProtocol, AnyObject {}\n"), Example("@objc protocol SomeClassOnlyProtocol: ↓class, SomeInheritedProtocol {}\n"): Example("@objc protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {}\n") ] ) // MARK: - ASTRule public func validate(file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [StyleViolation] { return violationRanges(in: file, kind: kind, dictionary: dictionary).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } // MARK: - SubstitutionCorrectableASTRule public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? { return (violationRange, "AnyObject") } public func violationRanges(in file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [NSRange] { guard kind == .protocol else { return [] } return dictionary.elements.compactMap { subDict -> NSRange? in guard let byteRange = subDict.byteRange, let content = file.stringView.substringWithByteRange(byteRange), content == "class" else { return nil } return file.stringView.byteRangeToNSRange(byteRange) } } }
45.066667
105
0.624556
ed3e3c3cd84830e77bd445b6387a23e4408c63fd
605
// // DateExtension.swift // EliteSISSwift // // Created by PeakGeek on 31/03/18. // Copyright © 2018 Vivek Garg. All rights reserved. // import Foundation extension Date{ /// This method is used to get the current date with specified format default is 09-Mar-1990 /// /// - Parameter format: i.e. dd-MMM-yyyy /// - Returns: formatted date string static func getCurrentDateWithFormat(format: String = "dd-MMM-yyyy")->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: Date()) } }
25.208333
96
0.661157
d5e00fdf03e50e448ed84996732df02c25ae7a0c
7,854
// String+Attributed.swift // // Copyright (c) 2020 Burak Uzunboy // // 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 #if !os(macOS) import UIKit #endif public extension String { /// Converts string to `URL`. func convertURL() -> URL? { return URL(string: self) } /// Converts string to Integer value. var intValue: Int? { return Int(self) ?? (self.doubleValue != nil ? Int(self.doubleValue!) : nil) } /// Converts string to Double value. var doubleValue: Double? { return Double(self) } /// Converts string to `Date` object with the Database Timestamp format. var dateValue: Date? { return self.date(withFormat: "yyyy-MM-dd'T'hh:mm:ss") } /// Converts string to `Date` object with the given format. func date(withFormat format: String) -> Date? { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.timeZone = TimeZone(identifier: "UTC") formatter.dateFormat = format return formatter.date(from: self) } /// Returns localized string. var localized: String { if NSLocalizedString(self, comment: self).isEmpty { return enLocalized } return NSLocalizedString(self, comment: self) } /// returns localized string in english or empty string var enLocalized: String { if let enPath = Bundle.main.path(forResource: "en", ofType: "lproj") { let enBundle = Bundle(path: enPath) return enBundle?.localizedString(forKey: self, value: self, table: nil) ?? "" } return "" } /// Capitalizing first letter func capitalizingFirstLetter() -> String { return prefix(1).capitalized + dropFirst() } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } /// Returns attributed string func attributed(with attributes: [NSAttributedString.Key:Any]) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: attributes) } #if !os(macOS) /** Returns HTML attributed string with custom attributes. - parameter attributes: custom attributes - returns: HTML formatted `NSAttributedString` */ func richAttributed(with attributes: [NSAttributedString.Key:Any]) -> NSAttributedString { var text = NSMutableAttributedString(string: self) do { text = try NSMutableAttributedString(data: self.data(using: .unicode, allowLossyConversion: true)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } catch { print(error.localizedDescription) } for attribute in attributes { if attribute.key == .font { guard let font = attribute.value as? UIFont else { break } // let size = font.pointSize // check font weight text.enumerateAttribute(.font, in: NSRange(location: 0, length: text.string.count), options: .init(rawValue: 0)) { (object, range, stop) in let newFont: UIFont = font // // if let fontTraits = (object as? UIFont)?.fontDescriptor.symbolicTraits { // if fontTraits.contains(.traitItalic) && fontTraits.contains(.traitBold) { // newFont = UIFont.font(style: .boldItalic, size: size) // } // else if fontTraits.contains(.traitBold) { // newFont = UIFont.font(style: .bold, size: size) // } // else if fontTraits.contains(.traitItalic) { // newFont = UIFont.font(style: .regularItalic, size: size) // } else { // newFont = UIFont.font(style: .regular, size: size) // } // } text.addAttribute(.font, value: newFont, range: range) } } else if attribute.key == .paragraphStyle { text.enumerateAttribute(.paragraphStyle, in: NSRange(location: 0, length: text.string.count), options: .init(rawValue: 0)) { (object, range, stop) in if (object as! NSParagraphStyle).alignment == .natural { // override text.addAttribute(attribute.key, value: attribute.value, range: range) } } } else { // add directly text.addAttribute(attribute.key, value: attribute.value, range: NSRange(location: 0, length: text.string.count)) } } return text } #endif /// Converts string to URL by using `stringLiteral` initializer. var url: URL { return URL(stringLiteral: self) } } public extension String { var length: Int { return count } subscript (i: Int) -> String { return self[i ..< i + 1] } func substring(fromIndex: Int) -> String { return self[min(fromIndex, length) ..< length] } func substring(toIndex: Int) -> String { return self[0 ..< max(0, toIndex)] } subscript (r: Range<Int>) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return String(self[start ..< end]) } } public extension String { var nonEmpty: String? { return self.isEmpty ? nil : self } } public extension String { // allows you to replace a string inside a string without getting a new string object // var string = "foo!" // string.replace("!", with: "?") // print(string) // output is 'foo?' mutating func replace(_ originalString:String, with newString:String) { self = self.replacingOccurrences(of: originalString, with: newString) } } public extension String { func countInstances(of stringToFind: String) -> Int { var stringToSearch = self var count = 0 while let foundRange = stringToSearch.range(of: stringToFind, options: .diacriticInsensitive) { stringToSearch = stringToSearch.replacingCharacters(in: foundRange, with: "") count += 1 } return count } }
36.361111
165
0.597148
3804f1f8bcb25e96a474771b3b4b6d8d3ddea030
738
// // RKDateFormatter.swift // RebeloperKit // // Created by Alex Nagy on 01/06/2019. // import Foundation public enum RKDateFormatter: String { case MMM_d = "MMM d" case EEEE_MMM_d_yyyy = "EEEE, MMM d, yyyy" case MM_dd_yyyy = "MM/dd/yyyy" case MM_dd_yyyy_HH_mm = "MM-dd-yyyy HH:mm" case MMM_d_h_mm_a = "MMM d, h:mm a" case MMMM_yyyy = "MMMM yyyy" case yyyy_MM_dd_T_HH_mm_ssZ = "yyyy-MM-dd'T'HH:mm:ssZ" case dd_MM_yy = "dd.MM.yy" case HH_mm_ss_SSS = "HH:mm:ss.SSS" case MM_dd_yyyy_HH_mm_ss_SSS = "MM/dd/yyyy HH:mm:ss:SSS" case MM_dd_yyyy_HH_mm_ss = "MM-dd-yyyy HH:mm:ss" case E_d_MMM_yyyy_HH_mm_ss_Z = "E, d MMM yyyy HH:mm:ss Z" case MMM_d_HH_mm_ss_SSSZ = "MMM d, HH:mm:ss:SSSZ" }
29.52
61
0.670732
1123c01c9c8480008bb84416814fedacfc69e935
1,160
// // CollectionCellDescribable.swift // Collor // // Created by Guihal Gwenn on 16/03/17. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved. // import Foundation import UIKit import ObjectiveC private struct AssociatedKeys { static var IndexPath = "collor_IndexPath" } public protocol CollectionCellDescribable : Identifiable { var identifier: String { get } var className: String { get } var selectable: Bool { get } func getAdapter() -> CollectionAdapter func size(_ collectionView: UICollectionView, sectionDescriptor: CollectionSectionDescribable) -> CGSize var bundle: Bundle { get } } extension CollectionCellDescribable { public internal(set) var indexPath: IndexPath? { get { return objc_getAssociatedObject(self, &AssociatedKeys.IndexPath) as? IndexPath } set { objc_setAssociatedObject( self, &AssociatedKeys.IndexPath, newValue as IndexPath?, .OBJC_ASSOCIATION_COPY) } } } public extension CollectionCellDescribable { var bundle: Bundle { let typeClass = type(of: self) return Bundle(for: typeClass) } }
26.976744
118
0.699138
01cb792c7884085fd748316cac855847fed3d594
673
// // MinMax.swift // WaveLabs // // Created by Vlad Gorlov on 06/05/16. // Copyright © 2016 Vlad Gorlov. All rights reserved. // public struct MinMax<T: Comparable> { public var min: T public var max: T public init(min aMin: T, max aMax: T) { min = aMin max = aMax assert(min <= max) } public init(valueA: MinMax, valueB: MinMax) { min = Swift.min(valueA.min, valueB.min) max = Swift.max(valueA.max, valueB.max) } } extension MinMax where T: Numeric { public var difference: T { return max - min } } extension MinMax where T: FloatingPoint { public var difference: T { return max - min } }
18.189189
54
0.610698
690c5d25957b7eebaebd543c85f888213f025b0b
8,964
import Foundation import Capacitor import FirebaseCore import FirebaseAuth public typealias AuthStateChangedObserver = () -> Void @objc public class FirebaseAuthentication: NSObject { public let errorDeviceUnsupported = "Device is not supported. At least iOS 13 is required." public let errorCustomTokenSkipNativeAuth = "signInWithCustomToken cannot be used in combination with skipNativeAuth." public var authStateObserver: AuthStateChangedObserver? private let plugin: FirebaseAuthenticationPlugin private let config: FirebaseAuthenticationConfig private var appleAuthProviderHandler: AppleAuthProviderHandler? private var facebookAuthProviderHandler: FacebookAuthProviderHandler? private var googleAuthProviderHandler: GoogleAuthProviderHandler? private var oAuthProviderHandler: OAuthProviderHandler? private var phoneAuthProviderHandler: PhoneAuthProviderHandler? private var savedCall: CAPPluginCall? init(plugin: FirebaseAuthenticationPlugin, config: FirebaseAuthenticationConfig) { self.plugin = plugin print("plugin constructor") self.config = config super.init() if FirebaseApp.app() == nil { print ("configuring app") FirebaseApp.configure() print ("app configured") } self.initListeners(); } @objc func initListeners() { print("initializing listeners"); self.initAuthProviderHandlers(config: config) Auth.auth().addStateDidChangeListener {_, _ in print("authStateChanged2") self.authStateObserver?() } } @objc func getCurrentUser() -> User? { return Auth.auth().currentUser } @objc func getIdToken(_ forceRefresh: Bool, completion: @escaping (String?, Error?) -> Void) { let user = self.getCurrentUser() user?.getIDTokenResult(forcingRefresh: forceRefresh, completion: { result, error in if let error = error { completion(nil, error) return } completion(result?.token, nil) }) } @objc func setLanguageCode(_ languageCode: String) { Auth.auth().languageCode = languageCode } @objc func signInWithApple(_ call: CAPPluginCall) { self.savedCall = call self.appleAuthProviderHandler?.signIn(call: call) } @objc func signInWithFacebook(_ call: CAPPluginCall) { self.savedCall = call self.facebookAuthProviderHandler?.signIn(call: call) } @objc func signInWithGithub(_ call: CAPPluginCall) { self.savedCall = call self.oAuthProviderHandler?.signIn(call: call, providerId: "github.com") } @objc func signInWithGoogle(_ call: CAPPluginCall) { self.savedCall = call self.googleAuthProviderHandler?.signIn(call: call) } @objc func signInWithMicrosoft(_ call: CAPPluginCall) { self.savedCall = call self.oAuthProviderHandler?.signIn(call: call, providerId: "microsoft.com") } @objc func signInWithPhoneNumber(_ call: CAPPluginCall) { self.savedCall = call self.phoneAuthProviderHandler?.signIn(call: call) } @objc func signInWithTwitter(_ call: CAPPluginCall) { self.savedCall = call self.oAuthProviderHandler?.signIn(call: call, providerId: "twitter.com") } @objc func signInWithYahoo(_ call: CAPPluginCall) { self.savedCall = call self.oAuthProviderHandler?.signIn(call: call, providerId: "yahoo.com") } @objc func signInWithCustomToken(_ call: CAPPluginCall) { if config.skipNativeAuth == true { call.reject(self.errorCustomTokenSkipNativeAuth) return } let token = call.getString("token", "") self.savedCall = call Auth.auth().signIn(withCustomToken: token) { _, error in if let error = error { self.handleFailedSignIn(message: nil, error: error) return } guard let savedCall = self.savedCall else { return } let user = self.getCurrentUser() let result = FirebaseAuthenticationHelper.createSignInResult(credential: nil, user: user, idToken: nil, nonce: nil) savedCall.resolve(result) } } @objc func signInWithEmailAndPassword(_ call: CAPPluginCall) { let email = call.getString("email", "") let password = call.getString("password", "") self.savedCall = call Auth.auth().signIn(withEmail: email, password: password) { _, error in if let error = error { self.handleFailedSignIn(message: nil, error: error) return } guard let savedCall = self.savedCall else { return } let user = self.getCurrentUser() let result = FirebaseAuthenticationHelper.createSignInResult(credential: nil, user: user, idToken: nil, nonce: nil) savedCall.resolve(result) } } @objc func createUserWithEmailAndPassword(_ call: CAPPluginCall) { let email = call.getString("email", "") let password = call.getString("password", "") self.savedCall = call Auth.auth().createUser(withEmail: email, password: password) { _, error in if let error = error { self.handleFailedSignIn(message: nil, error: error) return } guard let savedCall = self.savedCall else { return } let user = self.getCurrentUser() user?.sendEmailVerification(completion: { (error) in let result = FirebaseAuthenticationHelper.createSignInResult(credential: nil, user: user, idToken: nil, nonce: nil) savedCall.resolve(result) }) } } @objc func sendPasswordResetEmail(_ call: CAPPluginCall) { let email = call.getString("email", "") self.savedCall = call Auth.auth().sendPasswordReset(withEmail: email) { error in if let error = error { self.handleFailedSignIn(message: nil, error: error) return } guard let savedCall = self.savedCall else { return } savedCall.resolve() } } @objc func signOut(_ call: CAPPluginCall) { do { try Auth.auth().signOut() googleAuthProviderHandler?.signOut() facebookAuthProviderHandler?.signOut() call.resolve() } catch let signOutError as NSError { call.reject("Error signing out: \(signOutError)") } } @objc func useAppLanguage() { Auth.auth().useAppLanguage() } func handleSuccessfulSignIn(credential: AuthCredential, idToken: String?, nonce: String?) { if config.skipNativeAuth == true { guard let savedCall = self.savedCall else { return } let result = FirebaseAuthenticationHelper.createSignInResult(credential: credential, user: nil, idToken: idToken, nonce: nonce) savedCall.resolve(result) return } Auth.auth().signIn(with: credential) { (_, error) in if let error = error { self.handleFailedSignIn(message: nil, error: error) return } guard let savedCall = self.savedCall else { return } let user = self.getCurrentUser() let result = FirebaseAuthenticationHelper.createSignInResult(credential: credential, user: user, idToken: idToken, nonce: nonce) savedCall.resolve(result) } } func handleFailedSignIn(message: String?, error: Error?) { guard let savedCall = self.savedCall else { return } let errorMessage = message ?? error?.localizedDescription ?? "" savedCall.reject(errorMessage, nil, error) } func getPlugin() -> FirebaseAuthenticationPlugin { return self.plugin } private func initAuthProviderHandlers(config: FirebaseAuthenticationConfig) { if config.providers.contains("apple.com") { self.appleAuthProviderHandler = AppleAuthProviderHandler(self) } if config.providers.contains("facebook.com") { self.facebookAuthProviderHandler = FacebookAuthProviderHandler(self) } if config.providers.contains("google.com") { self.googleAuthProviderHandler = GoogleAuthProviderHandler(self) } if config.providers.contains("phone") { self.phoneAuthProviderHandler = PhoneAuthProviderHandler(self) } self.oAuthProviderHandler = OAuthProviderHandler(self) } }
35.856
140
0.617693
61b876058faf3931fe1cf1093a82981a502e3b5d
963
// // BroadcastsDataFetcherProtocol.swift // LiveEvents // // Created by Serhii Krotkykh on 27.10.2020. // Copyright © 2020 Serhii Krotkykh. All rights reserved. // import Foundation import YTLiveStreaming import RxSwift protocol BroadcastsDataFetcher { /// Observable data source for Broadcasts List /// /// - Parameters: /// /// - Returns: var rxData: PublishSubject<[SectionModel]> { get } /// send request to load source data for Broadcasts List /// /// - Parameters: /// /// - Returns: func loadData() /// Get Current Broadcast /// /// - Parameters: /// - index of the Broadcast source data /// /// - Returns: func getCurrent(for index: Int) -> LiveBroadcastStreamModel /// Get Completed Broadcast /// /// - Parameters: /// - index of the Broadcast source data /// /// - Returns: func getPast(for index: Int) -> LiveBroadcastStreamModel }
23.487805
63
0.614746
21ac8b232a48b8bf82fceffc8e011406370801e5
1,500
// // Created by Avihu Harush on 17/01/2020 // import Foundation import AVFoundation class CustomMediaRecorder { private var recordingSession: AVAudioSession! private var audioRecorder: AVAudioRecorder! private var audioFilePath: URL! private let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44100, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] private func getDirectoryToSaveAudioFile() -> URL { return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) } public func startRecording() -> Bool { do { recordingSession = AVAudioSession.sharedInstance() try recordingSession.setCategory(AVAudioSession.Category.record) try recordingSession.setActive(true) audioFilePath = getDirectoryToSaveAudioFile().appendingPathComponent("\(UUID().uuidString).aac") audioRecorder = try AVAudioRecorder(url: audioFilePath, settings: settings) audioRecorder.record() return true } catch { return false } } public func stopRecording() { do { audioRecorder.stop() try recordingSession.setActive(false) audioRecorder = nil recordingSession = nil } catch {} } public func getOutputFile() -> URL { return audioFilePath } }
28.301887
108
0.632667
ac23c95b2a8e03db3f5a3f77996d68f8bdbfbd01
25,335
// // FaceRecognitionViewController.swift // BeanCounter // // Created by Robert Horrion on 12/13/19. // Copyright © 2019 Robert Horrion. All rights reserved. // import UIKit import CoreData import AVFoundation import SFaceCompare import KeychainSwift class FaceRecognitionViewController: UIViewController, AVCapturePhotoCaptureDelegate { var managedObjectsArray = [NSManagedObject?]() var imagesFromCoreDataArray = [UIImage?]() var transactionsManagedObjectsArray = [NSManagedObject?]() var mainViewController: ViewController? var indexSelected: Int? var cameraTimer: Timer? var captureSession: AVCaptureSession! var cameraOutput: AVCapturePhotoOutput! var previewLayer: AVCaptureVideoPreviewLayer! var imageTaken: UIImage? var orientationFromWindow: UIDeviceOrientation? var cameraPosition = AVCaptureDevice.Position.front var rearCameraSelected = AVCaptureDevice.DeviceType.builtInWideAngleCamera @IBOutlet weak var previewView: UIView! //MARK: - App Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // UINavigationBar Setup navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneUserButton)) // This will rotate the camera when the device orientation changes let didRotate: (Notification) -> Void = { notification in self.fixOrientation() } // Device orientation has changed, update the camera NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: .main, using: didRotate) getDataFromCoreData() loadTransactionsFromCoreData() // Do camera setup here captureSession = AVCaptureSession() cameraOutput = AVCapturePhotoOutput() previewLayer = AVCaptureVideoPreviewLayer() let device = AVCaptureDevice.default(rearCameraSelected, for: AVMediaType.video, position: cameraPosition) if captureSession?.inputs.first != nil { captureSession?.removeInput((captureSession?.inputs.first!)!) } if let input = try? AVCaptureDeviceInput(device: device!) { if ((captureSession?.canAddInput(input))!) { captureSession?.addInput(input) if ((captureSession?.canAddOutput(cameraOutput!))!) { //cameraOutput.availableRawPhotoFileTypes = captureSession?.addOutput(cameraOutput!) // Next, the previewLayer is setup to show the camera content with the size of the view. previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!) previewLayer?.frame = previewView.bounds previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill previewView.clipsToBounds = true previewView.layer.addSublayer(previewLayer!) captureSession?.startRunning() } } else { print("Cannot add output") } } fixOrientation() cameraTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerCalled), userInfo: nil, repeats: true) } @objc func doneUserButton() { self.dismiss(animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { cameraTimer?.invalidate() } func fixOrientation() { // Call function here to get orientation value if let connection = self.previewLayer?.connection { let previewLayerConnection : AVCaptureConnection = connection if previewLayerConnection.isVideoOrientationSupported { if let interfaceOrientation = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.windowScene?.interfaceOrientation { switch interfaceOrientation { case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait) orientationFromWindow = .landscapeLeft print("Portrait down detected") case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight) orientationFromWindow = .portrait print("Landscape right detected") case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft) orientationFromWindow = .landscapeRight print("Landscape left detected") case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown) orientationFromWindow = .portraitUpsideDown print("Portrait upside down detected") default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait) orientationFromWindow = .portrait print("Default detected") } } } } } // Helper function for getting the videoLayer orientation right private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) { layer.videoOrientation = orientation previewLayer.frame = previewView.bounds } func performPasscodeSegue() { performSegue(withIdentifier: "getUserPasscodeForFaceRecognition", sender: self) } //MARK: - CoreData helper // Get images for Face compare from CoreData and save them to an Array for faster access func getDataFromCoreData() { // Create context for context info stored in AppDelegate let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User") request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)] // Reset Array to empty Array managedObjectsArray.removeAll() // Iterate through all NSManagedObjects in NSFetchRequestResult request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { let index = managedObjectsArray.count // New method, just save the whole NSManagedObject, then read from it later on managedObjectsArray.insert(data, at: index) // next few lines are for debugging let firstName = data.value(forKey: "firstname") as! String let lastName = data.value(forKey: "lastname") as! String let eMail = data.value(forKey: "email") as! String // Check if user saved a photo if data.value(forKey: "photo") != nil { // Get photos and save them in a separate array as UIImages with matching array index values let imageFromCoreData = data.value(forKey: "photo") as! Data let uiImageValue = UIImage(data: imageFromCoreData) imagesFromCoreDataArray.insert(uiImageValue, at: index) print("photo was found for user: " + firstName + " " + lastName + " (" + eMail + ")") } else { // User didn't save a photo imagesFromCoreDataArray.insert(nil, at: index) print("photo wasn't found for user: " + firstName + " " + lastName + " (" + eMail + ")") } } } catch { print("failed to fetch data from context") } } //MARK: Compare Faces here @objc func timerCalled() { // Take a photo here, this happens once a second let settings = AVCapturePhotoSettings() settings.flashMode = .off cameraOutput?.capturePhoto(with: settings, delegate: self) } // MARK: Photo Capture Delegate handling func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { if let error = error { print(error.localizedDescription) } // Create the CGImage from AVCapturePhoto let cgImage = photo.cgImageRepresentation()!.takeUnretainedValue() // Get the orientation from Window let altOrientation = (orientationFromWindow?.rawValue)! let uiImageOrientation = UIImage.Orientation(rawValue: altOrientation)! // Create the UIImage let imageFromDeviceOrientation = UIImage(cgImage: cgImage, scale: 1, orientation: uiImageOrientation) // Take the resulting image and compare it with the ones on record compareFaces(faceFromCamera: imageFromDeviceOrientation) } func compareFaces(faceFromCamera: UIImage) { // Set up an attempt counter to count how many accounts have been checked var attemptCounter = 0 // Get the MatchingCoefficient from UserDefaults to determine the minimum matching likelihood required let matchingCoefficientFromUserDefaults = UserDefaults.standard.double(forKey: "matchingCoefficient") // Create a dict to save all matching coefficients var matchingCoeffDict = [Int:Double]() // Compare the photo captured with the ones in imagesFromCoreDataArray for (index, userPhoto) in imagesFromCoreDataArray.enumerated() { // Weed out the users who didn't save a profile picture if userPhoto != nil { print("Firstname: ") print(self.managedObjectsArray[index]?.value(forKey: "firstname") as! String) // Compare userPhoto from array with photo from camera let faceComparator = SFaceCompare(on: userPhoto!, and: faceFromCamera) faceComparator.compareFaces { [self] result in switch result { case .failure(let error): // Add matching coefficient value to the dictionary matchingCoeffDict[index] = 1.1 // Raise attemptCounter by 1 attemptCounter += 1 // print("Faces don't match with more than 1.0 matching coefficient!") print(error) print("AttemptCounter: " + String(attemptCounter)) if attemptCounter == imagesFromCoreDataArray.count { print("Dict: ") print(matchingCoeffDict) // All images in the array have been checked self.pickUserWithBestMatch(matchingCoeffDict: matchingCoeffDict) } case .success(let data): // faces match // If the matchingCoefficient is smaller than the one defined in UserDefaults, a likely match is found if data.probability <= matchingCoefficientFromUserDefaults { // Add matching coefficient value to the dictionary matchingCoeffDict[index] = data.probability // Raise attemptCounter by 1 attemptCounter += 1 // print("Matching probability: " + String(data.probability)) print("AttemptCounter: " + String(attemptCounter)) if attemptCounter == imagesFromCoreDataArray.count { print("Dict: ") print(matchingCoeffDict) // All images in the array have been checked self.pickUserWithBestMatch(matchingCoeffDict: matchingCoeffDict) } } } } } } } func pickUserWithBestMatch(matchingCoeffDict: Dictionary<Int, Double>) { if matchingCoeffDict.isEmpty == false { // If the dictionary contains data at least one match has been found // TODO: Remove after debugging print("MatchingCoeffDict:") print(matchingCoeffDict) // Lower matchingCoefficient means higher matching likelihood let bestMatch = matchingCoeffDict.min { a, b in a.value < b.value } if bestMatch!.value <= 1 { print("Best Match coefficient: " + String(bestMatch!.value)) // Save indexSelected for later access when billing the user for coffee and when checking the Passcode self.indexSelected = bestMatch?.key // Set variables from managedObject let firstName = self.managedObjectsArray[bestMatch!.key]?.value(forKey: "firstname") as! String let lastName = self.managedObjectsArray[bestMatch!.key]?.value(forKey: "lastname") as! String let eMail = self.managedObjectsArray[bestMatch!.key]?.value(forKey: "email") as! String let userIDString = firstName + " " + lastName + " (" + eMail + ")" print("Faces Match! ") print("Hello, : " + userIDString) let alertController = UIAlertController(title: "Would you like some coffee?", message: "Hi, " + userIDString, preferredStyle: .alert) let dismissAction = UIAlertAction(title: "No", style: .default) let coffeeAction = UIAlertAction(title: "Yes", style: .default) { action in // invalidate the timer, you found the person! self.cameraTimer?.invalidate() // Get "faceRecPasscode" to determine whether to require a passcode when using face recognition let recIsActivated = UserDefaults.standard.bool(forKey: "faceRecPasscode") // Ask for user passcode if enabled in settings if recIsActivated == true { // Passcode protection is enabled self.performPasscodeSegue() } else { // Passcode protection isn't enabled self.writeBilledCoffeeToDatabase() } } alertController.addAction(dismissAction) alertController.addAction(coffeeAction) self.present(alertController, animated: true) } } } func billUserForCoffee(passcodeReturned: String) { // Get UUID from managed object let uuidFromManagedObject = managedObjectsArray[indexSelected!]!.value(forKey: "userUUID") as! NSUUID // Get keychain value using UUID let keychain = KeychainSwift() let userPasscode = keychain.get(uuidFromManagedObject.uuidString) // Check to see if passcode entered matches the one in the keychain if userPasscode == passcodeReturned { // The passcodes matched, bill the user for coffee! writeBilledCoffeeToDatabase() } else { // Provided passcode was wrong, alert the user let alert = UIAlertController(title: "Wrong passcode", message: "You entered the wrong passcode, please try again!", preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Ok", style: .default) alert.addAction(dismissAction) self.present(alert, animated: true) } } func writeBilledCoffeeToDatabase() { // Get current coffee price from NSUserDefaults let userDefaults = UserDefaults.standard let coffeePriceAsInt = userDefaults.integer(forKey: "CoffeePrice") let coffeePriceAsInt64 = Int64(coffeePriceAsInt) // Read and print balance before making changes to saved data let balanceBeforeChanges = managedObjectsArray[indexSelected!]?.value(forKey: "balanceInCents") as! Int64 print("balance before changes: " + String(balanceBeforeChanges)) // Save new balance let newBalance = balanceBeforeChanges - coffeePriceAsInt64 managedObjectsArray[indexSelected!]?.setValue(newBalance, forKey: "balanceInCents") // Write the transaction to the TransactionsForUser entity in CoreData CoreDataHelperClass.init().saveNewTransaction(userForTransaction: managedObjectsArray[indexSelected!] as! User, dateTime: Date(), monetaryValue: -coffeePriceAsInt64, transactionType: "Coffee") // Read and print balance before making changes to saved data let balanceAfterChanges = managedObjectsArray[indexSelected!]?.value(forKey: "balanceInCents") as! Int64 print("balance after changes: " + String(balanceAfterChanges)) // Save number of coffee cups for stats screen saveCurrentNumberOfTransactionsToCoreData(numberOfCups: 1) // Create instance of MOC let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext // Save newUserInfo to CoreData do { try context.save() // Data was successfully saved print("successfully saved data") self.dismiss(animated: true, completion: nil) // This viewcontroller is already in the process of being dismissed. Call the alertview on mainViewController to avoid viewController hierarchy issues. mainViewController?.billedForCoffeeSuccessfullyAlert() } catch { // Failed to write to the database print("Couldn't save to CoreData") let alert = UIAlertController(title: "Failed Database Operation", message: "Failed to write to the Database", preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Ok", style: .default) alert.addAction(dismissAction) self.present(alert, animated: true) } } //MARK: - Transaction helpers func loadTransactionsFromCoreData() { // Create context for context info stored in AppDelegate let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Transactions") request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)] // Reset Array to empty Array transactionsManagedObjectsArray.removeAll() // Iterate through all NSManagedObjects in NSFetchRequestResult request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { // Save the whole NSManagedObject, then read from it later on transactionsManagedObjectsArray.insert(data, at: transactionsManagedObjectsArray.count) } } catch { print("failed to fetch data from context") } } func saveCurrentNumberOfTransactionsToCoreData(numberOfCups: Int64) { // Create context for context info stored in AppDelegate let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext // Load all transactions to always have access to the current data loadTransactionsFromCoreData() let date = Date() let calendar = Calendar.current let dateString = String(calendar.component(.year, from: date)+calendar.component(.month, from: date)+calendar.component(.day, from: date)) if let matchingIndex = transactionsManagedObjectsArray.firstIndex(where: {$0!.value(forKey: "date") as! String == dateString}) { // Object was found, this is not the first cup today! let priorTransactions = transactionsManagedObjectsArray[matchingIndex]?.value(forKey: "numberOfTransactions") as! Int64 let sumOfCupsToday = priorTransactions + numberOfCups print("Sum of cups today is: " + String(sumOfCupsToday)) transactionsManagedObjectsArray[matchingIndex]?.setValue(sumOfCupsToday, forKey: "numberOfTransactions") } else { // item could not be found // Create entity, then create a transactionInfo object let entity = NSEntityDescription.entity(forEntityName: "Transactions", in: context) let transactionInfo = NSManagedObject(entity: entity!, insertInto: context) // Provide newUserInfo object with properties transactionInfo.setValue(dateString, forKey: "date") transactionInfo.setValue(numberOfCups, forKey: "numberOfTransactions") } // Save transactionInfo to CoreData do { try context.save() // Data was successfully saved, now pop the VC print("successfully saved stats data") mainViewController!.reloadStatsLabel() } catch { print("Couldn't save stats to CoreData") //Remind user to make sure all info has been provided / all fields are populated let alert = UIAlertController(title: "Failed Database Operation", message: "Failed to write stats to the Database", preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Ok", style: .default) alert.addAction(dismissAction) self.present(alert, animated: true) } } // 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. // Tell the destination ViewController that you're trying to access the user passcode if segue.identifier == "getUserPasscodeForFaceRecognition" { if let navigationViewController = segue.destination as? UINavigationController { if let passcodeViewController = navigationViewController.viewControllers[0] as? SetPasscodeViewController { passcodeViewController.userLevel = .getUserForFaceRecognition passcodeViewController.faceRecognitionController = self } } } } }
43.013582
163
0.567239
f422ca59b8341e97c71a4635fd5c9774ae5aca84
6,897
// // popup.swift // Disk // // Created by Serhiy Mytrovtsiy on 11/05/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import ModuleKit import StatsKit internal class Popup: NSView { let diskFullHeight: CGFloat = 60 var list: [String: DiskView] = [:] public init() { super.init(frame: NSRect(x: 0, y: 0, width: Constants.Popup.width, height: 0)) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func usageCallback(_ value: DiskList) { value.list.reversed().forEach { (d: diskInfo) in if self.list[d.name] == nil { DispatchQueue.main.async(execute: { self.list[d.name] = DiskView( NSRect(x: 0, y: (self.diskFullHeight + Constants.Popup.margins) * CGFloat(self.list.count), width: self.frame.width, height: self.diskFullHeight), name: d.name, size: d.totalSize, free: d.freeSize, path: d.path ) self.addSubview(self.list[d.name]!) self.setFrameSize(NSSize(width: self.frame.width, height: ((self.diskFullHeight + Constants.Popup.margins) * CGFloat(self.list.count)) - Constants.Popup.margins)) }) } else { self.list[d.name]?.update(free: d.freeSize) } } } } internal class DiskView: NSView { public let name: String public let size: Int64 private let uri: URL? private let nameHeight: CGFloat = 20 private let legendHeight: CGFloat = 12 private let barHeight: CGFloat = 10 private var legendField: NSTextField? = nil private var percentageField: NSTextField? = nil private var usedBarSpace: NSView? = nil private var mainView: NSView public init(_ frame: NSRect, name: String, size: Int64, free: Int64, path: URL?) { self.mainView = NSView(frame: NSRect(x: 5, y: 5, width: frame.width - 10, height: frame.height - 10)) self.name = name self.size = size self.uri = path super.init(frame: frame) self.wantsLayer = true self.layer?.cornerRadius = 2 self.addName() self.addHorizontalBar(free: free) self.addLegend(free: free) self.addSubview(self.mainView) let rect: CGRect = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) let trackingArea = NSTrackingArea(rect: rect, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInActiveApp], owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateLayer() { self.layer?.backgroundColor = isDarkMode ? NSColor(hexString: "#111111", alpha: 0.25).cgColor : NSColor(hexString: "#f5f5f5", alpha: 1).cgColor } private func addName() { let nameWidth = self.name.widthOfString(usingFont: .systemFont(ofSize: 13, weight: .light)) + 4 let view: NSView = NSView(frame: NSRect(x: 0, y: self.mainView.frame.height - nameHeight, width: nameWidth, height: nameHeight)) let nameField: NSTextField = TextView(frame: NSRect(x: 0, y: 0, width: nameWidth, height: view.frame.height)) nameField.stringValue = self.name view.addSubview(nameField) self.mainView.addSubview(view) } private func addLegend(free: Int64) { let view: NSView = NSView(frame: NSRect(x: 0, y: 2, width: self.mainView.frame.width, height: self.legendHeight)) self.legendField = TextView(frame: NSRect(x: 0, y: 0, width: view.frame.width - 40, height: view.frame.height)) self.legendField?.font = NSFont.systemFont(ofSize: 11, weight: .light) self.legendField?.stringValue = "Used \(Units(bytes: (self.size - free)).getReadableMemory()) from \(Units(bytes: self.size).getReadableMemory())" self.percentageField = TextView(frame: NSRect(x: view.frame.width - 40, y: 0, width: 40, height: view.frame.height)) self.percentageField?.font = NSFont.systemFont(ofSize: 11, weight: .regular) self.percentageField?.alignment = .right self.percentageField?.stringValue = "\(Int8((Double(self.size - free) / Double(self.size)) * 100))%" view.addSubview(self.legendField!) view.addSubview(self.percentageField!) self.mainView.addSubview(view) } private func addHorizontalBar(free: Int64) { let view: NSView = NSView(frame: NSRect(x: 1, y: self.mainView.frame.height - self.nameHeight - 11, width: self.mainView.frame.width - 2, height: self.barHeight)) view.wantsLayer = true view.layer?.backgroundColor = NSColor.white.cgColor view.layer?.borderColor = NSColor.secondaryLabelColor.cgColor view.layer?.borderWidth = 0.25 view.layer?.cornerRadius = 3 let percentage = CGFloat(self.size - free) / CGFloat(self.size) let width: CGFloat = (view.frame.width * percentage) / 1 self.usedBarSpace = NSView(frame: NSRect(x: 0, y: 0, width: width, height: view.frame.height)) self.usedBarSpace?.wantsLayer = true self.usedBarSpace?.layer?.backgroundColor = NSColor.controlAccentColor.cgColor view.addSubview(self.usedBarSpace!) self.mainView.addSubview(view) } public func update(free: Int64) { DispatchQueue.main.async(execute: { if self.legendField != nil { self.legendField?.stringValue = "Used \(Units(bytes: (self.size - free)).getReadableMemory()) from \(Units(bytes: self.size).getReadableMemory())" self.percentageField?.stringValue = "\(Int8((Double(self.size - free) / Double(self.size)) * 100))%" } if self.usedBarSpace != nil { let percentage = CGFloat(self.size - free) / CGFloat(self.size) let width: CGFloat = ((self.mainView.frame.width - 2) * percentage) / 1 self.usedBarSpace?.setFrameSize(NSSize(width: width, height: self.usedBarSpace!.frame.height)) } }) } override func mouseEntered(with: NSEvent) { NSCursor.pointingHand.set() } override func mouseExited(with: NSEvent) { NSCursor.arrow.set() } override func mouseDown(with: NSEvent) { if let uri = self.uri { NSWorkspace.shared.openFile(uri.absoluteString, withApplication: "Finder") } } }
40.810651
217
0.614615
09a868cef7c902df5feeca261d7641d1d1d783b2
1,974
// UDMessageButtonCellNode.swift // UseDesk_SDK_Swift // import Foundation import AsyncDisplayKit class UDMessageButtonCellNode: ASCellNode { var titleNode = ASTextNode() let backgroundNode = ASDisplayNode() var configurationStyle: ConfigurationStyle = ConfigurationStyle() func setCell(titleButton: String) { self.backgroundColor = .clear self.selectionStyle = .none let messageStyle = configurationStyle.messageStyle let attributedString = NSMutableAttributedString(string: titleButton) attributedString.addAttributes([NSAttributedString.Key.font : messageStyle.font, .foregroundColor : UIColor.white], range: NSRange(location: 0, length: attributedString.length)) titleNode.attributedText = attributedString titleNode.style.alignSelf = .center backgroundNode.backgroundColor = configurationStyle.messageButtonStyle.color backgroundNode.cornerRadius = configurationStyle.messageButtonStyle.cornerRadius addSubnode(backgroundNode) addSubnode(titleNode) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let verticalSpec = ASBackgroundLayoutSpec() verticalSpec.background = backgroundNode let titleNodeInsetSpec = ASInsetLayoutSpec(insets: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), child: titleNode) let vMessageStack = ASStackLayoutSpec( direction: .vertical, spacing: 0, justifyContent: .center, alignItems: .center, children: [titleNodeInsetSpec]) verticalSpec.setChild(vMessageStack, at: 0) verticalSpec.style.alignSelf = .center let verticalSpecInsetSpec = ASInsetLayoutSpec(insets: UIEdgeInsets(top: indexPath?.row == 0 ? 0 : 10, left: 0, bottom: 0, right: 0), child: verticalSpec) return verticalSpecInsetSpec } }
43.866667
185
0.695035
d952a06b413d32704ae285056b5c0cf8339061bf
6,874
// // BuilderTests.swift // XMLToolsTests // // Created on 28.06.18 // // swiftlint:disable nesting function_body_length import XCTest import XMLTools class BuilderTests: XCTestCase { let expectedXmlSource = """ <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book> <title lang="en">Harry Potter: The Philosopher's Stone</title> <price>24.99</price> <pages>223</pages> </book> <book> <title lang="en">Harry Potter: The Chamber of Secrets</title> <price>29.99</price> <pages>251</pages> </book> <book> <title lang="en">Learning XML</title> <price>39.95</price> <pages>432</pages> </book> <book> <title lang="de">IT-Sicherheit: Konzepte - Verfahren - Protokolle</title> <price>69.95</price> <pages>932</pages> </book> </bookstore> """ func testBuildDocument() { struct Book { let title: String let lang: String let price: Decimal let pages: Int } let bookstore = [ Book(title: "Harry Potter: The Philosopher's Stone", lang: "en", price: 24.99, pages: 223), Book(title: "Harry Potter: The Chamber of Secrets", lang: "en", price: 29.99, pages: 251), Book(title: "Learning XML", lang: "en", price: 39.95, pages: 432), Book(title: "IT-Sicherheit: Konzepte - Verfahren - Protokolle", lang: "de", price: 69.95, pages: 932) ] let builtXML = Document().select() builtXML.appendElement("bookstore") for book in bookstore { builtXML["bookstore"].appendElement("book") .appendElement("title").manipulate { $0.text = book.title; $0.attr("lang", setValue: book.lang) } .parent() .appendElement("price").manipulate { $0.decimalValue = book.price}.parent() .appendElement("pages").manipulate { $0.intValue = book.pages } } let xmlData = builtXML.document().data(.indent, .omitXMLDeclaration) print( String(data: xmlData!, encoding: .utf8)! ) let parser = Parser() guard let parsedXML = try? parser.parse(data: xmlData!) else { XCTFail("Unable to parse") return } // 1. bookstore XCTAssertEqual("bookstore", parsedXML["bookstore"].name().localName) // 2. /bookstore XCTAssertEqual("bookstore", parsedXML.selectDocument()["bookstore"].name().localName) // 3. bookstore/book XCTAssertEqual(4, parsedXML["bookstore", "book"].count) XCTAssertEqual(4, parsedXML["bookstore"]["book"].count) XCTAssertEqual(4, parsedXML.select("bookstore", "book").count) XCTAssertEqual(4, parsedXML.select("bookstore").select("book").count) // 4. //book XCTAssertEqual(4, parsedXML.descendants("book").count) // 5. //@lang XCTAssertEqual(4, parsedXML.descendants().attr("lang").count) // 6. /bookstore/book[1] XCTAssertEqual("Harry Potter: The Philosopher's Stone", parsedXML["bookstore", "book", 0]["title"].text) XCTAssertEqual("Harry Potter: The Philosopher's Stone", parsedXML["bookstore", "book"].item(0)["title"].text) // 7. /bookstore/book[last()] XCTAssertEqual("IT-Sicherheit: Konzepte - Verfahren - Protokolle", parsedXML["bookstore", "book"].last()["title"].text) // 8. /bookstore/book[position()<3] XCTAssertEqual(2, parsedXML["bookstore", "book"].select(byPosition: { $0 < 2 }).count ) // 9. //title[@lang] XCTAssertEqual(4, parsedXML.descendants("title").select({ $0.attr("lang").text != "" }).count ) // 10. //title[@lang='en'] XCTAssertEqual(3, parsedXML.descendants("title").select({ $0.attr("lang").text == "en" }).count ) // 11. /bookstore/book[pages>300] XCTAssertEqual(2, parsedXML["bookstore", "book"].select({ $0["pages"].number > 300 }).count ) // 11. /bookstore/book[price>35.00] XCTAssertEqual(2, parsedXML["bookstore", "book"].select({ $0["price"].number > 35 }).count ) // 12. /bookstore/book[price>40.00]/title XCTAssertEqual("IT-Sicherheit: Konzepte - Verfahren - Protokolle", parsedXML["bookstore", "book"].select({ $0["price"].number > 40 }).select("title").text) XCTAssertEqual("IT-Sicherheit: Konzepte - Verfahren - Protokolle", parsedXML["bookstore", "book"].select({ $0["price"].number > 40 })["title"].text) // 13. * XCTAssertEqual(1, parsedXML.select().count) // 13. /bookstore/book/title/@* XCTAssertEqual(4, parsedXML["bookstore", "book", "title"].attr().count) // 14. node() XCTAssertEqual(1, parsedXML["bookstore", "book", "title", 0].selectNode().count) // must select the TextNode // 15. /bookstore/* XCTAssertEqual(4, parsedXML["bookstore"].select().count) // 16. //* XCTAssertEqual(17, parsedXML.descendants().count) // 17. count(//book) XCTAssertEqual(4, parsedXML.descendants("book").count) // 18. XCTAssertEqual(["en", "en", "en", "de"], parsedXML.descendants("book").map({ $0["title"].attr("lang").text})) } public func testManipulation() { let parser = Parser() let xml: Infoset do { xml = try parser.parse(string: expectedXmlSource) } catch { XCTFail("Unable to parse \(error)") return } XCTAssertEqual(4, xml.descendants("book").count) xml["bookstore"].appendElement("book") XCTAssertEqual(5, xml.descendants("book").count) XCTAssertTrue(xml["bookstore", "book"].select({$0["title"].text.starts(with: "Harry Potter")}).count == 2, "Expected 2 Harry Potter books") xml["bookstore", "book", 0, "title"].text = "I renamed this book!" XCTAssertTrue(xml["bookstore", "book"].select({$0["title"].text.starts(with: "Harry Potter")}).count == 1, "Expected 1 Harry Potter book after rename") // rename all books to Fahrenheit 451 xml["bookstore", "book", "title"].text = "Fahrenheit 451" XCTAssertEqual(["Fahrenheit 451", "Fahrenheit 451", "Fahrenheit 451", "Fahrenheit 451"], xml["bookstore", "book", "title"].map {$0.text}) XCTAssertEqual("de", xml["bookstore", "book", 3, "title"].attr("lang").text) xml["bookstore", "book", 3, "title"].attr("lang", setValue: "lv") XCTAssertEqual("lv", xml["bookstore", "book", 3, "title"].attr("lang").text) XCTAssertEqual("", xml["bookstore", "book", 3, "title"].attr("newattr").text) xml["bookstore", "book", 3, "title"].attr("newattr", setValue: "newval") XCTAssertEqual("newval", xml["bookstore", "book", 3, "title"].attr("newattr").text) } }
39.965116
159
0.587576
d6df53544099b76a61eb15210234cdf6e8317189
259
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum B { let c = e.f { } func e<T class c { enum a<T where B : I { class B<T where H.d: I
21.583333
87
0.702703
87971107ea5fbb60daef5178a4630babc0903af4
2,066
// // PlayCatchupSpec.swift // Exposure // // Created by Fredrik Sjöberg on 2017-06-13. // Copyright © 2017 emp. All rights reserved. // import Quick import Nimble @testable import Exposure class PlayProgramSpec: QuickSpec { override func spec() { super.spec() let base = "https://exposure.empps.ebsd.ericsson.net" let customer = "BlixtGroup" let businessUnit = "Blixt" let env = Environment(baseUrl: base, customer: customer, businessUnit: businessUnit) let channelId = "channel1_qwerty" let programId = "program1_qwerty" let endpoint = "/entitlement/channel/" + channelId + "/program/" + programId + "/play" let sessionToken = SessionToken(value: "token") let entitlement = Entitlement(environment: env, sessionToken: sessionToken) let play = entitlement .program(programId: programId, channelId: channelId) .use(drm: "UNENCRYPTED") .use(format: "HLS") describe("Catchup") { it("should have headers") { expect(play.headers).toNot(beNil()) expect(play.headers!).to(equal(sessionToken.authorizationHeader)) } it("should generate a correct endpoint url") { expect(play.endpointUrl).to(equal(env.apiUrl+endpoint)) } it("should record DRM and format") { let drm = play.drm let format = play.format expect(drm).to(equal("UNENCRYPTED")) expect(format).to(equal("HLS")) } it("should transform PlayLive to PlayCatchup") { let transformed = entitlement .live(channelId: channelId) .program(programId: programId) expect(transformed.endpointUrl).to(equal(env.apiUrl+endpoint)) } } } }
32.28125
94
0.536786
5b9492ad9c2926eea28198f160050c7aeac89198
9,105
// // CurveViewController.swift // AnimationDemo // // Created by Jay on 2017-01-07. // Copyright © 2017 Jay Abbott. All rights reserved. // import UIKit import Animation private let curveLeft: CGFloat = 0.1 private let curveWidth: CGFloat = 0.8 private let curveTop: CGFloat = 0.2 private let curveHeight: CGFloat = 0.3 private let demoLeft: CGFloat = curveLeft private let demoWidth: CGFloat = curveWidth private let demoTop: CGFloat = 0.5 private let demoHeight: CGFloat = 0.2 private let demoBoxSize = CGSize(width: 25, height: 25) private let uiLeft: CGFloat = curveLeft private let uiWidth: CGFloat = curveWidth private let uiTop: CGFloat = 0.7 private let uiHeight: CGFloat = 0.2 class CurveViewController: UIViewController { @IBOutlet var changeHermiteButton: UIButton? @IBOutlet var changeCompositeButton: UIButton? var presetCurves = [ "linear" : Curve.linear, "easeInEaseOut" : Curve.easeInEaseOut, "easeIn" : Curve.easeIn, "easeOut" : Curve.easeOut, "bell" : Curve.bell, "parabolicAcceleration" : Curve.parabolicAcceleration, "parabolicDeceleration" : Curve.parabolicDeceleration, "parabolicPeak" : Curve.parabolicPeak, "parabolicBounce" : Curve.parabolicBounce, ] as [String : Parametric] var currentCurve: Parametric? { didSet { // Update the view. self.configureView(animated: true) } } private struct HermiteParameters { var gradientIn: Double var gradientOut: Double } private var hermiteParams = HermiteParameters(gradientIn: -2, gradientOut: -2) func setCurrentCurve(_ name: String) { switch name { case "hermite": self.currentCurve = HermiteCurve(gradientIn: hermiteParams.gradientIn, gradientOut: hermiteParams.gradientOut) case "composite": self.currentCurve = CompositeChooserViewController.bouncing() default: self.currentCurve = presetCurves[name] } } let numPoints = 71 var points = [UIView]() let timerLine = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 100)) let demoBox = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) let demoImage1 = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) let demoImage2 = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) let demoImage3 = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) let demoImage4 = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) private func installPointViews() { let curveRect = self.curveArea // Add the point views if required while(points.count < numPoints) { let newPoint = UIView(frame: CGRect(x: 0, y: 0, width: 3, height: 3)) let (pos, col) = curveData(for: points.count, in: curveRect) newPoint.center = pos newPoint.backgroundColor = col self.view.addSubview(newPoint) points.append(newPoint) } // Add the timer line and demo box timerLine.backgroundColor = UIColor.red demoBox.backgroundColor = UIColor.green <~~ 0.5 ~~> UIColor.black self.view.addSubview(timerLine) self.view.addSubview(demoBox) self.view.sendSubview(toBack: timerLine) // Add the image views let image = UIImage(named: "BoxStar") demoImage1.image = image demoImage2.image = image demoImage3.image = image demoImage4.image = image self.view.addSubview(demoImage1) self.view.addSubview(demoImage2) self.view.addSubview(demoImage3) self.view.addSubview(demoImage4) } private var curveArea: CGRect { get { let viewSize = self.view.frame.size return CGRect(x: viewSize.width * curveLeft, y: viewSize.height * curveTop, width: viewSize.width * curveWidth, height: viewSize.height * curveHeight) } } private var demoArea: CGRect { get { let viewSize = self.view.frame.size return CGRect(x: viewSize.width * demoLeft, y: viewSize.height * demoTop, width: viewSize.width * demoWidth, height: viewSize.height * demoHeight) } } private var uiArea: CGRect { get { let viewSize = self.view.frame.size return CGRect(x: viewSize.width * uiLeft, y: viewSize.height * uiTop, width: viewSize.width * uiWidth, height: viewSize.height * uiHeight) } } private func curveData(for point: Int, in rect: CGRect) -> (position: CGPoint, color: UIColor) { let curve = currentCurve ?? Curve.zero let xParam = Double(point) / Double(numPoints - 1) let yValue = curve[xParam] let pos = CGPoint(x: rect.origin.x + (rect.size.width * CGFloat(xParam)), y: rect.origin.y + (rect.size.height * CGFloat(1 - yValue))) let col = UIColor.blue <~~ yValue ~~> UIColor.black return (pos, col) } private func configureView(animated: Bool) { let curveRect = self.curveArea // Position each point in the curve for i in 0 ..< points.count { let pointView = points[i] let startPos = pointView.center let startCol = pointView.backgroundColor! let (endPos, endCol) = curveData(for: i, in: curveRect) switch(animated) { case true: Animation.animate(identifier: "point-\(i)", duration: 0.5, update: { (progress) -> Bool in pointView.center = startPos <~~ Curve.easeInEaseOut[progress] ~~> endPos pointView.backgroundColor = startCol <~~ progress ~~> endCol return true }) case false: pointView.center = endPos } } // Position the image demos let demoArea = self.demoArea let left = Double(demoArea.minX) let right = Double(demoArea.maxX) let bottom = Double(demoArea.maxY - (demoBoxSize.height / 2)) demoImage1.center = CGPoint(x: left <~~ 0.2 ~~> right, y: bottom) demoImage2.center = CGPoint(x: left <~~ 0.4 ~~> right, y: bottom) demoImage3.center = CGPoint(x: left <~~ 0.6 ~~> right, y: bottom) demoImage4.center = CGPoint(x: left <~~ 0.8 ~~> right, y: bottom) // Position any other UI elements changeCompositeButton?.isHidden = true changeHermiteButton?.isHidden = true let button = (currentCurve is HermiteCurve) ? changeHermiteButton : (currentCurve is CompositeCurve) ? changeCompositeButton : nil if let uiButton = button { let uiRect = self.uiArea let uiMiddle = CGPoint(x: uiRect.midX, y: uiRect.midY) let start = uiButton.center uiButton.isHidden = false Animation.animate(identifier: "uiElements", duration: 0.3, update: { (progress) -> Bool in uiButton.center = start <~~ Curve.easeInEaseOut[progress] ~~> uiMiddle return true }) } // Animate the timer-line and demo box startDemoAnimation() } private func startDemoAnimation() { var lineRect = self.curveArea var lineEnd = lineRect lineEnd.origin.x = lineRect.origin.x + lineRect.width lineRect.size.width = 1 lineEnd.size.width = 1 var boxRect = self.demoArea boxRect.origin.y = boxRect.origin.y + (boxRect.height / 2) - (demoBoxSize.height / 2) var boxEnd = boxRect boxEnd.origin.x = boxRect.origin.x + boxRect.width - demoBoxSize.width boxRect.size = demoBoxSize boxEnd.size = demoBoxSize let curve = currentCurve ?? Curve.zero Animation.animate(identifier: "demoAnimation", duration: 3, update: { (progress) -> Bool in let curveVal = curve[progress] let maxAngle = Double.pi / 2.0 // Timer-line animation (linear with progress) self.timerLine.frame = lineRect <~~ progress ~~> lineEnd // Demo box animation (left-to-right using curve value) self.demoBox.frame = boxRect <~~ curveVal ~~> boxEnd // Demo image animations (scale, inverse scale, rotation, inverse rotation) self.demoImage1.transform = CGAffineTransform(rotationAngle: CGFloat(0.0 <~~ curveVal ~~> maxAngle)) self.demoImage2.transform = CGAffineTransform(scaleX: CGFloat(curveVal), y: CGFloat(curveVal)) self.demoImage3.transform = CGAffineTransform(rotationAngle: CGFloat(maxAngle <~~ curveVal ~~> 0.0)) self.demoImage4.transform = CGAffineTransform(scaleX: CGFloat(1.0 + curveVal), y: CGFloat(1.0 + curveVal)) return true }, completion: { (_) in self.startDemoAnimation() }) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.installPointViews() } override func viewWillAppear(_ animated: Bool) { self.configureView(animated: false) } override func viewDidLayoutSubviews() { self.configureView(animated: true) } //: MARK - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showPopover") { switch segue.destination { case let hermiteVC as HermiteParametersViewController: hermiteVC.setGradients(in: hermiteParams.gradientIn, out: hermiteParams.gradientOut) hermiteVC.onApply = { [unowned self] (gIn, gOut) in self.hermiteParams.gradientIn = gIn self.hermiteParams.gradientOut = gOut self.setCurrentCurve("hermite") } case let compositeVC as CompositeChooserViewController: compositeVC.onApply = { [weak self] (curve) in self?.currentCurve = curve } default: break } return } } }
32.751799
113
0.688303
8f9af91d243f39ad7dfddbcf912645978545bf59
1,759
import Foundation import AppKit import Darwin var pasteboard = NSPasteboard.general func printInfo() { print(toJson(obj: ["count": pasteboard.changeCount, "types": pasteboard.types!])) } func printByType(type: NSString!) { let dataType = NSPasteboard.PasteboardType(rawValue: type as String) if let data = pasteboard.data(forType: dataType) { FileHandle.standardOutput.write(data) } } func setByType(type: NSString!) -> Bool { let dataType = NSPasteboard.PasteboardType(rawValue: type as String) let data = FileHandle.standardInput.readDataToEndOfFile() pasteboard.declareTypes([dataType], owner: nil) return pasteboard.setData(data, forType: dataType) } func toJson(obj: Any) -> NSString { let data = try! JSONSerialization.data(withJSONObject: obj) return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! } func printHelp() { print("Usage:\n -h, --help\tShow help\n -c, --count\tShow clipboard change count\n -i, --input <type>\tSet clipboard by type with content from stdin\n -o, --output <type>\tOutput clipboard content by type\n -s, --status\tShow clipboard information") } let args = CommandLine.arguments if (args.count <= 1) { printHelp() exit(1) } else if (args[1] == "--help" || args[1] == "-h") { printHelp() } else if (args[1] == "--count" || args[1] == "-c") { print(pasteboard.changeCount) } else if (args[1] == "--status" || args[1] == "-s") { printInfo() } else if (args.count >= 2 && (args[1] == "--input" || args[1] == "-i")) { exit(setByType(type: args[2] as NSString) ? 0 : 1) } else if (args.count >= 2 && (args[1] == "--output" || args[1] == "-o")) { printByType(type: args[2] as NSString) } else { printHelp() exit(1) }
29.813559
258
0.652075
fb239f052319e4c23efe7790aac2353acc69c264
463
// // LocalizedSegmentedControl.swift // EasyLocalizedStrings // // Created by Alex on 23/01/2019. // Copyright © 2019 Tucanae. All rights reserved. // import UIKit public class LocalizedSegmentedControl: UISegmentedControl { public var localizedKeys = [Int: String]() { didSet { for (index, key) in localizedKeys { setTitle(NSLocalizedString(key, comment: ""), forSegmentAt: index) } } } }
21.045455
82
0.62635
2255c615cc3c6457b0064dd3ae1f76fee7b48c45
1,741
// // ImageRowViewModel.swift // SwiftUIImageGallery // // Created by Lilia Dassine BELAID on 9/25/19. // Copyright © 2019 Lilia Dassine BELAID. All rights reserved. // import UIKit import Combine enum ImageLoadingError: Error { case incorrectData } class ImageRowViewModel: ObservableObject { @Published private(set) var image: UIImage? private let name: String private let url: URL private var cancellable: AnyCancellable? private let cache: NSCache<NSString, UIImage> = NSCache() init(name: String) { self.url = URL(string: APIConfig.url + APIConfig.imagePath)!.appendingPathComponent(name) self.name = name } deinit { cancellable?.cancel() } func load() { if let image = cache.object(forKey: name as NSString) { self.image = image } else { cancellable = URLSession .shared .dataTaskPublisher(for: url) .tryMap { [weak self] data, _ in guard let image = UIImage(data: data) else { throw ImageLoadingError.incorrectData } if let self = self { self.cache.setObject(image, forKey: self.name as NSString) } return image } .receive(on: DispatchQueue.main) .sink( receiveCompletion: { _ in }, receiveValue: { [weak self] image in self?.image = image } ) } } func cancel() { cancellable?.cancel() } }
25.985075
97
0.512349
9c5b3b4cd1a951015647ebced7353a485f6d707e
526
// // ViewController.swift // KeystoneCrypto // // Created by [email protected] on 01/25/2019. // Copyright (c) 2019 [email protected]. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
21.04
80
0.676806
e406f7adde0f7aa617291c949367e72c8ebbb1db
7,114
// // DPAGPreferencesShareExt.swift // SIMSmeCore // // Created by Robert Burchert on 01.07.19. // Copyright © 2020 ginlo.net GmbH. All rights reserved. // import AVFoundation import Foundation public protocol DPAGPreferencesShareExtProtocol: AnyObject { var isBaMandant: Bool { get } var isWhiteLabelBuild: Bool { get } var mandantIdent: String? { get } var mandantLabel: String? { get } var saltClient: String? { get } var companyIndexName: String? { get } var isCompanyManagedState: Bool { get } var canSendMedia: Bool { get } var autoSaveMedia: Bool { get } var canExportMedia: Bool { get } var saveImagesToCameraRoll: Bool { get } var sendNickname: Bool { get } var maximumNumberOfMediaAttachments: Int { get } var imageOptionsForSending: DPAGImageOptions { get } var videoOptionsForSending: DPAGVideoOptions { get } var maxLengthForSentVideos: TimeInterval { get } var maxFileSize: UInt64 { get } var mandantenDict: [String: DPAGMandant] { get } var sharedContainerConfig: DPAGSharedContainerConfig { get } var shareExtensionDevicePasstoken: String? { get } var shareExtensionDeviceGuid: String? { get } var contactsPrivateCount: Int { get } var contactsCompanyCount: Int { get } var contactsDomainCount: Int { get } var contactsPrivateFullTextSearchEnabled: Bool { get } var contactsCompanyFullTextSearchEnabled: Bool { get } var contactsDomainFullTextSearchEnabled: Bool { get } var lastRecentlyUsedContactsPrivate: [String] { get } var lastRecentlyUsedContactsCompany: [String] { get } var lastRecentlyUsedContactsDomain: [String] { get } func useDefaultColors() -> Bool func companyColorMain() -> UIColor func companyColorMainContrast() -> UIColor func companyColorAction() -> UIColor func companyColorActionContrast() -> UIColor func companyColorSecLevelHigh() -> UIColor func companyColorSecLevelHighContrast() -> UIColor func companyColorSecLevelMed() -> UIColor func companyColorSecLevelMedContrast() -> UIColor func companyColorSecLevelLow() -> UIColor func companyColorSecLevelLowContrast() -> UIColor func configure(container: DPAGSharedContainerExtensionSending.Container) } class DPAGPreferencesShareExt: DPAGPreferencesShareExtProtocol { var mandantIdent: String? { self.prefs?.mandantIdent ?? "ba" } var mandantLabel: String? { self.prefs?.mandantLabel ?? "Business" } var saltClient: String? { self.prefs?.saltClient ?? "$2a$04$Y5FhTtjHoIRLU99TNEXLSe" } var isWhiteLabelBuild: Bool { self.prefs?.isWhiteLabelBuild ?? true } var isBaMandant: Bool { self.prefs?.isBaMandant ?? true } var companyIndexName: String? { self.prefs?.companyIndexName } var isCompanyManagedState: Bool { self.prefs?.isCompanyManagedState ?? false } var canSendMedia: Bool { self.prefs?.canSendMedia ?? false } var autoSaveMedia: Bool = false var canExportMedia: Bool = false var saveImagesToCameraRoll: Bool = false var sendNickname: Bool { self.prefs?.sendNickname ?? false } var sharedContainerConfig: DPAGSharedContainerConfig { self.prefs?.sharedContainerConfig ?? DPAGSharedContainerConfig(keychainAccessGroupName: "???", groupID: "???", urlHttpService: "???") } var maximumNumberOfMediaAttachments: Int = 10 var imageOptionsForSending: DPAGImageOptions { if let l = self.prefs?.imageOptionsForSending { var s = l.size s.width = min(s.width, 1_920) s.height = min(s.height, 1_920) return DPAGImageOptions(size: s, quality: l.quality, interpolationQuality: l.interpolationQuality) } else { return DPAGImageOptions(size: CGSize(width: 1_024, height: 1_024), quality: 0.75, interpolationQuality: CGInterpolationQuality.default.rawValue) } } var videoOptionsForSending: DPAGVideoOptions { self.prefs?.videoOptionsForSending ?? DPAGVideoOptions(size: CGSize(width: 854, height: 480), bitrate: 800_000, fps: 30, profileLevel: AVVideoProfileLevelH264Baseline41) } var maxFileSize: UInt64 { self.prefs?.maxFileSize ?? 0x1E00000 } var maxLengthForSentVideos: TimeInterval { self.prefs?.maxLengthForSentVideos ?? 0 } var mandantenDict: [String: DPAGMandant] = [:] var shareExtensionDevicePasstoken: String? var shareExtensionDeviceGuid: String? var contactsPrivateCount: Int { self.prefs?.contactsPrivateCount ?? 0 } var contactsCompanyCount: Int { self.prefs?.contactsCompanyCount ?? 0 } var contactsDomainCount: Int { self.prefs?.contactsDomainCount ?? 0 } var contactsPrivateFullTextSearchEnabled: Bool { self.prefs?.contactsPrivateFullTextSearchEnabled ?? false } var contactsCompanyFullTextSearchEnabled: Bool { self.prefs?.contactsCompanyFullTextSearchEnabled ?? false } var contactsDomainFullTextSearchEnabled: Bool { self.prefs?.contactsDomainFullTextSearchEnabled ?? false } var lastRecentlyUsedContactsPrivate: [String] { self.prefs?.lastRecentlyUsedContactsPrivate ?? [] } var lastRecentlyUsedContactsCompany: [String] { self.prefs?.lastRecentlyUsedContactsCompany ?? [] } var lastRecentlyUsedContactsDomain: [String] { self.prefs?.lastRecentlyUsedContactsDomain ?? [] } private var prefs: DPAGSharedContainerExtensionSending.Preferences? func useDefaultColors() -> Bool { self.prefs?.colors.companyColorMain == nil } func companyColorMain() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorMain ?? 0xFFFFFF) } func companyColorMainContrast() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorMainContrast ?? 0x3E494E) } func companyColorAction() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorAction ?? 0x2083B0) } func companyColorActionContrast() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelHigh ?? 0xFFFFFF) } func companyColorSecLevelHigh() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelHigh ?? 0x83B37A) } func companyColorSecLevelHighContrast() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelHighContrast ?? 0xFFFFFF) } func companyColorSecLevelMed() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelMed ?? 0xFFCC00) } func companyColorSecLevelMedContrast() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelMedContrast ?? 0x3E494E) } func companyColorSecLevelLow() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelLow ?? 0xE94B57) } func companyColorSecLevelLowContrast() -> UIColor { UIColor(hex: self.prefs?.colors.companyColorSecLevelLowContrast ?? 0xFFFFFF) } func configure(container: DPAGSharedContainerExtensionSending.Container) { self.prefs = container.preferences self.mandantenDict = container.preferences.mandanten.reduce(into: [:]) { mandantenDict, mandant in mandantenDict[mandant.ident] = DPAGMandant(mandant: mandant) } self.shareExtensionDeviceGuid = container.device.guid self.shareExtensionDevicePasstoken = container.device.passToken } }
53.089552
222
0.736576
ff97436f31fb65d321afabf2020d9b5e18f5cbbe
980
// // GoBackTest.swift // AppiumSwiftClientUnitTests // // Created by Gabriel Fioretti on 05.05.20. // Copyright © 2020 KazuCocoa. All rights reserved. // import XCTest import Mockingjay @testable import AppiumSwiftClient class GoBackTest: AppiumSwiftClientTestBase { private var url = "http://127.0.0.1:4723/wd/hub/session/3CB9E12B-419C-49B1-855A-45322861F1F7/back" func testCanGoBack() { let response = """ {"value":""} """.data(using: .utf8)! func matcher(request: URLRequest) -> Bool { if (request.url?.absoluteString == url) { XCTAssertEqual(HttpMethod.post.rawValue, request.httpMethod) return true } else { return false } } stub(matcher, jsonData(response, status: 200)) let driver = try! AppiumDriver(AppiumCapabilities(super.iOSOpts)) XCTAssertNoThrow(try driver.back().get()) } }
27.222222
102
0.605102
2026a37c16e5bf1d9807040b4dcdd02b3bd7adf4
1,698
// // SchemaMutations.swift // GraphQL-Server // // Created by Rumata on 11/16/17. // // import Foundation import GraphQL import Graphiti enum SchemaMutations { static func addMutations(for schema: SchemaBuilder<NoRoot, RequestContext>) throws { try schema.mutation { builder in try createEvent(with: builder) try updateEvent(with: builder) try deleteEvent(with: builder) } } private struct HistoricalEventInputArguments : Arguments { let input: HistoricalEventInput static let descriptions = ["input": "content of the historical event"] } private static func createEvent(with builder: ObjectTypeBuilder<NoRoot, RequestContext, NoRoot>) throws { try builder.field(name: "createEvent", type: HistoricalEvent.self) { (_, arguments: HistoricalEventInputArguments, context, _) in try context.mongo.addHistoricalEvent(input: arguments.input) } } private static func updateEvent(with builder: ObjectTypeBuilder<NoRoot, RequestContext, NoRoot>) throws { try builder.field(name: "updateEvent", type: HistoricalEvent.self) { (_, arguments: HistoricalEventInputArguments, context, _) in try context.mongo.updateHistoricalEvent(input: arguments.input) } } struct HistoricalEventDeleteArguments : Arguments { let id: String static let descriptions = ["id": "id of the historical event"] } private static func deleteEvent(with builder: ObjectTypeBuilder<NoRoot, RequestContext, NoRoot>) throws { try builder.field(name: "deleteEvent", type: HistoricalEvent.self) { (_, arguments: HistoricalEventDeleteArguments, context, _) in try context.mongo.deleteHistoricalEvent(id: arguments.id) } } }
32.653846
134
0.735571
d7c87cde7aca0c8f2793a628a4042412a4f80b42
4,115
import XCTest import Cuckoo @testable import BitcoinCoreKit extension XCTestCase { func waitForMainQueue(queue: DispatchQueue = DispatchQueue.main) { let e = expectation(description: "Wait for Main Queue") queue.async { e.fulfill() } waitForExpectations(timeout: 2) } } public func equalErrors(_ lhs: Error?, _ rhs: Error?) -> Bool { lhs?.reflectedString == rhs?.reflectedString } public extension Error { var reflectedString: String { // NOTE 1: We can just use the standard reflection for our case String(reflecting: self) } // Same typed Equality func isEqual(to: Self) -> Bool { self.reflectedString == to.reflectedString } } extension Block { var header: BlockHeader { BlockHeader( version: version, headerHash: headerHash, previousBlockHeaderHash: previousBlockHash, merkleRoot: merkleRoot, timestamp: timestamp, bits: bits, nonce: nonce ) } func setHeaderHash(hash: Data) { headerHash = hash } } extension BlockInfo: Equatable { public static func ==(lhs: BlockInfo, rhs: BlockInfo) -> Bool { lhs.headerHash == rhs.headerHash && lhs.height == rhs.height && lhs.timestamp == rhs.timestamp } } extension TransactionInfo: Equatable { public static func ==(lhs: TransactionInfo, rhs: TransactionInfo) -> Bool { lhs.transactionHash == rhs.transactionHash } } extension PeerAddress: Equatable { public static func ==(lhs: PeerAddress, rhs: PeerAddress) -> Bool { lhs.ip == rhs.ip } } extension PublicKey: Equatable { public static func ==(lhs: PublicKey, rhs: PublicKey) -> Bool { lhs.path == rhs.path } } extension Checkpoint: Equatable { public static func ==(lhs: Checkpoint, rhs: Checkpoint) -> Bool { lhs.block == rhs.block } } extension Block: Equatable { public static func ==(lhs: Block, rhs: Block) -> Bool { lhs.headerHash == rhs.headerHash } } extension Transaction: Equatable { public static func ==(lhs: Transaction, rhs: Transaction) -> Bool { lhs.dataHash == rhs.dataHash } } extension Input: Equatable { public static func ==(lhs: Input, rhs: Input) -> Bool { lhs.previousOutputIndex == rhs.previousOutputIndex && lhs.previousOutputTxHash == rhs.previousOutputTxHash } } extension Output: Equatable { public static func ==(lhs: Output, rhs: Output) -> Bool { lhs.keyHash == rhs.keyHash && lhs.scriptType == rhs.scriptType && lhs.value == rhs.value && lhs.index == rhs.index } } extension BlockHeader: Equatable { public static func ==(lhs: BlockHeader, rhs: BlockHeader) -> Bool { lhs.previousBlockHeaderHash == rhs.previousBlockHeaderHash && lhs.headerHash == rhs.headerHash && lhs.merkleRoot == rhs.merkleRoot } } extension FullTransaction: Equatable { public static func ==(lhs: FullTransaction, rhs: FullTransaction) -> Bool { TransactionSerializer.serialize(transaction: lhs) == TransactionSerializer.serialize(transaction: rhs) } } extension UnspentOutput: Equatable { public static func ==(lhs: UnspentOutput, rhs: UnspentOutput) -> Bool { lhs.output.value == rhs.output.value } } extension InputToSign: Equatable { public static func ==(lhs: InputToSign, rhs: InputToSign) -> Bool { lhs.input == rhs.input && lhs.previousOutputPublicKey == rhs.previousOutputPublicKey } } func addressMatcher(_ address: Address) -> ParameterMatcher<Address> { ParameterMatcher<Address> { address.stringValue == $0.stringValue } } func addressMatcher(_ address: Address?) -> ParameterMatcher<Address?> { ParameterMatcher<Address?> { tested in if let a1 = address, let a2 = tested { return addressMatcher(a1).matches(a2) } else { return address == nil && tested == nil } } } func outputs(withScriptTypes scriptTypes: [ScriptType]) -> [Output] { scriptTypes.map { Output(withValue: 0, index: 0, lockingScript: Data(), type: $0) } }
24.349112
138
0.655407
acc927c3db04e7c50a8e1d8dcb4a6bd7c52bcb9e
499
// // DateFormatter.swift // Calendr // // Created by Paker on 01/01/21. // import Foundation extension DateFormatter { convenience init(locale: Locale?) { self.init() self.locale = locale } convenience init(format: String, locale: Locale?) { self.init(locale: locale) dateFormat = format } convenience init(template: String, locale: Locale?) { self.init(locale: locale) setLocalizedDateFormatFromTemplate(template) } }
19.192308
57
0.629259
bf1b069376a19e50d0094a9bfbe4ca801678baaa
24,131
//===----------------------------------------------------------------------===// // // This source file is part of the Box project. // // Copyright (c) 2019 Obuchi Yuki // This source file is released under the MIT License. // // See http://opensource.org/licenses/mit-license.php for license information // //===----------------------------------------------------------------------===// import Foundation //===----------------------------------------------------------------------===// // MARK: - TagID - //===----------------------------------------------------------------------===// /// Tag id with rawValue UInt8. /// This rawValue is equals to saved value. @usableFromInline enum TagID: UInt8 { case end = 0 case byte = 1 case short = 2 case int = 3 case long = 4 case float = 5 case double = 6 case string = 7 case list = 8 case compound = 9 case byteArray = 10 } //===----------------------------------------------------------------------===// // MARK: - TagFactory - //===----------------------------------------------------------------------===// @usableFromInline final internal class TagFactory { @inlinable @inline(__always) static func idFromType<T: Tag>(_ type:T.Type) -> TagID { if T.self == EndTag.self {return .end} if T.self == ByteTag.self {return .byte} if T.self == ShortTag.self {return .short} if T.self == IntTag.self {return .int} if T.self == LongTag.self {return .long} if T.self == FloatTag.self {return .float} if T.self == DoubleTag.self {return .double} if T.self == ByteArrayTag.self {return .byteArray} if T.self == StringTag.self {return .string} if T.self == ListTag.self {return .list} if T.self == CompoundTag.self {return .compound} fatalError("Not matching tag") } @inlinable @inline(__always) static func fromID(id: UInt8) throws -> Tag { guard let tag = TagID(rawValue: id) else { throw DecodingError.dataCorrupted( .init(codingPath: [], debugDescription: "Tag for id \(id) cannot be decoded.") ) } switch tag { case .end: return EndTag.shared case .byte: return ByteTag(value: nil) case .short: return ShortTag(value: nil) case .int: return IntTag(value: nil) case .long: return LongTag(value: nil) case .float: return FloatTag(value: nil) case .double: return DoubleTag(value: nil) case .byteArray: return ByteArrayTag(value: nil) case .string: return StringTag(value: nil) case .list: return ListTag(value: nil) case .compound: return CompoundTag(value: nil) } } } //===----------------------------------------------------------------------===// // MARK: - Tag - //===----------------------------------------------------------------------===// /// # Class `Tag` /// /// Represents non value type Tag. If use want to use tag with value use ValueTag instead. /// /// Tag serialization /// ### for Normal tag /// `| tag_id | name | value |` /// /// ### for End tag /// `| tag_id |` @usableFromInline internal class Tag { /// Subclass of Tag must implement tagID() to return own type. fileprivate func tagID() -> TagID { fatalError("Subclass of Tag must implement tagID().") } fileprivate static var useStructureCache:Bool = true // MARK: - Methods - /// //@usableFromInline //final func serialize(into dos: DataWriteStream, maxDepth:Int) throws { // // // serialize(into: dos, maxDepth: maxDepth) //} /// This method must be called from outside as root object. @usableFromInline final func serialize(into dos:BoxDataWriteStream, maxDepth:Int = Tag.defaultMaxDepth, useStructureCache:Bool) throws { Tag.useStructureCache = useStructureCache try _serialize(into: dos, named: "", maxDepth: maxDepth) } /// serialize data with name. for component final fileprivate func _serialize(into dos:BoxDataWriteStream, named name:String, maxDepth: Int) throws { let id = tagID() try dos.write(id.rawValue) if (id != .end) { try dos.write(name) } try serializeValue(into: dos, maxDepth: maxDepth) } /// deserialize input. static internal func deserialize(from dis: BoxDataReadStream, maxDepth:Int = Tag.defaultMaxDepth, useStructureCache:Bool) throws -> Tag { Tag.useStructureCache = useStructureCache let id = try dis.uInt8() let tag = try TagFactory.fromID(id: id) if (id != 0) { try tag.deserializeValue(from: dis, maxDepth: maxDepth); } return tag } /// decrement maxDepth use this method to decrease maxDepth. /// This method check if maxDepth match requirement. final fileprivate func decrementMaxDepth(_ maxDepth: Int) -> Int { assert(maxDepth > 0, "negative maximum depth is not allowed") assert(maxDepth != 0, "reached maximum depth of NBT structure") return maxDepth - 1 } // MARK: - Overridable Methods // Subclass of Tag must override those methods below to implement function. /// Subclass of Tag must override this method to serialize value. fileprivate func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { fatalError("Subclass of Tag must implement serializeValue(into:, _:).") } /// Subclass of Tag must override this method to deserialize value. fileprivate func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { fatalError("Subclass of Tag must implement deserializeValue(from:, _:).") } /// Subclass of Tag must override this method to retuen description of Value. fileprivate func valueString(maxDepth: Int) -> String { fatalError("Subclass of Tag must implement valueString(maxDepth:)") } } extension Tag { /// defalt max depth of deserialize. @usableFromInline static let defaultMaxDepth = 512 } extension Tag: CustomStringConvertible { @usableFromInline var description: String { return valueString(maxDepth: Tag.defaultMaxDepth) } } //===----------------------------------------------------------------------===// // MARK: - ValueTag - //===----------------------------------------------------------------------===// /// # Class `ValueTag<T>` /// /// This class represents tag with value. Use generics to represent value type. /// All Tag with value must stem from this class. @usableFromInline internal class ValueTag<T>: Tag { /// The type of value contained in ValueTag. @usableFromInline typealias Element = T /// The value of tag. /// Initirized from `init(value:)` or `deserializeValue(_:,_:)` @usableFromInline var value: T! /// The initirizer of `ValueTag`. You can initirize `ValueTag` value with nil or some @usableFromInline init(value:T? = nil) { self.value = value } /// This method returns the description of `ValueTag`. @inlinable @inline(__always) override func valueString(maxDepth: Int) -> String { return value.map{"\($0)"} ?? "nil" } } /// `ValueTag` with `Equatable` type can be `Equatable`. extension ValueTag: Equatable where Element: Equatable { @inlinable static func == (left:ValueTag, right:ValueTag) -> Bool { return left.value == right.value } } /// `ValueTag` with `Hashable` type can be `Hashable`. extension ValueTag: Hashable where Element: Hashable { @inlinable func hash(into hasher: inout Hasher) { hasher.combine(value) } } //===----------------------------------------------------------------------===// // MARK: - Implemention of Tags - //===----------------------------------------------------------------------===// //===----------------------------------===// // MARK: - EndTag - //===----------------------------------===// /// This tag represents Compound end or represents NULL /// Use like this /// /// `| compound_tag |...| end_tag |` /// or /// `| EndTag |` /// /// Compound type read file while reaches this tag. @usableFromInline final internal class EndTag: Tag { /// Shared instance of `EndTag`. @usableFromInline static let shared = EndTag() /// Make `EndTag`'s init inaccessible. private override init() { super.init() } final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.writeBytes(value: TagID.end.rawValue) } @inlinable final override func valueString(maxDepth: Int) -> String { return "\"end\"" } } //===----------------------------------===// // MARK: - ByteTag - //===----------------------------------===// /// This class represents tag of `Int8`. /// /// ### Serialize structure /// /// | tag_id | 1 byte | @usableFromInline internal final class ByteTag: ValueTag<Int8> { /// Initirize ByteTag with Bool value. @inlinable @inline(__always) internal init(flag: Bool) { super.init(value: flag ? 1 : 0) } /// Initirize ByteTag with Int8 value. @inlinable @inline(__always) internal override init(value: Int8?) { super.init(value: value) } /// Bool representation of Int8. @inlinable @inline(__always) internal var bool: Bool { return value != 0 } @inlinable @inline(__always) final override func tagID() -> TagID { return .byte } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.int8() } } //===----------------------------------===// // MARK: - ShortTag - //===----------------------------------===// /// This class represents tag of `Int16`. /// /// ### Serialize structure /// /// | tag_id | 2 bytes | @usableFromInline internal final class ShortTag: ValueTag<Int16> { @inlinable @inline(__always) final override func tagID() -> TagID { return .short } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.int16() } } //===----------------------------------===// // MARK: - IntTag - //===----------------------------------===// /// This class represents tag of `Int32`. /// /// ### Serialize structure /// /// | tag_id | 4 bytes | @usableFromInline internal final class IntTag: ValueTag<Int32> { @inlinable @inline(__always) final override func tagID() -> TagID { return .int } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.int32() } } //===----------------------------------===// // MARK: - LongTag - //===----------------------------------===// /// This class represents tag of `Int64`. /// /// ### Serialize structure /// /// | tag_id | 8 bytes | @usableFromInline internal final class LongTag: ValueTag<Int64> { @inlinable @inline(__always) final override func tagID() -> TagID { return .long } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.int64() } } //===----------------------------------===// // MARK: - FloatTag - //===----------------------------------===// /// This class represents tag of `Float`. /// /// ### Serialize structure /// /// | tag_id | 4 bytes | @usableFromInline internal final class FloatTag: ValueTag<Float> { @inlinable @inline(__always) final override func tagID() -> TagID { return .float } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.float() } } //===----------------------------------===// // MARK: - DoubleTag - //===----------------------------------===// /// This class represents tag of `Double`. /// /// ### Serialize structure /// /// | tag_id | 8 bytes | @usableFromInline internal final class DoubleTag: ValueTag<Double> { @inlinable @inline(__always) final override func tagID() -> TagID { return.double } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.double() } } //===----------------------------------===// // MARK: - StringTag - //===----------------------------------===// /// This class represents tag of `String`. /// Max String length is 255 /// /// ### Serialize structure /// /// | tag_id | length(1 bytes) | data(UTF)... | @usableFromInline internal final class StringTag: ValueTag<String> { @inlinable @inline(__always) final override func tagID() -> TagID { return .string } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(value) } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = try dis.string() } } //===----------------------------------===// // MARK: - ByteArrayTag - //===----------------------------------===// /// This class represents tag of `[Int8]`. /// /// ### Serialize structure /// /// | tag_id | length (4 bytes) | data...(1byte...) | @usableFromInline internal final class ByteArrayTag: ValueTag<[Int8]> { @inlinable @inline(__always) final override func tagID() -> TagID { return .byteArray } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(UInt32(value.count)) try value.forEach{ try dos.write($0) } } @usableFromInline final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { let length = try dis.uInt32() var _value = [Int8]() for _ in 0..<length { _value.append(try dis.int8()) } self.value = _value } } //===----------------------------------===// // MARK: - ListTag - //===----------------------------------===// /// This class represents tag of `[Tag]`. /// /// ListTag contains single type of tag. /// You must not put multiple type of tag into ListTag. /// /// ### Serialize structure /// /// ##### Empty /// /// `| tag_id | length(4 bytes) = 0 | ` /// /// ##### Not Empty /// /// `| tag_id | length(4 bytes) | value_tag_id (1 bytes) | ( value(ValueTag) )... |` @usableFromInline internal final class ListTag: ValueTag<[Tag]> { internal func add(_ tag:Tag) { self.value.append(tag) } @inlinable @inline(__always) final override func tagID() -> TagID { return .list } final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { try dos.write(UInt32(value.count)) guard !value.isEmpty else { return } let valuez = value[0] let tagId = valuez.tagID() try dos.write(tagId.rawValue) if Tag.useStructureCache && tagId == .compound { // FixCompoundのみ特例処理 try serializeFixCompound(into: dos, fixCompound: valuez as! CompoundTag, maxDepth: maxDepth) }else{ for element in value { try element.serializeValue(into: dos, maxDepth: decrementMaxDepth(maxDepth)) } } } final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = [] let size = try dis.uInt32() guard size != 0 else { return } let typeId = try dis.uInt8() if Tag.useStructureCache && typeId == TagID.compound.rawValue { // FixCompoundのみ特例処理 try deserializeFixCompound(from: dis, size:size, maxDepth: maxDepth) } else { for _ in 0..<size { let tag = try TagFactory.fromID(id: typeId) try tag.deserializeValue(from: dis, maxDepth: decrementMaxDepth(maxDepth)) self.value.append(tag) } } } // MARK: FixCompound serialize private final func serializeFixCompound(into dos: BoxDataWriteStream, fixCompound:CompoundTag , maxDepth: Int) throws { try fixCompound.serializeDataStructure(into: dos, maxDepth: maxDepth) for element in value { try (element as! CompoundTag).serializeValueFromList(into: dos, maxDepth: decrementMaxDepth(maxDepth)) } } private final func deserializeFixCompound(from dis: BoxDataReadStream, size: UInt32, maxDepth: Int) throws { let structure = try CompoundTag.deserializeFixCompoundStructure(from: dis, maxDepth: maxDepth) for _ in 0..<size { var dict = [String: Tag]() try CompoundTag.deserializeFixCompound(from: dis, structure: structure, into: &dict, maxDepth: maxDepth) self.value.append(CompoundTag(value: dict)) } } } // MARK: - _FixCompoundStructure - /// This class represents `FixCompound` structure. private struct _FixCompoundStructure { /// (name: UInt8 (tagID)) or /// (name: _FixCompoundStructure (child)) var children = [(String, Any)]() mutating func appendChild(_ tagID: UInt8, for name:String) { children.append((name, tagID)) } mutating func appendChild(_ structure: _FixCompoundStructure, for name:String) { children.append((name, structure)) } } //===----------------------------------===// // MARK: - CompoundTag - //===----------------------------------===// /// This class represents tag of `[Int64]`. /// /// ### Serialize structure /// /// /// ##### DataStructure /// /// | length(4 bytes) | (| name | tag_id |)... | /// /// The names must be ordered by name. /// /// ##### Data /// /// | tag_id | value(Value)... | @usableFromInline internal final class CompoundTag: ValueTag<[String: Tag]> { internal subscript(_ name:String) -> Tag? { set { value[name] = newValue } get { return value[name] } } @inlinable final override func tagID() -> TagID { return .compound } @usableFromInline final override func serializeValue(into dos: BoxDataWriteStream, maxDepth: Int) throws { for (key, value) in value.sorted(by: {$0.key < $1.key}) { try value._serialize(into: dos, named: key, maxDepth: decrementMaxDepth(maxDepth)) } try EndTag.shared.serializeValue(into: dos, maxDepth: decrementMaxDepth(maxDepth)) } @usableFromInline final func serializeValueFromList(into dos: BoxDataWriteStream, maxDepth: Int) throws { for (_, value) in value.sorted(by: {$0.key < $1.key}) { if let value = value as? CompoundTag { try value.serializeValueFromList(into: dos, maxDepth: decrementMaxDepth(maxDepth)) }else{ try value.serializeValue(into: dos, maxDepth: decrementMaxDepth(maxDepth)) } } } /// deserialize `FixCompound` with structure. fileprivate static func deserializeFixCompound( from dis: BoxDataReadStream, structure: _FixCompoundStructure, into dict: inout [String: Tag], maxDepth: Int ) throws { for (key, st) in structure.children { if let tagID = st as? UInt8 { let tag = try TagFactory.fromID(id: tagID) try tag.deserializeValue(from: dis, maxDepth: maxDepth - 1) dict[key] = tag }else if let str = st as? _FixCompoundStructure { var _dict = [String: Tag]() try deserializeFixCompound(from: dis, structure: str, into: &_dict, maxDepth: maxDepth - 1) dict[key] = CompoundTag(value: _dict) } } } // MARK: - Structure serialization /// This method serialize own Structure. fileprivate final func serializeDataStructure(into dos: BoxDataWriteStream, maxDepth:Int) throws { for (key, value) in value.sorted(by: {$0.key < $1.key}) { let id = value.tagID() try dos.write(id.rawValue) try dos.write(key) if id == .compound { try (value as! CompoundTag).serializeDataStructure(into: dos, maxDepth: decrementMaxDepth(maxDepth)) } } try EndTag.shared.serializeValue(into: dos, maxDepth: maxDepth) } /// This method deserialize own structure to `_FixCompoundStructure` fileprivate static func deserializeFixCompoundStructure(from dis: BoxDataReadStream, maxDepth: Int) throws -> _FixCompoundStructure { var structure = _FixCompoundStructure() var id = try dis.uInt8() if id == 0 { return structure } var name = try dis.string() if id == TagID.compound.rawValue { structure.appendChild(try deserializeFixCompoundStructure(from: dis, maxDepth: maxDepth), for: name) }else{ structure.appendChild(id, for: name) } while true { id = try dis.uInt8() if id == 0 { return structure } name = try dis.string() if id == TagID.compound.rawValue { structure.appendChild(try deserializeFixCompoundStructure(from: dis, maxDepth: maxDepth), for: name) }else{ structure.appendChild(id, for: name) } } } /// deserialize `FixCompound` without structure. /// add all value to tag and name. final override func deserializeValue(from dis: BoxDataReadStream, maxDepth: Int) throws { self.value = [:] var id = try dis.uInt8() if id == 0 { /// Empty CompoundTag return } var name = try dis.string() while true { let tag = try TagFactory.fromID(id: id) try tag.deserializeValue(from: dis, maxDepth: decrementMaxDepth(maxDepth)) value[name] = tag id = try dis.uInt8() if id == 0 { /// Read until End tag. break } name = try dis.string() } } }
29.828183
141
0.551656
9cb44f39a8fb3b40b92c1cf9213c54ca78d09698
2,314
// // SceneDelegate.swift // FrameworksExample // // Created by Luis Antonio Gomez Vazquez on 11/09/21. // 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.660377
147
0.71478
e024790e613594f156e5c4f1e0e5fabe8be51fa5
529
// // UIColorExtensions.swift // Droar // // Created by Nathan Jangula on 10/26/17. // import Foundation internal extension UIColor { static var droarBlue: UIColor { get { return UIColor(red: 45.0 / 255, green: 88.0 / 255, blue: 124.0/255, alpha: 1.0) } } static var droarGray: UIColor { get { return UIColor(red: 205.0 / 255, green: 207.0 / 255, blue: 209.0/255, alpha: 1.0) } } static var disabledGray: UIColor { get { return UIColor(white: 0.95, alpha: 1.0)} } }
23
97
0.597353
895ecf70e7303c50c72a33fc07b2aa8469d0c552
1,149
// https://github.com/Quick/Quick import Quick import Nimble import Fixer class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.529412
60
0.355091
1a847075545f47ab5f7452bc5feeeb78bd2f1c62
449
// 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 B{struct B{ enum S{struct b let _{let a{{b{{
37.416667
79
0.746102
3a75294b5eeb31b4e14135d38a46daf76e92031e
525
// // DocumentView.swift // Document Based App // // Created by user on 2020/03/22. // Copyright © 2020 256hax. All rights reserved. // import SwiftUI struct DocumentView: View { var document: UIDocument var dismiss: () -> Void var body: some View { VStack { HStack { Text("File Name") .foregroundColor(.secondary) Text(document.fileURL.lastPathComponent) } Button("Done", action: dismiss) } } }
18.75
56
0.540952
7589fd2c4c8d0f1669b1b08f57aa785a90c6eedb
15,679
// // AppConfigurationFetch.swift // DuckDuckGo // // Copyright © 2018 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import BackgroundTasks import Core import os.log public typealias AppConfigurationCompletion = (Bool) -> Void protocol CompletableTask { func setTaskCompleted(success: Bool) } @available(iOS 13.0, *) extension BGTask: CompletableTask { } protocol AppConfigurationFetchStatistics { var foregroundStartCount: Int { get set } var foregroundNoDataCount: Int { get set } var foregroundNewDataCount: Int { get set } var backgroundStartCount: Int { get set } var backgroundNoDataCount: Int { get set } var backgroundNewDataCount: Int { get set } var backgroundFetchTaskExpirationCount: Int { get set } } class AppConfigurationFetch { struct Constants { static let backgroundTaskName = "Fetch Configuration Task" static let backgroundProcessingTaskIdentifier = "com.duckduckgo.app.configurationRefresh" static let minimumConfigurationRefreshInterval: TimeInterval = 60 * 30 } private struct Keys { static let bgFetchType = "bgft" static let bgFetchTypeBackgroundTasks = "bgbt" static let bgFetchTypeLegacy = "bgl" static let bgFetchTaskExpiration = "bgte" static let bgFetchTaskDuration = "bgtd" static let bgFetchStart = "bgfs" static let bgFetchNoData = "bgnd" static let bgFetchWithData = "bgwd" static let fgFetchStart = "fgfs" static let fgFetchNoData = "fgnd" static let fgFetchWithData = "fgwd" static let fetchHTTPSBloomFilterSpec = "d1" static let fetchHTTPSBloomFilter = "d2" static let fetchHTTPSExcludedDomainsCount = "d3" static let fetchSurrogatesCount = "d4" static let fetchTrackerDataSetCount = "d5" static let fetchPrivacyConfigurationCount = "d7" } private static let fetchQueue = DispatchQueue(label: "Config Fetch queue", qos: .utility) @UserDefaultsWrapper(key: .lastConfigurationRefreshDate, defaultValue: .distantPast) static private var lastConfigurationRefreshDate: Date @UserDefaultsWrapper(key: .backgroundFetchTaskDuration, defaultValue: 0) static private var backgroundFetchTaskDuration: Int @UserDefaultsWrapper(key: .downloadedHTTPSBloomFilterSpecCount, defaultValue: 0) private var downloadedHTTPSBloomFilterSpecCount: Int @UserDefaultsWrapper(key: .downloadedHTTPSBloomFilterCount, defaultValue: 0) private var downloadedHTTPSBloomFilterCount: Int @UserDefaultsWrapper(key: .downloadedHTTPSExcludedDomainsCount, defaultValue: 0) private var downloadedHTTPSExcludedDomainsCount: Int @UserDefaultsWrapper(key: .downloadedSurrogatesCount, defaultValue: 0) private var downloadedSurrogatesCount: Int @UserDefaultsWrapper(key: .downloadedTrackerDataSetCount, defaultValue: 0) private var downloadedTrackerDataSetCount: Int @UserDefaultsWrapper(key: .downloadedPrivacyConfigurationCount, defaultValue: 0) private var downloadedPrivacyConfigurationCount: Int static private var shouldRefresh: Bool { return Date().timeIntervalSince(Self.lastConfigurationRefreshDate) > Constants.minimumConfigurationRefreshInterval } enum BackgroundRefreshCompletionStatus { case expired case noData case newData var success: Bool { self != .expired } } func start(isBackgroundFetch: Bool = false, completion: AppConfigurationCompletion?) { guard Self.shouldRefresh else { // Statistics are not sent after a successful background refresh in order to reduce the time spent in the background, so they are checked // here in case a background refresh has happened recently. Self.fetchQueue.async { self.sendStatistics { completion?(false) } } return } type(of: self).fetchQueue.async { let taskID = UIApplication.shared.beginBackgroundTask(withName: Constants.backgroundTaskName) let fetchedNewData = self.fetchConfigurationFiles(isBackground: isBackgroundFetch) if !isBackgroundFetch { type(of: self).fetchQueue.async { self.sendStatistics { UIApplication.shared.endBackgroundTask(taskID) } } } else { UIApplication.shared.endBackgroundTask(taskID) } completion?(fetchedNewData) } } @available(iOS 13.0, *) static func registerBackgroundRefreshTaskHandler() { BGTaskScheduler.shared.register(forTaskWithIdentifier: Constants.backgroundProcessingTaskIdentifier, using: nil) { (task) in guard shouldRefresh else { task.setTaskCompleted(success: true) scheduleBackgroundRefreshTask() return } let store = AppUserDefaults() let fetcher = AppConfigurationFetch() backgroundRefreshTaskHandler(store: store, configurationFetcher: fetcher, queue: fetchQueue, task: task) } } @available(iOS 13.0, *) static func scheduleBackgroundRefreshTask() { let task = BGProcessingTaskRequest(identifier: AppConfigurationFetch.Constants.backgroundProcessingTaskIdentifier) task.requiresNetworkConnectivity = true task.earliestBeginDate = Date(timeIntervalSinceNow: Constants.minimumConfigurationRefreshInterval) // Background tasks can be debugged by breaking on the `submit` call, stepping over, then running the following LLDB command, before resuming: // // e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.duckduckgo.app.configurationRefresh"] // // Task expiration can be simulated similarly: // // e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.duckduckgo.app.configurationRefresh"] #if !targetEnvironment(simulator) do { try BGTaskScheduler.shared.submit(task) } catch { Pixel.fire(pixel: .backgroundTaskSubmissionFailed, error: error) } #endif } @discardableResult private func fetchConfigurationFiles(isBackground: Bool) -> Bool { self.markFetchStarted(isBackground: isBackground) var newData = false let semaphore = DispatchSemaphore(value: 0) AppDependencyProvider.shared.storageCache.update(progress: updateFetchProgress) { newCache in newData = newData || (newCache != nil) semaphore.signal() } semaphore.wait() self.markFetchCompleted(isBackground: isBackground, hasNewData: newData) return newData } private func markFetchStarted(isBackground: Bool) { var store: AppConfigurationFetchStatistics = AppUserDefaults() if isBackground { store.backgroundStartCount += 1 } else { store.foregroundStartCount += 1 } } private func updateFetchProgress(configuration: ContentBlockerRequest.Configuration) { switch configuration { case .httpsBloomFilter: downloadedHTTPSBloomFilterCount += 1 case .httpsBloomFilterSpec: downloadedHTTPSBloomFilterSpecCount += 1 case .httpsExcludedDomains: downloadedHTTPSExcludedDomainsCount += 1 case .surrogates: downloadedSurrogatesCount += 1 case .trackerDataSet: downloadedTrackerDataSetCount += 1 case .privacyConfiguration: downloadedPrivacyConfigurationCount += 1 } } private func markFetchCompleted(isBackground: Bool, hasNewData: Bool) { var store: AppConfigurationFetchStatistics = AppUserDefaults() if isBackground { if hasNewData { store.backgroundNewDataCount += 1 } else { store.backgroundNoDataCount += 1 } } else { if hasNewData { store.foregroundNewDataCount += 1 } else { store.foregroundNoDataCount += 1 } } Self.lastConfigurationRefreshDate = Date() } private func sendStatistics(completion: () -> Void ) { let store: AppConfigurationFetchStatistics = AppUserDefaults() guard store.foregroundStartCount > 0 || store.backgroundStartCount > 0 else { completion() return } let backgroundFetchType: String if #available(iOS 13.0, *) { backgroundFetchType = Keys.bgFetchTypeBackgroundTasks } else { backgroundFetchType = Keys.bgFetchTypeLegacy } let parameters = [Keys.bgFetchStart: String(store.backgroundStartCount), Keys.bgFetchNoData: String(store.backgroundNoDataCount), Keys.bgFetchWithData: String(store.backgroundNewDataCount), Keys.fgFetchStart: String(store.foregroundStartCount), Keys.fgFetchNoData: String(store.foregroundNoDataCount), Keys.fgFetchWithData: String(store.foregroundNewDataCount), Keys.bgFetchType: backgroundFetchType, Keys.bgFetchTaskExpiration: String(store.backgroundFetchTaskExpirationCount), Keys.bgFetchTaskDuration: String(Self.backgroundFetchTaskDuration), Keys.fetchHTTPSBloomFilterSpec: String(downloadedHTTPSBloomFilterSpecCount), Keys.fetchHTTPSBloomFilter: String(downloadedHTTPSBloomFilterCount), Keys.fetchHTTPSExcludedDomainsCount: String(downloadedHTTPSExcludedDomainsCount), Keys.fetchSurrogatesCount: String(downloadedSurrogatesCount), Keys.fetchTrackerDataSetCount: String(downloadedTrackerDataSetCount), Keys.fetchPrivacyConfigurationCount: String(downloadedPrivacyConfigurationCount)] let semaphore = DispatchSemaphore(value: 0) Pixel.fire(pixel: .configurationFetchInfo, withAdditionalParameters: parameters) { error in guard error == nil else { semaphore.signal() return } self.resetStatistics() semaphore.signal() } semaphore.wait() completion() } private func resetStatistics() { var store: AppConfigurationFetchStatistics = AppUserDefaults() store.backgroundStartCount = 0 store.backgroundNoDataCount = 0 store.backgroundNewDataCount = 0 store.foregroundStartCount = 0 store.foregroundNoDataCount = 0 store.foregroundNewDataCount = 0 store.backgroundFetchTaskExpirationCount = 0 Self.backgroundFetchTaskDuration = 0 downloadedHTTPSBloomFilterCount = 0 downloadedHTTPSBloomFilterSpecCount = 0 downloadedHTTPSExcludedDomainsCount = 0 downloadedSurrogatesCount = 0 downloadedTrackerDataSetCount = 0 downloadedPrivacyConfigurationCount = 0 } } extension AppConfigurationFetch { @available(iOS 13.0, *) static func backgroundRefreshTaskHandler(store: AppConfigurationFetchStatistics, configurationFetcher: AppConfigurationFetch, queue: DispatchQueue, task: BGTask) { let refreshStartDate = Date() var lastCompletionStatus: BackgroundRefreshCompletionStatus? task.expirationHandler = { DispatchQueue.main.async { if lastCompletionStatus == nil { var mutableStore = store mutableStore.backgroundFetchTaskExpirationCount += 1 } lastCompletionStatus = backgroundRefreshTaskCompletionHandler(store: store, refreshStartDate: refreshStartDate, task: task, status: .expired, previousStatus: lastCompletionStatus) } } queue.async { let fetchedNewData = configurationFetcher.fetchConfigurationFiles(isBackground: true) ContentBlockerRulesManager.shared.recompile() DispatchQueue.main.async { lastCompletionStatus = backgroundRefreshTaskCompletionHandler(store: store, refreshStartDate: refreshStartDate, task: task, status: fetchedNewData ? .newData : .noData, previousStatus: lastCompletionStatus) } } } // Gets called at the end of the refresh process, either by the task being expired by the OS or by the refresh process completing successfully. // It checks whether it has been called earlier in the same refresh run and self-corrects the completion statistics if necessary. @available(iOS 13.0, *) static func backgroundRefreshTaskCompletionHandler(store: AppConfigurationFetchStatistics, refreshStartDate: Date, task: CompletableTask, status: BackgroundRefreshCompletionStatus, previousStatus: BackgroundRefreshCompletionStatus?) -> BackgroundRefreshCompletionStatus { task.setTaskCompleted(success: status.success) scheduleBackgroundRefreshTask() let refreshEndDate = Date() let difference = refreshEndDate.timeIntervalSince(refreshStartDate) backgroundFetchTaskDuration += Int(difference) // This function tries to avoid expirations that are counted erroneously, so in the case where an expiration comes in _just_ before the // refresh process completes it checks if an expiration was last processed and decrements the expiration counter so that the books balance. if previousStatus == .expired { var mutableStore = store mutableStore.backgroundFetchTaskExpirationCount = max(0, store.backgroundFetchTaskExpirationCount - 1) } return status } }
41.044503
150
0.630908
1d92f8ebe8c3359d90bcc04912f69dc665ccdf2e
4,033
// // NetworkLayer.swift // CarLocator // // Created by Amitabha Saha on 24/09/21. // import Foundation import UIKit.UIApplication class NetworkLayer: NSObject { var urlSessionDefaultConfig: URLSession { get{ let configuration: URLSessionConfiguration = URLSessionConfiguration.default configuration.waitsForConnectivity = false configuration.multipathServiceType = .none let delegate = SessionManagerDelegate() delegate.networkRequest = self return URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) } } var didReceiveData: ((_ count: Int?) -> ())? var didFinishDownloadedData: ((_ data: Data?, _ error: Error?, _ request: URLRequest?, _ response: URLResponse?) -> ())? var didFinishWithError: (( _ error: Error?, _ request: URLRequest?, _ response: URLResponse?) -> ())? var port: Int? var isProgressing = false var localResponse: localJSON? var request: HTTPrequest? internal var task: URLSessionTask? internal var resumeData: Data? internal var url: URL! // earliest begin date var earliestBeginDate: Date? public func resumeTask(){ if let localResponse = localResponse, localResponse.0 { if let url = Bundle.main.url(forResource: localResponse.1, withExtension: "json"), let data = try? Data(contentsOf: url) { didFinishDownloadedData?(data, nil, nil, nil) } else { didFinishDownloadedData?(nil, ResponseError.NoLocalData, nil, nil) } return } if let request = request, let url = URL.init(string: request.url){ let urlRequest = NSMutableURLRequest.init(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30.0) urlRequest.httpMethod = request.method if let headers = request.headers { urlRequest.allHTTPHeaderFields = headers as? [String : String] } if let headers = request.headers as? [String: String] { for (key, value) in headers { if urlRequest.value(forHTTPHeaderField: key) == nil { urlRequest.setValue(value, forHTTPHeaderField: key) } } } if let headers = request.body { do { let data = try JSONSerialization.data(withJSONObject: headers, options:JSONSerialization.WritingOptions()) urlRequest.httpBody = data } catch {} } if let beginDate = earliestBeginDate{ self.task?.earliestBeginDate = beginDate } self.task = urlSessionDefaultConfig.dataTask(with: urlRequest as URLRequest) self.task?.resume() } } public func resumeTaskWithDownloadedData() { if let _ = self.task as? URLSessionDownloadTask{ if let resumeData = resumeData{ let downloadTask = urlSessionDefaultConfig.downloadTask(withResumeData: resumeData) self.task = downloadTask }else{ let downloadTask = urlSessionDefaultConfig.downloadTask(with: self.url) self.task = downloadTask } } self.task?.resume() } public func cancel(){ self.task?.cancel() } public func pause(){ if self.isProgressing{ if let task = self.task as? URLSessionDownloadTask{ task.cancel(byProducingResumeData: { data in self.resumeData = data }) } self.isProgressing = false } } }
32.264
139
0.554178
91dc5b03dca78a9f5c3b4e46ebd1fc9b7e90f3a3
8,708
// // CityView.swift // LuohenWeather (iOS) // // Created by 杨立鹏 on 2021/12/30. // import SwiftUI struct CityView: View { var topItemHeight: CGFloat = 70 var dayWeatherHeight: CGFloat = 140 @StateObject var dataModel = HomeViewModel() var city: CityModel var body: some View { GeometryReader { proxy in ScrollView(showsIndicators: false) { let height = proxy.size.height - 10 - topItemHeight - 10 - dayWeatherHeight - 30 - 10 VStack(spacing: 10) { currentWeather(height: height) currentAir() HStack { GeometryReader { proxy in let width = proxy.size.width let itemWidth = width / 4 topItem(title: "体感", value: "\(dataModel.currentWeather.feelsLike)℃") .frame(width: itemWidth) topItem(title: "湿度", value: "\(dataModel.currentWeather.humidity)%") .frame(width: itemWidth) .offset(x: itemWidth) topItem(title: "风力", value: "\(dataModel.currentWeather.windDir)\(dataModel.currentWeather.windScale)级") .frame(width: itemWidth) .offset(x: itemWidth * 2) topItem(title: "气压", value: "\(dataModel.currentWeather.pressure)hPa") .frame(width: itemWidth) .offset(x: itemWidth * 3) } } .contentBackground(height: topItemHeight) HStack { GeometryReader { proxy in let width = proxy.size.width let itemWidth = width / 3 dayWeatherItem(day: "今天", weather: "晴", temperature: "-2~11℃") .frame(width: itemWidth) dayWeatherItem(day: "明天", weather: "晴转多云", temperature: "-10~1℃") .frame(width: itemWidth) .offset(x: itemWidth) dayWeatherItem(day: "后天", weather: "小雪", temperature: "-10~-1℃") .frame(width: itemWidth) .offset(x: itemWidth * 2) } } .foregroundColor(.textColor) .contentBackground(height: dayWeatherHeight) FifteenDailyWeatherView(dailyWeather: dataModel.dailyWeather) .contentBackground(height: 400) AirQualityView(air: dataModel.currentAir) .contentBackground(height: 180) HStack { VStack(alignment: .leading, spacing: 0) { Text("太阳和月亮").padding(8) HStack(spacing: 0) { ForEach(0 ..< 2) { _ in VStack { Canvas { context, size in var path = Path() path.move(to: CGPoint(x: 0, y: size.height)) path.addLine(to: CGPoint(x: size.width, y: size.height)) context.stroke(path, with: .color(.subTextColor), lineWidth: 3) var circle = Path() circle.addArc(center: CGPoint(x: size.width / 2, y: size.height), radius: size.width / 3, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 180), clockwise: true, transform: .identity) context.stroke(circle, with: .color(Color.subTextColor), lineWidth: 2) } HStack(spacing: 0) { VStack { Text("日出") Text("07:36") } Spacer() VStack { Text("日出") Text("19:36") } } .font(.system(size: 14)) } // .background(.blue) .padding(2) } .frame(maxWidth: .infinity) } .frame(maxHeight: .infinity) } } .contentBackground(height: 150) HStack { Text("Powered by Luohen") .foregroundColor(.subTextColor) } .contentBackground(height: 40) } .padding(.bottom, 10) } } // .frame(maxHeight: .infinity) .padding(.horizontal, 16) .task { dataModel.refreshData(cityId: city.id ?? "") } .onReceive(NotificationCenter.default.publisher(for: Notification.Name("indexChanged"), object: nil)) { _ in NotificationCenter.default.post(name: NSNotification.Name("CurrentCityWeather"), object: nil, userInfo: [ "currentWeather": dataModel.currentWeather, // "city": city!.id, ]) } } @ViewBuilder func currentWeather(height: CGFloat) -> some View { VStack { HStack { Text(dataModel.currentWeather.temp) .font(.system(size: 100, weight: .medium, design: .default)) VStack { Text("℃") .offset(y: -15) Text(dataModel.currentWeather.text) .font(.system(size: 20)) .fontWeight(.medium) .offset(y: 15) } } Text("12月30日 农历十一月廿七") } .foregroundColor(.white) .frame(height: height) } @ViewBuilder func currentAir() -> some View { HStack { Spacer() HStack { Image(systemName: "leaf") .foregroundColor(.green) Text("\(dataModel.currentAir.aqi) 空气\(dataModel.currentAir.category)") .foregroundColor(.white) } .font(.footnote) .frame(height: 30) .padding(.horizontal, 10) .background(.black.opacity(0.5)) .cornerRadius(15) } } @ViewBuilder func topItem(title: String, value: String) -> some View { VStack(spacing: 0) { Text(value) .padding(.top, 10) .font(.system(size: 18)) .foregroundColor(Color(red: 0.1, green: 0.1, blue: 0.1)) Text(title) .padding(.top, 5) .font(.system(size: 16, weight: .medium)) .foregroundColor(Color(red: 0.1, green: 0.1, blue: 0.1)) .opacity(0.7) } } @ViewBuilder func dayWeatherItem(day: String, weather: String, temperature: String) -> some View { VStack(spacing: 0) { Text(day) .padding(.top, 10) Image(systemName: "sun.max") .font(.system(size: 20)) Text(weather) .padding(.top, 10) Text(temperature) .padding(.top, 5) } } } struct HomeContentBackground: ViewModifier { var height: CGFloat func body(content: Content) -> some View { content .frame(maxWidth: .infinity) .frame(height: height) .background(Color.themeWhite.opacity(0.8)) .cornerRadius(10) } } extension View { func contentBackground(height: CGFloat) -> some View { modifier(HomeContentBackground(height: height)) } } struct CityView_Previews: PreviewProvider { static var previews: some View { getHomeViewPreviews() } }
37.86087
234
0.417088
f77c31c1d1303783021c92fe8a06284ce00c96e1
2,273
// // LayoutItem.swift // LayoutBuilder // // Created by Ihor Malovanyi on 10.05.2021. // #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif public struct LBLayoutItem { var view: View var attribute: NSLayoutConstraint.Attribute func equal(to relationItem: LBLayoutRelationItem, inset: Bool = false) -> NSLayoutConstraint { makeConstraint(item: self, relationItem: relationItem, relation: .equal, inset: inset) } func greaterThanOrEqual(to relationItem: LBLayoutRelationItem, inset: Bool = false) -> NSLayoutConstraint { makeConstraint(item: self, relationItem: relationItem, relation: .greaterThanOrEqual, inset: inset) } func lessThanOrEqual(to relationItem: LBLayoutRelationItem, inset: Bool = false) -> NSLayoutConstraint { makeConstraint(item: self, relationItem: relationItem, relation: .lessThanOrEqual, inset: inset) } internal func makeConstraint(item: LBLayoutItem, relationItem: LBLayoutRelationItem, relation: NSLayoutConstraint.Relation, inset: Bool = false) -> NSLayoutConstraint { var relationView = relationItem.view var relationAttribute = relationItem.attribute == .notAnAttribute ? item.attribute : relationItem.attribute let isRevercedAttribute = [NSLayoutConstraint.Attribute.right, .bottom].contains(relationAttribute) if relationItem.view == nil && relationItem.attribute == .notAnAttribute && ![NSLayoutConstraint.Attribute.width, .height].contains(item.attribute) { relationView = item.view.superview relationAttribute = item.attribute } let result = NSLayoutConstraint(item: item.view, attribute: item.attribute, relatedBy: relation, toItem: relationView, attribute: relationAttribute, multiplier: relationItem.multiplier.cgFloatValue, constant: isRevercedAttribute && inset ? -relationItem.constant.cgFloatValue : relationItem.constant.cgFloatValue) result.priority = relationItem.priority return result } }
40.589286
172
0.661681
0381ec17658fc76b3273af52160262d7362c4995
516
// // unitHelpers.swift // WeatherApp // // Created by Andrew Lofthouse on 06/08/2018. // Copyright © 2018 Andrew Lofthouse. All rights reserved. // import Foundation class unitHelpers { // function to convert kelvin to Celsius public func kelvinToCelcius(temp : Float) -> Float { return temp - 273.15 } // function to convert kelvin to Fahrenheit public func kelvinToFahrenheit(temp : Float) -> Float { return temp * (9/5) - 459.67 } }
19.846154
59
0.614341
3a6b63afcc38938a228e194b97bd70630b4f71b6
4,189
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore // MARK: Paginators extension EKS { /// Lists the Amazon EKS clusters in your AWS account in the specified Region. public func listClustersPaginator( _ input: ListClustersRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListClustersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listClusters, tokenKey: \ListClustersResponse.nextToken, on: eventLoop, onPage: onPage) } /// Lists the AWS Fargate profiles associated with the specified cluster in your AWS account in the specified Region. public func listFargateProfilesPaginator( _ input: ListFargateProfilesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListFargateProfilesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listFargateProfiles, tokenKey: \ListFargateProfilesResponse.nextToken, on: eventLoop, onPage: onPage) } /// Lists the Amazon EKS managed node groups associated with the specified cluster in your AWS account in the specified Region. Self-managed node groups are not listed. public func listNodegroupsPaginator( _ input: ListNodegroupsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListNodegroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listNodegroups, tokenKey: \ListNodegroupsResponse.nextToken, on: eventLoop, onPage: onPage) } /// Lists the updates associated with an Amazon EKS cluster or managed node group in your AWS account, in the specified Region. public func listUpdatesPaginator( _ input: ListUpdatesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListUpdatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listUpdates, tokenKey: \ListUpdatesResponse.nextToken, on: eventLoop, onPage: onPage) } } extension EKS.ListClustersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EKS.ListClustersRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension EKS.ListFargateProfilesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EKS.ListFargateProfilesRequest { return .init( clusterName: self.clusterName, maxResults: self.maxResults, nextToken: token ) } } extension EKS.ListNodegroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EKS.ListNodegroupsRequest { return .init( clusterName: self.clusterName, maxResults: self.maxResults, nextToken: token ) } } extension EKS.ListUpdatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> EKS.ListUpdatesRequest { return .init( maxResults: self.maxResults, name: self.name, nextToken: token, nodegroupName: self.nodegroupName ) } }
38.431193
173
0.673192
d6a9d220b5a73b9769da239eda21b816185f749b
657
import SFBRBazelRemoteAPI typealias ServerCapabilities = Build_Bazel_Remote_Execution_V2_ServerCapabilities typealias ExecutionCapabilities = Build_Bazel_Remote_Execution_V2_ExecutionCapabilities typealias CacheCapabilities = Build_Bazel_Remote_Execution_V2_CacheCapabilities typealias SymlinkAbsolutePathStrategy = Build_Bazel_Remote_Execution_V2_SymlinkAbsolutePathStrategy typealias ActionCacheUpdateCapabilities = Build_Bazel_Remote_Execution_V2_ActionCacheUpdateCapabilities typealias PriorityCapabilities = Build_Bazel_Remote_Execution_V2_PriorityCapabilities typealias GetCapabilitiesRequest = Build_Bazel_Remote_Execution_V2_GetCapabilitiesRequest
65.7
103
0.942161
c1d925b84662075f152d1040d1aec508471c6929
195
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct g<g where f=c{let:c
39
87
0.769231
db083b74ec09e8fc152b8273e2d20c1d88c1a990
225
type messagefile; p() { m = "hi"; } (messagefile t) greeting() { app { echo m stdout=@filename(t); } } global string m; messagefile outfile <"1231-global-assign-inside.out">; outfile = greeting(); p();
11.842105
54
0.595556
0301d22cd58a4580735250e8053c36d035d5e44e
3,956
// RUN: %target-resilience-test // REQUIRES: executable_test // REQUIRES: no_asan import StdlibUnittest import class_change_size // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate import SwiftPrivatePthreadExtras #if _runtime(_ObjC) import ObjectiveC #endif var ClassChangeSizeTest = TestSuite("ClassChangeSize") func increment(c: inout ChangeSize) { c.version += 1 } // Change field offsets and size of a class from a different // resilience domain ClassChangeSizeTest.test("ChangeFieldOffsetsOfFixedLayout") { let t = ChangeFieldOffsetsOfFixedLayout(major: 7, minor: 5, patch: 3) do { expectEqual(t.getVersion(), "7.5.3") } do { t.minor.version = 1 t.patch.version = 2 expectEqual(t.getVersion(), "7.1.2") } do { increment(&t.patch) expectEqual(t.getVersion(), "7.1.3") } } // Superclass and subclass are in a different resilience domain ClassChangeSizeTest.test("ChangeSizeOfSuperclass") { let t = ChangeSizeOfSuperclass() do { expectEqual(t.getVersion(), "7.0.0 (Big Bang)") } do { t.major.version = 6 t.minor.version = 0 t.patch.version = 5 t.codename = "Big Deal" expectEqual(t.getVersion(), "6.0.5 (Big Deal)") } do { increment(&t.patch) t.codename = "Six Pack" expectEqual(t.getVersion(), "6.0.6 (Six Pack)") } } // Change field offsets and size of a class from the current // resilience domain class ChangeFieldOffsetsOfMyFixedLayout { init(major: Int32, minor: Int32, patch: Int32) { self.major = ChangeSize(version: major) self.minor = ChangeSize(version: minor) self.patch = ChangeSize(version: patch) } var major: ChangeSize var minor: ChangeSize var patch: ChangeSize func getVersion() -> String { return "\(major.version).\(minor.version).\(patch.version)" } } ClassChangeSizeTest.test("ChangeFieldOffsetsOfMyFixedLayout") { let t = ChangeFieldOffsetsOfMyFixedLayout(major: 9, minor: 2, patch: 1) do { expectEqual(t.getVersion(), "9.2.1") } do { t.major.version = 7 t.minor.version = 6 t.patch.version = 1 expectEqual(t.getVersion(), "7.6.1") } do { increment(&t.patch) expectEqual(t.getVersion(), "7.6.2") } } // Subclass is in our resilience domain, superclass is in a // different resilience domain class MyChangeSizeOfSuperclass : ChangeFieldOffsetsOfFixedLayout { init() { self.codename = "Road Warrior" super.init(major: 7, minor: 0, patch: 1) } var codename: String override func getVersion() -> String { return "\(super.getVersion()) (\(codename))"; } } ClassChangeSizeTest.test("MyChangeSizeOfSuperclass") { let t = MyChangeSizeOfSuperclass() do { expectEqual(t.getVersion(), "7.0.1 (Road Warrior)") } do { t.minor.version = 5 t.patch.version = 2 t.codename = "Marconi" expectEqual(t.getVersion(), "7.5.2 (Marconi)") } do { increment(&t.patch) t.codename = "Unity" expectEqual(t.getVersion(), "7.5.3 (Unity)") } } // Subclass and superclass are both in our resilience domain class ChangeSizeOfMySuperclass : ChangeFieldOffsetsOfFixedLayout { init() { self.codename = "Big Bang" super.init(major: 7, minor: 0, patch: 0) } var codename: String override func getVersion() -> String { return "\(super.getVersion()) (\(codename))"; } } ClassChangeSizeTest.test("ChangeSizeOfMySuperclass") { let t = ChangeSizeOfMySuperclass() do { expectEqual(t.getVersion(), "7.0.0 (Big Bang)") } do { t.major.version = 6 t.minor.version = 0 t.patch.version = 5 t.codename = "Big Deal" expectEqual(t.getVersion(), "6.0.5 (Big Deal)") } do { increment(&t.patch) t.codename = "Six Pack" expectEqual(t.getVersion(), "6.0.6 (Six Pack)") } } runAllTests()
21.383784
73
0.668857
f8f0a1ffa285d7d6cd5d182175781e55758acd83
1,287
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "UserService", platforms: [ .macOS(.v10_15) ], dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"), .package(url: "https://github.com/vapor/fluent.git", from: "4.0.0"), .package(url: "https://github.com/vapor/fluent-mysql-driver.git", from: "4.0.0"), .package(url: "https://github.com/proggeramlug/SimpleJWTMiddleware.git", from: "1.1.0"), .package(url: "https://github.com/vapor-community/sendgrid.git", from: "4.0.0") ], targets: [ .target(name: "App", dependencies: [ .product(name: "Fluent", package: "fluent"), .product(name: "FluentMySQLDriver", package: "fluent-mysql-driver"), .product(name: "Vapor", package: "vapor"), .product(name: "SimpleJWTMiddleware", package: "SimpleJWTMiddleware"), .product(name: "SendGrid", package: "sendgrid") ]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: [ .target(name: "App"), .product(name: "XCTVapor", package: "vapor"), ]) ] )
39
96
0.574204
e587fb7d8c3633260612ad8d2e51d5538bde620d
437
// // ParserPrintStatement.swift // swiftparser // // Created by Nuno Silva on 22/06/2021. // import Foundation extension Parser { func printStatement() throws -> StatementProtocol { let value = try expression() let token = try self.consume(tokenType: .semicolon, message: "Expected `;' after expression.") return PrintStatement(token: token, expression: value) } }
19.863636
102
0.622426
26f1fe84e1662ec51e97e4a3687826e7b96f980e
523
// // ClearRefinementsButtonController.swift // InstantSearch // // Created by Vladislav Fitc on 24/05/2019. // import Foundation import InstantSearchCore import UIKit public class FilterClearButtonController: FilterClearController { public let button: UIButton public var onClick: (() -> Void)? public init(button: UIButton) { self.button = button button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside) } @objc private func didTapButton() { onClick?() } }
18.678571
80
0.705545
08e853ae009991aa19218f921e0feeab022753d7
611
// // PinAnnotation.swift // Virtual-Tourist // // Created by Matthias Wagner on 13.05.18. // Copyright © 2018 Matthias Wagner. All rights reserved. // import MapKit import ReactiveSwift class PinAnnotation: NSObject, MKAnnotation { // MARK: - MKAnnotation Properties let coordinate: CLLocationCoordinate2D let pin: Pin // MARK: Init init(pin: Pin) { let latitude = CLLocationDegrees(pin.latitude) let longitude = CLLocationDegrees(pin.longitude) coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) self.pin = pin } }
21.068966
85
0.687398
8f614b76f010a53b12f96c616aeee62d55b8c722
3,926
import UIKit class TriangleLayer: CAShapeLayer { let innerPadding: CGFloat = 30.0 override init() { super.init() fillColor = Colors.red.cgColor strokeColor = Colors.red.cgColor lineWidth = 7.0 lineCap = kCALineCapRound lineJoin = kCALineJoinRound path = trianglePathSmall.cgPath } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var trianglePathSmall: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0 + innerPadding, y: 95.0)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5 + innerPadding)) trianglePath.addLine(to: CGPoint(x: 95.0 - innerPadding, y: 95.0)) trianglePath.close() return trianglePath } var trianglePathLeftExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0, y: 95.0)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5 + innerPadding)) trianglePath.addLine(to: CGPoint(x: 95.0 - innerPadding, y: 95.0)) trianglePath.close() return trianglePath } var trianglePathRightExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0, y: 95.0)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5 + innerPadding)) trianglePath.addLine(to: CGPoint(x: 95.0, y: 95.0)) trianglePath.close() return trianglePath } var trianglePathTopExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0, y: 95.0)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5)) trianglePath.addLine(to: CGPoint(x: 95.0, y: 95.0)) trianglePath.close() return trianglePath } var trianglePathBottomExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0, y: 95.0)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5)) trianglePath.addLine(to: CGPoint(x: 95.0 - innerPadding, y: 95.0)) trianglePath.close() return trianglePath } func animate() { let triangleAnimationLeft: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationLeft.fromValue = trianglePathSmall.cgPath triangleAnimationLeft.toValue = trianglePathLeftExtension.cgPath triangleAnimationLeft.beginTime = 0.0 triangleAnimationLeft.duration = 0.3 let triangleAnimationRight: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationRight.fromValue = trianglePathLeftExtension.cgPath triangleAnimationRight.toValue = trianglePathRightExtension.cgPath triangleAnimationRight.beginTime = triangleAnimationLeft.beginTime + triangleAnimationLeft.duration triangleAnimationRight.duration = 0.25 let triangleAnimationTop: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationTop.fromValue = trianglePathRightExtension.cgPath triangleAnimationTop.toValue = trianglePathTopExtension.cgPath triangleAnimationTop.beginTime = triangleAnimationRight.beginTime + triangleAnimationRight.duration triangleAnimationTop.duration = 0.20 let triangleAnimationGroup: CAAnimationGroup = CAAnimationGroup() triangleAnimationGroup.animations = [triangleAnimationLeft, triangleAnimationRight, triangleAnimationTop] triangleAnimationGroup.duration = triangleAnimationTop.beginTime + triangleAnimationTop.duration triangleAnimationGroup.fillMode = kCAFillModeForwards triangleAnimationGroup.isRemovedOnCompletion = false add(triangleAnimationGroup, forKey: nil) } }
41.765957
107
0.673714
90787b616e4e2cac9b99bd8efa440d992098299e
2,779
import Eureka import PromiseKit import Shared import UIKit class ServerSelectViewController: HAFormViewController, ServerObserver, UIAdaptivePresentationControllerDelegate { let result: Promise<AccountRowValue> private let resultSeal: Resolver<AccountRowValue> enum ServerSelectError: Error, CancellableError { case cancelled var isCancelled: Bool { switch self { case .cancelled: return true } } } var prompt: String? { didSet { setupForm() } } var allowAll: Bool = false { didSet { setupForm() } } override init() { (self.result, self.resultSeal) = Promise<AccountRowValue>.pending() super.init() title = L10n.Settings.ServerSelect.pageTitle navigationItem.leftBarButtonItems = [ UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(_:))), ] } override func viewDidLoad() { super.viewDidLoad() setupForm() Current.servers.add(observer: self) } @objc private func cancel(_ sender: UIBarButtonItem) { resultSeal.reject(ServerSelectError.cancelled) } override func willMove(toParent parent: UIViewController?) { super.willMove(toParent: parent) if let parent = parent as? UINavigationController, parent.viewControllers == [self] { parent.presentationController?.delegate = self // sheet is a little annoying (even with large detent) with many servers if #available(iOS 15, *), Current.servers.all.count <= 4 { with(parent.sheetPresentationController) { $0?.detents = [.medium(), .large()] } } } } func serversDidChange(_ serverManager: ServerManager) { UIView.performWithoutAnimation { setupForm() } } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { resultSeal.reject(ServerSelectError.cancelled) } private func setupForm() { form.removeAll() if let prompt = prompt, !prompt.isEmpty { form +++ InfoLabelRow { $0.title = prompt } } var rows = [AccountRowValue]() if allowAll { rows.append(.all) } rows.append(contentsOf: Current.servers.all.map { .server($0) }) form +++ Section(rows.map { value in HomeAssistantAccountRow { $0.value = value $0.onCellSelection { [resultSeal] _, _ in resultSeal.fulfill(value) } } }) } }
26.721154
114
0.581504
50edf8481dae1b10262dd6f78f1a99e61066ac50
3,662
// // Zip.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // protocol ZipSinkProtocol : class { func next(_ index: Int) func fail(_ error: Swift.Error) func done(_ index: Int) } class ZipSink<O: ObserverType> : Sink<O>, ZipSinkProtocol { typealias Element = O.E let _arity: Int let _lock = RecursiveLock() // state private var _isDone: [Bool] init(arity: Int, observer: O, cancel: Cancelable) { self._isDone = [Bool](repeating: false, count: arity) self._arity = arity super.init(observer: observer, cancel: cancel) } func getResult() throws -> Element { rxAbstractMethod() } func hasElements(_ index: Int) -> Bool { rxAbstractMethod() } func next(_ index: Int) { var hasValueAll = true for i in 0 ..< self._arity { if !self.hasElements(i) { hasValueAll = false break } } if hasValueAll { do { let result = try self.getResult() self.forwardOn(.next(result)) } catch let e { self.forwardOn(.error(e)) self.dispose() } } else { var allOthersDone = true let arity = self._isDone.count for i in 0 ..< arity { if i != index && !self._isDone[i] { allOthersDone = false break } } if allOthersDone { self.forwardOn(.completed) self.dispose() } } } func fail(_ error: Swift.Error) { self.forwardOn(.error(error)) self.dispose() } func done(_ index: Int) { self._isDone[index] = true var allDone = true for done in self._isDone where !done { allDone = false break } if allDone { self.forwardOn(.completed) self.dispose() } } } final class ZipObserver<ElementType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias E = ElementType typealias ValueSetter = (ElementType) -> Void private var _parent: ZipSinkProtocol? let _lock: RecursiveLock // state private let _index: Int private let _this: Disposable private let _setNextValue: ValueSetter init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { self._lock = lock self._parent = parent self._index = index self._this = this self._setNextValue = setNextValue } func on(_ event: Event<E>) { self.synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { if self._parent != nil { switch event { case .next: break case .error: self._this.dispose() case .completed: self._this.dispose() } } if let parent = self._parent { switch event { case .next(let value): self._setNextValue(value) parent.next(self._index) case .error(let error): parent.fail(error) case .completed: parent.done(self._index) } } } }
23.779221
123
0.498088
21724e4f566479df262d91174f9ba50883e712eb
4,645
// // Copyright (c) 2018 KxCoding <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class AlignCenterViewController: UIViewController { @IBOutlet weak var bottomContainer: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bottomLineView: UIView! override func viewDidLoad() { super.viewDidLoad() // layoutWithInitializer() // layoutWithVisualFormatLanguage() layoutWithAnchor() } } extension AlignCenterViewController { func layoutWithInitializer() { titleLabel.translatesAutoresizingMaskIntoConstraints = false bottomLineView.translatesAutoresizingMaskIntoConstraints = false var centerX = NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: bottomContainer, attribute: .centerX, multiplier: 1.0, constant: 0.0) let centerY = NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: bottomContainer, attribute: .centerY, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate([centerX, centerY]) centerX = NSLayoutConstraint(item: bottomLineView, attribute: .centerX, relatedBy: .equal, toItem: titleLabel, attribute: .centerX, multiplier: 1.0, constant: 0.0) let top = NSLayoutConstraint(item: bottomLineView, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: 10.0) let width = NSLayoutConstraint(item: bottomLineView, attribute: .width, relatedBy: .equal, toItem: titleLabel, attribute: .width, multiplier: 1.0, constant: 0.0) let height = NSLayoutConstraint(item: bottomLineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 5.0) NSLayoutConstraint.activate([centerX, top, width, height]) } } extension AlignCenterViewController { func layoutWithVisualFormatLanguage() { titleLabel.translatesAutoresizingMaskIntoConstraints = false bottomLineView.translatesAutoresizingMaskIntoConstraints = false titleLabel.centerXAnchor.constraint(equalTo: bottomContainer.centerXAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: bottomContainer.centerYAnchor).isActive = true bottomLineView.widthAnchor.constraint(equalTo: titleLabel.widthAnchor).isActive = true let vertFmt = "V:[lbl]-10-[line(==5)]" let views: [String: Any] = ["lbl": titleLabel, "line": bottomLineView] let vertConstraints = NSLayoutConstraint.constraints(withVisualFormat: vertFmt, options: .alignAllCenterX, metrics: nil, views: views) NSLayoutConstraint.activate(vertConstraints) } } extension AlignCenterViewController { func layoutWithAnchor() { titleLabel.translatesAutoresizingMaskIntoConstraints = false bottomLineView.translatesAutoresizingMaskIntoConstraints = false titleLabel.centerXAnchor.constraint(equalTo: bottomContainer.centerXAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: bottomContainer.centerYAnchor).isActive = true bottomLineView.widthAnchor.constraint(equalTo: titleLabel.widthAnchor).isActive = true bottomLineView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10.0).isActive = true bottomLineView.centerXAnchor.constraint(equalTo: titleLabel.centerXAnchor).isActive = true bottomLineView.heightAnchor.constraint(equalToConstant: 5.0).isActive = true } }
24.067358
172
0.738213
14e92e017dd4b7e66051319b12a91a447811dc5b
869
// // PhotoBrowser+Indicator.swift // PhotoBrowser // // Created by 冯成林 on 15/8/13. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit extension PhotoBrowser{ /** pagecontrol准备 */ func pagecontrolPrepare(){ if !hideMsgForZoomAndDismissWithSingleTap {return} view.addSubview(pagecontrol) pagecontrol.make_bottomInsets_bottomHeight(left: 0, bottom: 0, right: 0, bottomHeight: 37) pagecontrol.numberOfPages = photoModels.count pagecontrol.enabled = false } /** pageControl页面变动 */ func pageControlPageChanged(page: Int){ if page<0 || page>=photoModels.count {return} if showType == ShowType.ZoomAndDismissWithSingleTap && hideMsgForZoomAndDismissWithSingleTap{ pagecontrol.currentPage = page } } }
24.828571
101
0.637514
ac95a2edc014a42723477dd46b071131388efe23
8,232
@objc(WMFHintPresenting) protocol HintPresenting: AnyObject { var hintController: HintController? { get set } } class HintController: NSObject { typealias Context = [String: Any] typealias HintPresentingViewController = UIViewController & HintPresenting private weak var presenter: HintPresentingViewController? private let hintViewController: HintViewController private var containerView = UIView() private var containerViewConstraint: (top: NSLayoutConstraint?, bottom: NSLayoutConstraint?) private var task: DispatchWorkItem? var theme = Theme.standard //if true, hint will extend below safe area to the bottom of the view, and hint content within will align to safe area //must also override extendsUnderSafeArea to true in HintViewController var extendsUnderSafeArea: Bool { return false } init(hintViewController: HintViewController) { self.hintViewController = hintViewController super.init() hintViewController.delegate = self } var isHintHidden: Bool { return containerView.superview == nil } private var hintVisibilityTime: TimeInterval = 13 { didSet { guard hintVisibilityTime != oldValue else { return } dismissHint() } } func dismissHint(completion: (() -> Void)? = nil) { self.task?.cancel() let task = DispatchWorkItem { [weak self] in self?.setHintHidden(true) if let completion = completion { completion() } } DispatchQueue.main.asyncAfter(deadline: .now() + hintVisibilityTime , execute: task) self.task = task } @objc func toggle(presenter: HintPresentingViewController, context: Context?, theme: Theme) { self.presenter = presenter apply(theme: theme) } func toggle(presenter: HintPresentingViewController, context: Context?, theme: Theme, subview: UIView? = nil, additionalBottomSpacing: CGFloat = 0, setPrimaryColor: ((inout UIColor?) -> Void)? = nil, setBackgroundColor: ((inout UIColor?) -> Void)? = nil) { self.subview = subview self.additionalBottomSpacing = additionalBottomSpacing setPrimaryColor?(&hintViewController.primaryColor) setBackgroundColor?(&hintViewController.backgroundColor) self.presenter = presenter apply(theme: theme) } private var subview: UIView? private var additionalBottomSpacing: CGFloat = 0 private func addHint(to presenter: HintPresentingViewController) { guard isHintHidden else { return } containerView.translatesAutoresizingMaskIntoConstraints = false var bottomAnchor: NSLayoutYAxisAnchor = extendsUnderSafeArea ? presenter.view.bottomAnchor : presenter.view.safeAreaLayoutGuide.bottomAnchor if let wmfVCPresenter = presenter as? ViewController { // not ideal, violates encapsulation wmfVCPresenter.view.insertSubview(containerView, belowSubview: wmfVCPresenter.toolbar) if !wmfVCPresenter.isToolbarHidden && wmfVCPresenter.toolbar.superview != nil { bottomAnchor = wmfVCPresenter.toolbar.topAnchor } } else if let subview = subview { presenter.view.insertSubview(containerView, belowSubview: subview) } else { presenter.view.addSubview(containerView) } // `containerBottomConstraint` is activated when the hint is visible containerViewConstraint.bottom = containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0 - additionalBottomSpacing) // `containerTopConstraint` is activated when the hint is hidden containerViewConstraint.top = containerView.topAnchor.constraint(equalTo: bottomAnchor) let leadingConstraint = containerView.leadingAnchor.constraint(equalTo: presenter.view.leadingAnchor) let trailingConstraint = containerView.trailingAnchor.constraint(equalTo: presenter.view.trailingAnchor) NSLayoutConstraint.activate([containerViewConstraint.top!, leadingConstraint, trailingConstraint]) if presenter.isKind(of: SearchResultsViewController.self){ presenter.wmf_hideKeyboard() } hintViewController.view.setContentHuggingPriority(.required, for: .vertical) hintViewController.view.setContentCompressionResistancePriority(.required, for: .vertical) containerView.setContentHuggingPriority(.required, for: .vertical) containerView.setContentCompressionResistancePriority(.required, for: .vertical) presenter.wmf_add(childController: hintViewController, andConstrainToEdgesOfContainerView: containerView) containerView.superview?.layoutIfNeeded() } private func removeHint() { task?.cancel() hintViewController.willMove(toParent: nil) hintViewController.view.removeFromSuperview() hintViewController.removeFromParent() containerView.removeFromSuperview() resetHint() } func resetHint() { hintVisibilityTime = 13 hintViewController.viewType = .default } func setHintHidden(_ hidden: Bool, completion: (() -> Void)? = nil) { guard isHintHidden != hidden, let presenter = presenter, presenter.presentedViewController == nil else { if let completion = completion { completion() } return } presenter.hintController = self if !hidden { // add hint before animation starts addHint(to: presenter) } self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden) UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: { if hidden { self.containerViewConstraint.bottom?.isActive = false self.containerViewConstraint.top?.isActive = true } else { self.containerViewConstraint.top?.isActive = false self.containerViewConstraint.bottom?.isActive = true } self.containerView.superview?.layoutIfNeeded() }, completion: { (_) in // remove hint after animation is completed if hidden { self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden) self.removeHint() if let completion = completion { completion() } } else { self.dismissHint(completion: completion) } }) } @objc func dismissHintDueToUserInteraction() { guard !self.isHintHidden else { return } self.hintVisibilityTime = 0 } private func adjustSpacingIfPresenterHasSecondToolbar(hintHidden: Bool) { guard let viewController = presenter as? ViewController, !viewController.isSecondToolbarHidden && !hintHidden else { return } viewController.setSecondToolbarHidden(true, animated: true) } } extension HintController: HintViewControllerDelegate { func hintViewControllerWillDisappear(_ hintViewController: HintViewController) { setHintHidden(true) } func hintViewControllerHeightDidChange(_ hintViewController: HintViewController) { adjustSpacingIfPresenterHasSecondToolbar(hintHidden: isHintHidden) } func hintViewControllerViewTypeDidChange(_ hintViewController: HintViewController, newViewType: HintViewController.ViewType) { guard newViewType == .confirmation else { return } setHintHidden(false) } func hintViewControllerDidPeformConfirmationAction(_ hintViewController: HintViewController) { setHintHidden(true) } func hintViewControllerDidFailToCompleteDefaultAction(_ hintViewController: HintViewController) { setHintHidden(true) } } extension HintController: Themeable { func apply(theme: Theme) { hintViewController.apply(theme: theme) } }
36.424779
260
0.668124
9187c5b40082e6aac331aa5525468ed58a69f49e
514
// // MessageTableViewController.swift // XLWB // // Created by CoderZQ on 2019/8/28. // Copyright © 2019 CoderZQ. All rights reserved. // import UIKit class MessageTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() // 1.如果没有登录,就设置未登录界面的信息 if !userLogin { visitorView?.setupVisitorInfo(isHome: false, imageName: "visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") } } }
19.769231
142
0.659533
0e0a2e7677e6dc94005c29df470cfee26bb15cfa
937
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "graphzahl-fluent-support", platforms: [ .macOS(.v10_15) ], products: [ .library(name: "GraphZahlFluentSupport", targets: ["GraphZahlFluentSupport"]), ], dependencies: [ .package(url: "https://github.com/nerdsupremacist/GraphZahl.git", from: "0.1.0-alpha.28"), .package(url: "https://github.com/nerdsupremacist/ContextKit.git", from: "0.2.1"), .package(url: "https://github.com/vapor/fluent.git", from: "4.0.0-rc.2.2"), .package(url: "https://github.com/vapor/fluent-kit.git", from: "1.0.0-rc.1.27"), ], targets: [ .target( name: "GraphZahlFluentSupport", dependencies: ["GraphZahl", "Fluent", "ContextKit"] ), ] )
33.464286
98
0.60619
1d183289a60ec622c4a8618f277f66ad7e90bd37
205
// // Lesson.swift // TypeTrainer // // Created by Azat Kaiumov on 04.05.2020. // Copyright © 2020 Azat Kaiumov. All rights reserved. // struct Lesson { var name: String var data: [[Token]] }
15.769231
55
0.634146
dd4e35ba84738b57da3383d800955ece0fa438dd
3,156
// // PPView+PPContentWrap.swift // PapaLayout // // Created by Daniel Huri on 11/21/17. // import Foundation #if os(OSX) import AppKit #else import UIKit #endif // MARK: Content Compression Resistance & Content Hugging Priority public extension PPView { /** Force hugging and compression resistance for the given axes, using variadic parameter. - parameter axes: The axes */ public func forceContentWrap(_ axes: PPAxis...) { if axes.contains(.vertically) { verticalHuggingPriority = .required verticalCompressionResistancePriority = .required } if axes.contains(.horizontally) { horizontalHuggingPriority = .required horizontalCompressionResistancePriority = .required } } /** Force hugging and compression resistance vertically and horizontally. */ public func forceContentWrap() { contentHuggingPriority = .required contentCompressionResistancePriority = .required } /** Vertical hugging priority */ public var verticalHuggingPriority: PPPriority { set { setContentHuggingPriority(newValue, for: .vertical) } get { return contentHuggingPriority(for: .vertical) } } /** Horizontal hugging priority */ public var horizontalHuggingPriority: PPPriority { set { setContentHuggingPriority(newValue, for: .horizontal) } get { return contentHuggingPriority(for: .horizontal) } } /** Content hugging priority (Vertical & Horizontal) */ public var contentHuggingPriority: PPPriorityPair { set { horizontalHuggingPriority = newValue.horizontal verticalHuggingPriority = newValue.vertical } get { return PPPriorityPair(horizontalHuggingPriority, verticalHuggingPriority) } } /** Vertical content compression resistance priority */ public var verticalCompressionResistancePriority: PPPriority { set { setContentCompressionResistancePriority(newValue, for: .vertical) } get { return contentCompressionResistancePriority(for: .vertical) } } /** Horizontal content compression resistance priority */ public var horizontalCompressionResistancePriority: PPPriority { set { setContentCompressionResistancePriority(newValue, for: .horizontal) } get { return contentCompressionResistancePriority(for: .horizontal) } } /** Content compression resistance priority (Vertical & Horizontal) */ public var contentCompressionResistancePriority: PPPriorityPair { set { horizontalCompressionResistancePriority = newValue.horizontal verticalCompressionResistancePriority = newValue.vertical } get { return PPPriorityPair(horizontalCompressionResistancePriority, verticalCompressionResistancePriority) } } }
27.443478
113
0.637516
39eedeee5dceb50740b305fa9369ebf30bf7333a
1,301
// // TestAnalyticsViewController.swift // MozQuito // // Created by Josh Campion on 22/01/2016. // Copyright © 2016 The Distance. All rights reserved. // import UIKit import Components class TestAnalyticsViewController: UIViewController, AnalyticScreenView { var screenName:AnalyticScreen = .Test override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) registerScreenView() } @IBAction func crashTapped() { AppDependencies.sharedDependencies().crashReporter?.simulateCrash() } @IBAction func eventTapped() { let testEvent = AnalyticEvent(category: .Test, action: .Test, label: nil) AppDependencies.sharedDependencies().analyticsReporter?.sendAnalytic(testEvent) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
26.55102
106
0.681783
6a49a15e6ead3c64a22b2d87fd865a6275254ff0
4,533
// // TLCubeAnimator.swift // Pods // 3D翻转 // Created by Andrew on 16/5/31. // // import UIKit private let PERSPECTIVE = CGFloat(-1.0 / 200.0) private let ROTATION_ANGLE = CGFloat(M_PI_2) public class TLCubeAnimator: TLBaseAnimator { /** 翻转方向 - horizontal: 水平方向 - vertical: 垂直方向 */ public enum TLCubeDirecation { case horizontal case vertical } /** 翻转类型 - normal: 普通 - inverse: 上下翻转 */ public enum TLCubeType { case normal case inverse } public var cubetype = TLCubeType.normal public var cubeDirecation = TLCubeDirecation.horizontal public override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let model = TransitionModel(context: transitionContext) //创建不同的3D效果 var viewFromTransform:CATransform3D? var viewToTransform:CATransform3D? var dir:CGFloat = 1 // if self.operaiton == .Pop{ // dir = -dir // } if self.isPositiveAnimation == false{ dir = -dir } switch cubeDirecation { case .horizontal: //旋转90度 viewFromTransform = CATransform3DMakeRotation(dir*ROTATION_ANGLE, 0, 1, 0) viewToTransform = CATransform3DMakeRotation(-dir*ROTATION_ANGLE, 0, 1, 0) model.toView.layer.anchorPoint = CGPointMake(dir == 1 ? 0 : 1, 0.5) model.fromView.layer.anchorPoint = CGPointMake(dir == 1 ? 1 : 0, 0.5) model.containerView.transform = CGAffineTransformMakeTranslation(dir*(model.containerView.frame.size.width/2), 0) case .vertical: viewFromTransform = CATransform3DMakeRotation(-dir*ROTATION_ANGLE, 1, 0, 0) viewToTransform = CATransform3DMakeRotation(dir*ROTATION_ANGLE, 1, 0, 0) model.toView.layer.anchorPoint = CGPointMake(0.5, dir == 1 ? 0 : 1) model.fromView.layer.anchorPoint = CGPointMake(0.5, dir == 1 ? 1 : 0) model.containerView.transform = CGAffineTransformMakeTranslation(0, dir*(model.containerView.frame.size.height)/2.0) break } //设置透明度,只有在旋转的时候这个属性才有效 viewFromTransform?.m34 = PERSPECTIVE viewToTransform?.m34 = PERSPECTIVE model.toView.layer.transform = viewToTransform! //创建阴影 let fromShadow = self.addOpacityToView(model.fromView, color: UIColor.blackColor()) let toShadow = self.addOpacityToView(model.toView, color: UIColor.blackColor()) fromShadow.alpha = 0 toShadow.alpha = 1 model.containerView.addSubview(model.toView) UIView.animateWithDuration(self.animatorDuration, animations: { switch self.cubeDirecation{ case .horizontal: model.containerView.transform = CGAffineTransformMakeTranslation(-dir*model.containerView.frame.size.width/2, 0) break case .vertical: model.containerView.transform = CGAffineTransformMakeTranslation(0,-dir*model.containerView.frame.size.height/2) break } model.fromView.layer.transform = viewFromTransform! model.toView.layer.transform = CATransform3DIdentity fromShadow.alpha = 1 toShadow.alpha = 0 }) { (finished) in //恢复最初的位置 model.containerView.transform = CGAffineTransformIdentity model.toView.layer.transform = CATransform3DIdentity model.fromView.layer.transform = CATransform3DIdentity //设置锚点为中心 model.fromView.layer.anchorPoint = CGPointMake(0.5, 0.5) model.toView.layer.anchorPoint = CGPointMake(0.5, 0.5) //移除阴影 fromShadow.removeFromSuperview() toShadow.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } func addOpacityToView(view:UIView,color:UIColor) -> UIView { let shadowView = UIView(frame: view.bounds) shadowView.backgroundColor = color.colorWithAlphaComponent(0.8) view.addSubview(shadowView) return shadowView } }
31.262069
133
0.591661
eb962af06b96d5a2a4f18f5ade167d978d9062c5
94
class ToDo { var id = 0 var userId = 0 var title = "" var completed = false }
13.428571
25
0.531915
290bdbd79c4d9282e96f656b29de5c7fe8b67866
241
// // Quickly // #if os(iOS) open class QSpaceTableRow: QBackgroundColorTableRow { public var size: CGFloat public init(size: CGFloat) { self.size = size super.init() } } #endif
12.684211
57
0.53112
33853ae2612d492d4d9050e048232c03adfecfcd
8,113
// Copyright 2022 Pera Wallet, LDA // 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. // // AddContactViewController.swift import UIKit final class AddContactViewController: BaseScrollViewController { weak var delegate: AddContactViewControllerDelegate? private lazy var theme = Theme() private lazy var addContactView = AddContactView() private lazy var imagePicker = ImagePicker() private lazy var keyboardController = KeyboardController() private var address: String? private var contactName: String? init(address: String?, name: String?, configuration: ViewControllerConfiguration) { super.init(configuration: configuration) self.address = address self.contactName = name } override func setListeners() { super.setListeners() keyboardController.beginTracking() } override func linkInteractors() { keyboardController.dataSource = self addContactView.delegate = self scrollView.touchDetectingDelegate = self } override func prepareLayout() { super.prepareLayout() addContactView.customize(theme.addContactViewTheme) contentView.addSubview(addContactView) addContactView.snp.makeConstraints { $0.edges.equalToSuperview() } } override func configureAppearance() { super.configureAppearance() view.customizeBaseAppearance(backgroundColor: theme.backgroundColor) } override func bindData() { super.bindData() addContactView.badgedImageView.bindData(image: nil, badgeImage: "icon-circle-add".uiImage) addContactView.nameInputView.text = contactName addContactView.addressInputView.text = address } } extension AddContactViewController: AddContactViewDelegate { func addContactViewInputFieldViewShouldReturn( _ addContactView: AddContactView, inputFieldView: FloatingTextInputFieldView ) -> Bool { if inputFieldView == addContactView.nameInputView { addContactView.addressInputView.beginEditing() } else { inputFieldView.endEditing() } return true } func addContactViewDidTapAddContactButton(_ addContactView: AddContactView) { guard let keyedValues = parseFieldsForContact() else { return } addContact(with: keyedValues) } func addContactViewDidTapAddImageButton(_ addContactView: AddContactView) { imagePicker.delegate = self imagePicker.present(from: self) } private func parseFieldsForContact() -> [String: Any]? { guard let name = addContactView.nameInputView.text, !name.isEmptyOrBlank else { displaySimpleAlertWith(title: "title-error".localized, message: "contacts-name-validation-error".localized) return nil } guard let address = addContactView.addressInputView.text, !address.isEmpty, address.isValidatedAddress else { displaySimpleAlertWith(title: "title-error".localized, message: "contacts-address-validation-error".localized) return nil } let trimmedAddress = address.trimmingCharacters(in: .whitespacesAndNewlines) var keyedValues: [String: Any] = [ Contact.CodingKeys.name.rawValue: name, Contact.CodingKeys.address.rawValue: trimmedAddress ] if let placeholderImage = img("icon-user-placeholder"), let image = addContactView.badgedImageView.imageView.image, let imageData = image.jpegData(compressionQuality: 1.0) ?? image.pngData(), image != placeholderImage { keyedValues[Contact.CodingKeys.image.rawValue] = imageData } return keyedValues } private func addContact(with values: [String: Any]) { Contact.create(entity: Contact.entityName, with: values) { result in switch result { case let .result(object: object): guard let contact = object as? Contact else { return } NotificationCenter.default.post(name: .ContactAddition, object: self, userInfo: ["contact": contact]) self.closeScreen(by: .pop) default: break } } } func addContactViewDidTapQRCodeButton(_ addContactView: AddContactView) { if !UIImagePickerController.isSourceTypeAvailable(.camera) { displaySimpleAlertWith(title: "qr-scan-error-title".localized, message: "qr-scan-error-message".localized) return } guard let qrScannerViewController = open(.qrScanner(canReadWCSession: false), by: .push) as? QRScannerViewController else { return } qrScannerViewController.delegate = self } } extension AddContactViewController: ImagePickerDelegate { func imagePicker(didPick image: UIImage, withInfo info: [String: Any]) { let resizedImage = image.convert(to: CGSize(width: 80, height: 80)) addContactView.badgedImageView.bindData(image: resizedImage, badgeImage: "icon-circle-edit".uiImage) } } extension AddContactViewController: KeyboardControllerDataSource { func bottomInsetWhenKeyboardPresented(for keyboardController: KeyboardController) -> CGFloat { return 15 } func firstResponder(for keyboardController: KeyboardController) -> UIView? { return addContactView.addressInputView } func containerView(for keyboardController: KeyboardController) -> UIView { return contentView } func bottomInsetWhenKeyboardDismissed(for keyboardController: KeyboardController) -> CGFloat { return 0 } } extension AddContactViewController: QRScannerViewControllerDelegate { func qrScannerViewController(_ controller: QRScannerViewController, didRead qrText: QRText, completionHandler: EmptyHandler?) { guard qrText.mode == .address, let qrAddress = qrText.address else { displaySimpleAlertWith(title: "title-error".localized, message: "qr-scan-should-scan-address-message".localized) { _ in if let handler = completionHandler { handler() } } return } addContactView.addressInputView.text = qrAddress } func qrScannerViewController(_ controller: QRScannerViewController, didFail error: QRScannerError, completionHandler: EmptyHandler?) { displaySimpleAlertWith(title: "title-error".localized, message: "qr-scan-should-scan-valid-qr".localized) { _ in if let handler = completionHandler { handler() } } } } extension AddContactViewController: TouchDetectingScrollViewDelegate { func scrollViewDidDetectTouchEvent(scrollView: TouchDetectingScrollView, in point: CGPoint) { if addContactView.addContactButton.frame.contains(point) || addContactView.addressInputView.frame.contains(point) || addContactView.nameInputView.frame.contains(point) { return } contentView.endEditing(true) } } protocol AddContactViewControllerDelegate: AnyObject { func addContactViewController(_ addContactViewController: AddContactViewController, didSave contact: Contact) }
36.877273
138
0.662024
46b440320a7e20305affebf76163835b9975e811
2,820
// @generated // This file was automatically generated and should not be edited. import Apollo import Foundation public final class GetItemsQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetItems { items { __typename name members } } """ public let operationName: String = "GetItems" public let operationIdentifier: String? = "1b873bb10dcac02164a7895d3887e21d5abf9da56c1f5d94624711d1d81a4caf" public init() { } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("items", type: .nonNull(.list(.nonNull(.object(Item.selections))))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(items: [Item]) { self.init(unsafeResultMap: ["__typename": "Query", "items": items.map { (value: Item) -> ResultMap in value.resultMap }]) } public var items: [Item] { get { return (resultMap["items"] as! [ResultMap]).map { (value: ResultMap) -> Item in Item(unsafeResultMap: value) } } set { resultMap.updateValue(newValue.map { (value: Item) -> ResultMap in value.resultMap }, forKey: "items") } } public struct Item: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("name", type: .nonNull(.scalar(String.self))), GraphQLField("members", type: .nonNull(.scalar(Bool.self))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String, members: Bool) { self.init(unsafeResultMap: ["__typename": "Item", "name": name, "members": members]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } /// Name displayed in game public var name: String { get { return resultMap["name"]! as! String } set { resultMap.updateValue(newValue, forKey: "name") } } public var members: Bool { get { return resultMap["members"]! as! Bool } set { resultMap.updateValue(newValue, forKey: "members") } } } } }
26.603774
127
0.604255
6a5c964a1605ac3c8667b42f6714376412101238
3,308
// // PulseDAO.swift // ModulAid // // Created by Ammar on 4/18/16. // Copyright © 2016 ModulAid. All rights reserved. // import Foundation class PulseDAO : SensorDAO { static let sharedInstance = PulseDAO() //pulse history objects let pulseFilePath: String = fileInDocumentsDirectory("PulseData.plist") //path to file to store temperature history var pulseHistory : NSMutableArray var pulseDict : NSMutableDictionary //last measurement override init() { //get stored data history if let history = NSMutableArray(contentsOfFile: pulseFilePath) { pulseHistory = history } else{ pulseHistory = NSMutableArray() } pulseDict = NSMutableDictionary() super.init(); } //MARK: Saving data //this method updates pulse data in pulse history array func updatePulseData(value : Double) { //update pulse history let location = ["latitude" : Double(locator.location!.coordinate.latitude), "longitude" : Double(locator.location!.coordinate.longitude), "city" : locator.city!, "state" : locator.state!, "country" : locator.country!] pulseDict = ["value (bpm)" : value, "date" : NSDate(), "location" : location] pulseHistory.addObject(pulseDict) if(pulseHistory.count > 10){ pulseHistory.removeObjectAtIndex(0) //remove oldest data point } //notify that last pulse measurement has been updated is_changed = true } //this method saves pulse data to plist, and firebase //should be called when closing a view controller func savePulseData() { //save data locally pulseHistory.writeToFile(pulseFilePath, atomically: false) //save data to database remotely if(is_changed){ if let value = pulseDict["value (bpm)"]{ let dict : NSMutableDictionary = ["value (bpm)" : value, "location" : pulseDict["location"]!] let date : NSDate = pulseDict["date"] as! NSDate dict.setObject(date.timeIntervalSince1970, forKey: "date") //convert date to number to efficiently store in database userFirebaseRef.updateChildValues(["pulse" : dict]) } } } //MARK: Sensor Communication Methods // initializeSensor // should be called to initialize the headphone jack so that to start taking data from quick jack specifically for pulse sensor func initializeSensor(){ communicator.sendData(0x31); //send a code through UART to let the microcontroller read temperature sensor communicator.resetJackBuffers(); } func startSending(){ communicator.sendData(0x47); } // measurePulse // used to get pulse reading func measurePulse() -> Double { var data : Double = Double(communicator.receiveData()); //get data from communicator (casted from float to double) // while(data == 0){ // initializeSensor(); // NSTimer(timeInterval: 2, target: self, selector: nil, userInfo: nil, repeats: false); // data = Double(communicator.receiveData()); // } return data; } }
35.191489
225
0.620314
9bfbd622d49c9d3f060bc6ef4c6e08e448ff536e
1,969
import Foundation public enum Error: Swift.Error, LocalizedError, Equatable { case script(ScriptError) case underlying(Swift.Error) case string(String) static let unknown = Error.string("An unknown error occured.") public var errorDescription: String? { switch self { case let .script(error): return error.localizedDescription case let .underlying(error): return error.localizedDescription case let .string(value): return value } } public static func == (lhs: Error, rhs: Error) -> Bool { switch (lhs, rhs) { case let (.script(lhs), .script(rhs)): return lhs == rhs case let (.underlying(lhs), .underlying(rhs)): return lhs as NSError == rhs as NSError case let (.string(lhs), .string(rhs)): return lhs == rhs case (.script, _), (.underlying, _), (.string, _): return false } } } public struct ScriptError: LocalizedError, Equatable { public var briefMessage: String public var message: String public var errorNumber: Int public var range: NSRange public init(briefMessage: String, message: String, errorNumber: Int, range: NSRange) { self.briefMessage = briefMessage self.message = message self.errorNumber = errorNumber self.range = range } public var errorDescription: String? { briefMessage } } extension Error { public init(dictionary: NSDictionary) { guard let briefMessage = dictionary["NSAppleScriptErrorBriefMessage"] as? String, let message = dictionary["NSAppleScriptErrorMessage"] as? String, let errorNumber = dictionary["NSAppleScriptErrorNumber"] as? NSNumber, let range = dictionary["NSAppleScriptErrorRange"] as? NSValue else { self = .unknown return } self = .script( ScriptError( briefMessage: briefMessage, message: message, errorNumber: errorNumber.intValue, range: range.rangeValue ) ) } }
26.608108
88
0.665312
d53d6b4635efa36c37df0f8f87e090339cfeddb5
4,113
// // Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class GraphicDrawOrderViewController: UIViewController { @IBOutlet var mapView: AGSMapView! @IBOutlet var buttons: [UIButton]! var map: AGSMap! private var graphicsOverlay = AGSGraphicsOverlay() private var graphics: [AGSGraphic]! private var drawIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GraphicDrawOrderViewController"] //create an instance of a map with ESRI topographic basemap self.map = AGSMap(basemap: .streets()) //assign map to the map view self.mapView.map = self.map //add the graphics overlay to the map view self.mapView.graphicsOverlays.add(self.graphicsOverlay) //add the graphics to the overlay self.addGraphics() //set map scale let mapScale: Double = 53500 //initial viewpoint self.mapView.setViewpointCenter(AGSPoint(x: -13148960, y: 4000040, spatialReference: .webMercator()), scale: mapScale) //restricting map scale to preserve the graphics overlapping self.map.minScale = mapScale self.map.maxScale = mapScale } private func addGraphics() { //starting x and y let x: Double = -13149000 let y: Double = 4e6 //distance between the graphics let delta: Double = 100 //graphics array for reference when a button is tapped self.graphics = [AGSGraphic]() //blue marker var geometry = AGSPoint(x: x, y: y, spatialReference: .webMercator()) var symbol = AGSPictureMarkerSymbol(image: UIImage(named: "BlueMarker")!) var graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil) self.graphics.append(graphic) //red marker geometry = AGSPoint(x: x + delta, y: y, spatialReference: .webMercator()) symbol = AGSPictureMarkerSymbol(image: UIImage(named: "RedMarker2")!) graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil) self.graphics.append(graphic) //green marker geometry = AGSPoint(x: x, y: y + delta, spatialReference: .webMercator()) symbol = AGSPictureMarkerSymbol(image: UIImage(named: "GreenMarker")!) graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil) self.graphics.append(graphic) //Violet marker geometry = AGSPoint(x: x + delta, y: y + delta, spatialReference: .webMercator()) symbol = AGSPictureMarkerSymbol(image: UIImage(named: "VioletMarker")!) graphic = AGSGraphic(geometry: geometry, symbol: symbol, attributes: nil) self.graphics.append(graphic) //add the graphics to the overlay self.graphicsOverlay.graphics.addObjects(from: self.graphics) } // MARK: - Actions @IBAction func buttonAction(_ sender: UIButton) { //increment draw index by 1 and assign as the zIndex for the respective graphic self.drawIndex += 1 //the button's tag value specifies which graphic to re-index //for example, a button tag value of 1 will move self.graphics[1] - the red marker self.graphics[sender.tag].zIndex = self.drawIndex } }
38.439252
126
0.652079
ed50a990c2b2a4235662cf5c6123a8829e6f105e
363
public protocol ConventionCountdownService { func add(_ observer: ConventionCountdownServiceObserver) } public enum ConventionCountdownState { case countingDown(daysUntilConvention: Int) case countdownElapsed } public protocol ConventionCountdownServiceObserver { func conventionCountdownStateDidChange(to state: ConventionCountdownState) }
21.352941
78
0.820937
fe300cdd54df93b9e0d6f4b3969bc5c59a139df2
1,369
// // ProgressUtils.swift // ProgressKit // // Created by Kauntey Suryawanshi on 09/07/15. // Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved. // import AppKit extension NSRect { var mid: CGPoint { return CGPoint(x: self.midX, y: self.midY) } } extension NSBezierPath { /// Converts NSBezierPath to CGPath var CGPath: CGPath { let path = CGMutablePath() let points = UnsafeMutablePointer<NSPoint>.allocate(capacity: 3) let numElements = self.elementCount for index in 0..<numElements { let pathType = self.element(at: index, associatedPoints: points) switch pathType { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() } } points.deallocate(capacity: 3) return path } } func degreeToRadian(_ degree: Int) -> Double { return Double(degree) * (Double.pi / 180) } func radianToDegree(_ radian: Double) -> Int { return Int(radian * (180 / Double.pi)) } func + (p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y) }
24.446429
86
0.584368
032caa55f816cd6748716f6376212c75df4c8b70
6,965
// // Entwine // https://github.com/tcldr/Entwine // // Copyright © 2019 Tristan Celder. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import OpenCombine import Entwine // MARK: - TestableSubscriberOptions value definition /// Options for the defining the behavior of a `TestableSubscriber` throughout its lifetime public struct TestableSubscriberOptions { /// The demand that will be signalled to the upstream `Publisher` upon subscription public var initialDemand = Subscribers.Demand.unlimited /// The demand that will be signalled to the upstream `Publisher` when the initial /// demand is depleted public var subsequentDemand = Subscribers.Demand.none /// When demand has been depleted, the delay in virtual time before additional demand /// (amount determined by `.subsequentDemand) is signalled to the upstream publisher. public var demandReplenishmentDelay: VirtualTimeInterval = 100 /// An action to perform when a publisher produces a greater number of elements than /// the subscriber has signalled demand for. The default is an assertion failure. public var negativeBalanceHandler: (() -> Void)? = nil /// Pre-populated `TestableSubscriber` options: /// /// The defaults are: /// - `initialDemand`: `.unlimited` /// - `subsequentDemand`: `.none` /// - `demandReplenishmentDelay`: `100` /// - `negativeBalanceHandler`: `nil` public static let `default` = TestableSubscriberOptions() } // MARK: - TestableSubscriber definition /// A subscriber that keeps a time-stamped log of the events that occur during the lifetime of a subscription to an arbitrary publisher. /// /// Initializable using the factory methods on `TestScheduler` public final class TestableSubscriber<Input, Failure: Error> { public typealias Sequence = TestSequence<Input, Failure> /// A time-stamped log of `Signal`s produced during the lifetime of a subscription to a publisher. public internal(set) var recordedOutput = TestSequence<Input, Failure>() /// A time-stamped account of `Subscribers.Demand`s issued upstream, and incoming elements /// downstream, during the lifetime of a subscription to a publisher. public internal(set) var recordedDemandLog = DemandLedger<VirtualTime>() private let scheduler: TestScheduler private let options: TestableSubscriberOptions private var subscription: Subscription? private var demandBalance = Subscribers.Demand.none private var replenishmentToken: Cancellable? init(scheduler: TestScheduler, options: TestableSubscriberOptions = .default) { self.scheduler = scheduler self.options = options } deinit { cancel() } func issueDemandCredit(_ demand: Subscribers.Demand) { demandBalance += demand recordedDemandLog.append((scheduler.now, demandBalance, .credit(amount: demand))) guard demand > .none else { return } subscription?.request(demand) } func debitDemand(_ demand: Subscribers.Demand) { let authorized = (demandBalance > .none) demandBalance -= authorized ? demand : .none recordedDemandLog.append((scheduler.now, demandBalance, .debit(authorized: authorized))) if !authorized { signalNegativeBalance() } } func signalNegativeBalance() { guard let negativeBalanceHandler = options.negativeBalanceHandler else { assertionFailure(""" ************************************************************************************** Bad Publisher The number of items received from the publisher exceeds the number of items requested. If you wish to test acquiring this state purposefully, add a `.negativeBalanceHandler` to the `TestableSubscriberOptions` configuration object to silence this assertion and handle the state. ************************************************************************************** """) return } negativeBalanceHandler() } func delayedReplenishDemandIfNeeded() { guard demandBalance == .none && options.subsequentDemand > .none else { return } guard replenishmentToken == nil else { return } replenishmentToken = scheduler.schedule(after: scheduler.now + options.demandReplenishmentDelay, interval: 0, tolerance: 1, options: nil) { self.issueDemandCredit(self.options.subsequentDemand) self.replenishmentToken = nil } } } // MARK: - Subscriber conformance extension TestableSubscriber: Subscriber { public func receive(subscription: Subscription) { guard self.subscription == nil else { subscription.cancel() return } self.demandBalance = .none self.subscription = subscription recordedOutput.append((scheduler.now, .subscription)) issueDemandCredit(options.initialDemand) delayedReplenishDemandIfNeeded() } public func receive(_ input: Input) -> Subscribers.Demand { recordedOutput.append((scheduler.now, .input(input))) debitDemand(.max(1)) delayedReplenishDemandIfNeeded() return .none } public func receive(completion: Subscribers.Completion<Failure>) { recordedOutput.append((scheduler.now, .completion(completion))) } } // MARK: - Cancellable conformance extension TestableSubscriber: Cancellable { public func cancel() { replenishmentToken?.cancel() subscription?.cancel() subscription = nil replenishmentToken = nil } }
38.910615
147
0.659584
4bfc63dd3834fcbe077126db608cd1f43e26624c
1,734
import SwiftUI struct UserTitleView: View { var user: Entities.User var body: some View { HStack{ VStack{ Image(systemName: "person") .resizable() .frame(width: 90, height: 90) .shadow(radius: 3) .lineLimit(1) }.padding() VStack{ Text("9999") .font(.title) .foregroundColor(.blue) .fontWeight(.bold) .lineLimit(1) Text("Publications") .font(.subheadline) .foregroundColor(.blue) .lineLimit(1) }.padding(.leading) VStack{ Text("9999") .font(.title) .foregroundColor(.blue) .fontWeight(.bold) .lineLimit(1) Text("Followers") .font(.subheadline) .foregroundColor(.blue) .lineLimit(1) } VStack{ Text("9999") .font(.title) .foregroundColor(.blue) .fontWeight(.bold) .lineLimit(1) Text("Following") .font(.subheadline) .foregroundColor(.blue) .lineLimit(1) } } .frame(height: 100) } } struct UserTitleView_Previews: PreviewProvider { static var previews: some View { UserTitleView(user: Entities.User(id: "1", name: "John")) } }
27.967742
65
0.38639
87a65e0a2b5778377d444c9a12ce7ba42169cc56
462
// // RepositoryDetailView.swift // SwiftUI-Flux // // Created by Yusuke Kita on 6/5/19. // Copyright © 2019 Yusuke Kita. All rights reserved. // import Foundation import SwiftUI struct RepositoryDetailView: View { var text: String var body: some View { Text(text) } } #if DEBUG struct RepositoryDetailView_Previews : PreviewProvider { static var previews: some View { RepositoryDetailView(text: "foo") } } #endif
17.111111
56
0.670996
143bb3e40d5a4ecc3cf93637c202736a23a70431
2,337
// // CampaignControllerTriggerLegacyQualityResponse.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct CampaignControllerTriggerLegacyQualityResponse: Codable { public enum TriggerType: String, Codable { case share = "SHARE" case purchase = "PURCHASE" case event = "EVENT" case score = "SCORE" case zoneState = "ZONE_STATE" case apiVersion = "API_VERSION" case referredByEvent = "REFERRED_BY_EVENT" case legacyQuality = "LEGACY_QUALITY" case expression = "EXPRESSION" case access = "ACCESS" case dataIntelligenceEvent = "DATA_INTELLIGENCE_EVENT" case hasPriorStep = "HAS_PRIOR_STEP" case maxmind = "MAXMIND" case rewardEvent = "REWARD_EVENT" case hasPriorReward = "HAS_PRIOR_REWARD" } public var triggerId: String? public var triggerType: TriggerType? public var triggerPhase: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerPhase? public var triggerName: BuildtimeEvaluatableControllerBuildtimeContextString? public var componentReferences: [CampaignComponentReferenceResponse]? public var actionType: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerActionType? public init(triggerId: String? = nil, triggerType: TriggerType? = nil, triggerPhase: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerPhase? = nil, triggerName: BuildtimeEvaluatableControllerBuildtimeContextString? = nil, componentReferences: [CampaignComponentReferenceResponse]? = nil, actionType: BuildtimeEvaluatableControllerBuildtimeContextCampaignControllerTriggerActionType? = nil) { self.triggerId = triggerId self.triggerType = triggerType self.triggerPhase = triggerPhase self.triggerName = triggerName self.componentReferences = componentReferences self.actionType = actionType } public enum CodingKeys: String, CodingKey { case triggerId = "trigger_id" case triggerType = "trigger_type" case triggerPhase = "trigger_phase" case triggerName = "trigger_name" case componentReferences = "component_references" case actionType = "action_type" } }
41
417
0.738554
eb2ea32d4dc876626d492fa97484f1a417dc1dde
38,689
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // StringObject abstracts the bit-level interpretation and creation of the // String struct. // // TODO(String docs): Word-level diagram @_fixed_layout @usableFromInline internal struct _StringObject { /* On 64-bit platforms, the discriminator is the most significant 8 bits of the bridge object. ┌─────────────────────╥─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ │ Form ║ 7 │ 6 │ 5 │ 4 │ 3 │ 2 │ 1 │ 0 │ ╞═════════════════════╬═════╪═════╪═════╪═════╪═════╧═════╧═════╧═════╡ │ Immortal, Small ║ 1 │ASCII│ 1 │ 0 │ small count │ ├─────────────────────╫─────┼─────┼─────┼─────┼─────┬─────┬─────┬─────┤ │ Immortal, Large ║ 1 │ 0 │ 0 │ 0 │ 0 │ TBD │ TBD │ TBD │ ╞═════════════════════╬═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╡ │ Native ║ 0 │ 0 │ 0 │ 0 │ 0 │ TBD │ TBD │ TBD │ ├─────────────────────╫─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │ Shared ║ x │ 0 │ 0 │ 0 │ 1 │ TBD │ TBD │ TBD │ ├─────────────────────╫─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │ Shared, Bridged ║ 0 │ 1 │ 0 │ 0 │ 1 │ TBD │ TBD │ TBD │ ╞═════════════════════╬═════╪═════╪═════╪═════╪═════╪═════╪═════╪═════╡ │ Foreign ║ x │ 0 │ 0 │ 1 │ 1 │ TBD │ TBD │ TBD │ ├─────────────────────╫─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ │ Foreign, Bridged ║ 0 │ 1 │ 0 │ 1 │ 1 │ TBD │ TBD │ TBD │ └─────────────────────╨─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ b7: isImmortal: Should the Swift runtime skip ARC - Small strings are just values, always immortal - Large strings can sometimes be immortal, e.g. literals b6: (large) isBridged / (small) isASCII - For large strings, this means lazily-bridged NSString: perform ObjC ARC - Small strings repurpose this as a dedicated bit to remember ASCII-ness b5: isSmall: Dedicated bit to denote small strings b4: isForeign: aka isSlow, cannot provide access to contiguous UTF-8 b3: (large) not isTailAllocated: payload isn't a biased pointer - Shared strings provide contiguous UTF-8 through extra level of indirection The canonical empty string is the zero-sized small string. It has a leading nibble of 1110, and all other bits are 0. A "dedicated" bit is used for the most frequent fast-path queries so that they can compile to a fused check-and-branch, even if that burns part of the encoding space. On 32-bit platforms, we use an explicit discriminator with the same encoding as above, except bit 7 is omitted from storage -- it is left free, to supply extra inhabitants in the StringObject structure. The missing bit can be recovered by looking at `_variant.isImmortal`. */ @_fixed_layout @usableFromInline struct Discriminator { @usableFromInline internal var _value: UInt8 @inlinable @inline(__always) internal init(_ value: UInt8) { self._value = value } } #if arch(i386) || arch(arm) @usableFromInline @_frozen internal enum Variant { case immortal(UInt) case native(AnyObject) case bridged(_CocoaString) @inlinable @inline(__always) internal static func immortal(start: UnsafePointer<UInt8>) -> Variant { let biased = UInt(bitPattern: start) &- _StringObject.nativeBias return .immortal(biased) } @inlinable internal var isImmortal: Bool { @inline(__always) get { if case .immortal = self { return true } return false } } } @_fixed_layout @usableFromInline struct Flags { @usableFromInline internal var _value: UInt16 @inlinable @inline(__always) init(_ value: UInt16) { self._value = value } } @_fixed_layout @usableFromInline struct CountAndFlags { @usableFromInline internal var count: Int @usableFromInline internal var flags: Flags @inlinable @inline(__always) init(count: Int, flags: Flags) { self.count = count self.flags = flags } @inlinable @inline(__always) internal func _invariantCheck() { flags._invariantCheck() } } @usableFromInline internal var _count: Int @usableFromInline internal var _variant: Variant @usableFromInline internal var _discriminator: Discriminator @usableFromInline internal var _flags: Flags @inlinable @inline(__always) init( count: Int, variant: Variant, discriminator: Discriminator, flags: Flags ) { self._count = count self._variant = variant self._discriminator = discriminator self._flags = flags } @inlinable internal var _countAndFlags: CountAndFlags { @inline(__always) get { return CountAndFlags(count: _count, flags: _flags) } } #else // Abstract the count and performance-flags containing word @_fixed_layout @usableFromInline struct CountAndFlags { @usableFromInline var _storage: UInt @inlinable @inline(__always) internal init(zero: ()) { self._storage = 0 } } // // Laid out as (_countAndFlags, _object), which allows small string contents to // naturally start on vector-alignment. // @usableFromInline internal var _countAndFlags: CountAndFlags @usableFromInline internal var _object: Builtin.BridgeObject @inlinable @inline(__always) internal init(zero: ()) { self._countAndFlags = CountAndFlags(zero:()) self._object = Builtin.valueToBridgeObject(UInt64(0)._value) } #endif // Namespace to hold magic numbers @usableFromInline @_frozen enum Nibbles {} } extension _StringObject { @inlinable internal var discriminator: Discriminator { @inline(__always) get { #if arch(i386) || arch(arm) return _discriminator #else let d = objectRawBits &>> Nibbles.discriminatorShift return Discriminator(UInt8(truncatingIfNeeded: d)) #endif } } } // Raw extension _StringObject { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) #if arch(i386) || arch(arm) // On 32-bit platforms, raw bit conversion is one-way only and uses the same // layout as on 64-bit platforms. @usableFromInline internal var rawBits: RawBitPattern { @inline(__always) get { let count = UInt64(truncatingIfNeeded: UInt(bitPattern: _count)) let payload = UInt64(truncatingIfNeeded: undiscriminatedObjectRawBits) let flags = UInt64(truncatingIfNeeded: _flags._value) let discr = UInt64(truncatingIfNeeded: _discriminator._value) if isSmall { // Rearrange small strings in a different way, compacting bytes into a // contiguous sequence. See comment on small string layout below. return (count | (payload &<< 32), flags | (discr &<< 56)) } return (count | (flags &<< 48), payload | (discr &<< 56)) } } #else @inlinable internal var rawBits: RawBitPattern { @inline(__always) get { return (_countAndFlags.rawBits, objectRawBits) } } @inlinable @inline(__always) internal init( bridgeObject: Builtin.BridgeObject, countAndFlags: CountAndFlags ) { self._object = bridgeObject self._countAndFlags = countAndFlags _invariantCheck() } @inlinable @inline(__always) internal init( object: AnyObject, discriminator: UInt64, countAndFlags: CountAndFlags ) { let builtinRawObject: Builtin.Int64 = Builtin.reinterpretCast(object) let builtinDiscrim: Builtin.Int64 = discriminator._value self.init( bridgeObject: Builtin.reinterpretCast( Builtin.stringObjectOr_Int64(builtinRawObject, builtinDiscrim)), countAndFlags: countAndFlags) } // Initializer to use for tagged (unmanaged) values @inlinable @inline(__always) internal init( pointerBits: UInt64, discriminator: UInt64, countAndFlags: CountAndFlags ) { let builtinValueBits: Builtin.Int64 = pointerBits._value let builtinDiscrim: Builtin.Int64 = discriminator._value self.init( bridgeObject: Builtin.valueToBridgeObject(Builtin.stringObjectOr_Int64( builtinValueBits, builtinDiscrim)), countAndFlags: countAndFlags) } @inlinable @inline(__always) internal init(rawUncheckedValue bits: RawBitPattern) { self.init(zero:()) self._countAndFlags = CountAndFlags(rawUnchecked: bits.0) self._object = Builtin.valueToBridgeObject(bits.1._value) _internalInvariant(self.rawBits == bits) } @inlinable @inline(__always) internal init(rawValue bits: RawBitPattern) { self.init(rawUncheckedValue: bits) _invariantCheck() } @inlinable @_transparent internal var objectRawBits: UInt64 { @inline(__always) get { return Builtin.reinterpretCast(_object) } } #endif } extension _StringObject { @inlinable @_transparent internal var undiscriminatedObjectRawBits: UInt { @inline(__always) get { #if arch(i386) || arch(arm) switch _variant { case .immortal(let bitPattern): return bitPattern case .native(let storage): return Builtin.reinterpretCast(storage) case .bridged(let object): return Builtin.reinterpretCast(object) } #else return UInt(truncatingIfNeeded: objectRawBits & Nibbles.largeAddressMask) #endif } } } #if !(arch(i386) || arch(arm)) extension _StringObject.CountAndFlags { @usableFromInline internal typealias RawBitPattern = UInt64 @inlinable internal var rawBits: RawBitPattern { @inline(__always) get { return UInt64(truncatingIfNeeded: _storage) } } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = UInt(truncatingIfNeeded: bits) } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } } #endif /* Encoding is optimized for common fast creation. The canonical empty string, ASCII small strings, as well as most literals, have all consecutive 1s in their high nibble mask, and thus can all be encoded as a logical immediate operand on arm64. See docs for _StringOjbect.Discriminator for the layout of the high nibble */ #if arch(i386) || arch(arm) extension _StringObject.Discriminator { @inlinable internal static var empty: _StringObject.Discriminator { @inline(__always) get { return _StringObject.Discriminator.small(withCount: 0, isASCII: true) } } } #else extension _StringObject.Nibbles { // The canonical empty sting is an empty small string @inlinable internal static var emptyString: UInt64 { @inline(__always) get { return _StringObject.Nibbles.small(isASCII: true) } } } #endif /* Large strings can either be "native", "shared", or "foreign". Native strings have tail-allocated storage, which begins at an offset of `nativeBias` from the storage object's address. String literals, which reside in the constant section, are encoded as their start address minus `nativeBias`, unifying code paths for both literals ("immortal native") and native strings. Native Strings are always managed by the Swift runtime. Shared strings do not have tail-allocated storage, but can provide access upon query to contiguous UTF-8 code units. Lazily-bridged NSStrings capable of providing access to contiguous ASCII/UTF-8 set the ObjC bit. Accessing shared string's pointer should always be behind a resilience barrier, permitting future evolution. Foreign strings cannot provide access to contiguous UTF-8. Currently, this only encompasses lazily-bridged NSStrings that cannot be treated as "shared". Such strings may provide access to contiguous UTF-16, or may be discontiguous in storage. Accessing foreign strings should remain behind a resilience barrier for future evolution. Other foreign forms are reserved for the future. Shared and foreign strings are always created and accessed behind a resilience barrier, providing flexibility for the future. ┌────────────┐ │ nativeBias │ ├────────────┤ │ 32 │ └────────────┘ ┌───────────────┬────────────┐ │ b63:b56 │ b55:b0 │ ├───────────────┼────────────┤ │ discriminator │ objectAddr │ └───────────────┴────────────┘ discriminator: See comment for _StringObject.Discriminator objectAddr: The address of the beginning of the potentially-managed object. TODO(Future): For Foreign strings, consider allocating a bit for whether they can provide contiguous UTF-16 code units, which would allow us to avoid doing the full call for non-contiguous NSString. */ extension _StringObject.Nibbles { // Mask for address bits, i.e. non-discriminator and non-extra high bits @inlinable static internal var largeAddressMask: UInt64 { @inline(__always) get { return 0x00FF_FFFF_FFFF_FFFF } } // Mask for discriminator bits @inlinable static internal var discriminatorMask: UInt64 { @inline(__always) get { return ~largeAddressMask } } // Position of discriminator bits @inlinable static internal var discriminatorShift: Int { @inline(__always) get { return 56 } } } extension _StringObject.Discriminator { // Discriminator for small strings @inlinable @inline(__always) internal static func small( withCount count: Int, isASCII: Bool ) -> _StringObject.Discriminator { _internalInvariant(count >= 0 && count <= _SmallString.capacity) let c = UInt8(truncatingIfNeeded: count) return _StringObject.Discriminator((isASCII ? 0xE0 : 0xA0) | c) } #if arch(i386) || arch(arm) // Discriminator for large, immortal, swift-native strings @inlinable @inline(__always) internal static func largeImmortal() -> _StringObject.Discriminator { return _StringObject.Discriminator(0x80) } // Discriminator for large, mortal (i.e. managed), swift-native strings @inlinable @inline(__always) internal static func largeMortal() -> _StringObject.Discriminator { return _StringObject.Discriminator(0x00) } // Discriminator for large, shared, mortal (i.e. managed), swift-native // strings @inlinable @inline(__always) internal static func largeSharedMortal() -> _StringObject.Discriminator { return _StringObject.Discriminator(0x08) } internal static func largeCocoa( providesFastUTF8: Bool ) -> _StringObject.Discriminator { return _StringObject.Discriminator(providesFastUTF8 ? 0x48 : 0x58) } #endif } #if !(arch(i386) || arch(arm)) // FIXME: Can we just switch to using the Discriminator factories above? extension _StringObject.Nibbles { // Discriminator for small strings @inlinable @inline(__always) internal static func small(isASCII: Bool) -> UInt64 { return isASCII ? 0xE000_0000_0000_0000 : 0xA000_0000_0000_0000 } // Discriminator for small strings @inlinable @inline(__always) internal static func small(withCount count: Int, isASCII: Bool) -> UInt64 { _internalInvariant(count <= _SmallString.capacity) return small(isASCII: isASCII) | UInt64(truncatingIfNeeded: count) &<< 56 } // Discriminator for large, immortal, swift-native strings @inlinable @inline(__always) internal static func largeImmortal() -> UInt64 { return 0x8000_0000_0000_0000 } // Discriminator for large, mortal (i.e. managed), swift-native strings @inlinable @inline(__always) internal static func largeMortal() -> UInt64 { return 0x0000_0000_0000_0000 } // Discriminator for large, shared, mortal (i.e. managed), swift-native // strings @inlinable @inline(__always) internal static func largeSharedMortal() -> UInt64 { return 0x0800_0000_0000_0000 } internal static func largeCocoa(providesFastUTF8: Bool) -> UInt64 { return providesFastUTF8 ? 0x4800_0000_0000_0000 : 0x5800_0000_0000_0000 } } #endif extension _StringObject.Discriminator { @inlinable internal var isImmortal: Bool { @inline(__always) get { return (_value & 0x80) != 0 } } @inlinable internal var isSmall: Bool { @inline(__always) get { return (_value & 0x20) != 0 } } @inlinable internal var smallIsASCII: Bool { @inline(__always) get { _internalInvariant(isSmall) return (_value & 0x40) != 0 } } @inlinable internal var smallCount: Int { @inline(__always) get { _internalInvariant(isSmall) return Int(truncatingIfNeeded: _value & 0x0F) } } @inlinable internal var providesFastUTF8: Bool { @inline(__always) get { return (_value & 0x10) == 0 } } // Whether we are a mortal, native string @inlinable internal var hasNativeStorage: Bool { @inline(__always) get { return (_value & 0xF8) == 0 } } // Whether we are a mortal, shared string (managed by Swift runtime) internal var hasSharedStorage: Bool { @inline(__always) get { return (_value & 0xF8) == 0x08 } } @inlinable internal var largeFastIsNative: Bool { @inline(__always) get { _internalInvariant(!isSmall && providesFastUTF8) return (_value & 0x08) == 0 } } // Whether this string is a lazily-bridged NSString, presupposing it is large @inlinable internal var largeIsCocoa: Bool { @inline(__always) get { _internalInvariant(!isSmall) return (_value & 0x40) != 0 } } } extension _StringObject.Discriminator { @inlinable internal var rawBits: UInt64 { return UInt64(_value) &<< _StringObject.Nibbles.discriminatorShift } } extension _StringObject { @inlinable internal static var nativeBias: UInt { @inline(__always) get { #if arch(i386) || arch(arm) return 20 #else return 32 #endif } } @inlinable internal var isImmortal: Bool { @inline(__always) get { #if arch(i386) || arch(arm) return _variant.isImmortal #else return (objectRawBits & 0x8000_0000_0000_0000) != 0 #endif } } @inlinable internal var isMortal: Bool { @inline(__always) get { return !isImmortal } } @inlinable internal var isSmall: Bool { @inline(__always) get { #if arch(i386) || arch(arm) return _discriminator.isSmall #else return (objectRawBits & 0x2000_0000_0000_0000) != 0 #endif } } @inlinable internal var isLarge: Bool { @inline(__always) get { return !isSmall } } // Whether this string can provide access to contiguous UTF-8 code units: // - Small strings can by spilling to the stack // - Large native strings can through an offset // - Shared strings can: // - Cocoa strings which respond to e.g. CFStringGetCStringPtr() // - Non-Cocoa shared strings @inlinable internal var providesFastUTF8: Bool { @inline(__always) get { #if arch(i386) || arch(arm) return _discriminator.providesFastUTF8 #else return (objectRawBits & 0x1000_0000_0000_0000) == 0 #endif } } @inlinable internal var isForeign: Bool { @inline(__always) get { return !providesFastUTF8 } } // Whether we are a mortal, native string @inlinable internal var hasNativeStorage: Bool { @inline(__always) get { #if arch(i386) || arch(arm) return _discriminator.hasNativeStorage #else return (objectRawBits & 0xF800_0000_0000_0000) == 0 #endif } } // Whether we are a mortal, shared string (managed by Swift runtime) internal var hasSharedStorage: Bool { @inline(__always) get { #if arch(i386) || arch(arm) return _discriminator.hasSharedStorage #else return (objectRawBits & 0xF800_0000_0000_0000) == Nibbles.largeSharedMortal() #endif } } } // Queries conditional on being in a large or fast form. extension _StringObject { // Whether this string is native, presupposing it is both large and fast @inlinable internal var largeFastIsNative: Bool { @inline(__always) get { _internalInvariant(isLarge && providesFastUTF8) #if arch(i386) || arch(arm) return _discriminator.largeFastIsNative #else return (objectRawBits & 0x0800_0000_0000_0000) == 0 #endif } } // Whether this string is shared, presupposing it is both large and fast @inlinable internal var largeFastIsShared: Bool { @inline(__always) get { return !largeFastIsNative } } // Whether this string is a lazily-bridged NSString, presupposing it is large @inlinable internal var largeIsCocoa: Bool { @inline(__always) get { _internalInvariant(isLarge) #if arch(i386) || arch(arm) return _discriminator.largeIsCocoa #else return (objectRawBits & 0x4000_0000_0000_0000) != 0 #endif } } } /* On 64-bit platforms, small strings have the following per-byte layout. When stored in memory (little-endian), their first character ('a') is in the lowest address and their top-nibble and count is in the highest address. ┌───────────────────────────────┬─────────────────────────────────────────────┐ │ _countAndFlags │ _object │ ├───┬───┬───┬───┬───┬───┬───┬───┼───┬───┬────┬────┬────┬────┬────┬────────────┤ │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ 12 │ 13 │ 14 │ 15 │ ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼────┼────┼────┼────┼────┼────────────┤ │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ 1x0x count │ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴────┴────┴────┴────┴────┴────────────┘ On 32-bit platforms, we have less space to store code units, and it isn't contiguous. However, we still use the above layout for the RawBitPattern representation. ┌───────────────┬───────────────────┬───────┬─────────┐ │ _count │_variant .immortal │_discr │ _flags │ ├───┬───┬───┬───┼───┬───┬───┬───┬───┼───────┼────┬────┤ │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ ├───┼───┼───┼───┼───┴───┴───┴───┴───┼───────┼────┼────┤ │ a │ b │ c │ d │ e f g h │x10 cnt│ i │ j │ └───┴───┴───┴───┴───────────────────┴───────┴────┴────┘ */ extension _StringObject { @inlinable internal var smallCount: Int { @inline(__always) get { _internalInvariant(isSmall) return discriminator.smallCount } } @inlinable internal var smallIsASCII: Bool { @inline(__always) get { _internalInvariant(isSmall) #if arch(i386) || arch(arm) return _discriminator.smallIsASCII #else return objectRawBits & 0x4000_0000_0000_0000 != 0 #endif } } @inlinable @inline(__always) internal init(_ small: _SmallString) { #if arch(i386) || arch(arm) let (word1, word2) = small.rawBits let countBits = Int(truncatingIfNeeded: word1) let variantBits = UInt(truncatingIfNeeded: word1 &>> 32) let flagBits = UInt16(truncatingIfNeeded: word2) let discriminatorBits = UInt8(truncatingIfNeeded: word2 &>> 56) _internalInvariant(discriminatorBits & 0xA0 == 0xA0) self.init( count: countBits, variant: .immortal(variantBits), discriminator: Discriminator(discriminatorBits), flags: Flags(flagBits) ) #else self.init(rawValue: small.rawBits) #endif _internalInvariant(isSmall) } @inlinable @inline(__always) internal init(empty:()) { // Canonical empty pattern: small zero-length string #if arch(i386) || arch(arm) self.init( count: 0, variant: .immortal(0), discriminator: .empty, flags: Flags(0)) #else self._countAndFlags = CountAndFlags(zero:()) self._object = Builtin.valueToBridgeObject(Nibbles.emptyString._value) #endif _internalInvariant(self.smallCount == 0) _invariantCheck() } } /* // TODO(String docs): Combine this with Nibbles table, and perhaps small string // table, into something that describes the higher-level structure of // _StringObject. All non-small forms share the same structure for the other half of the bits (i.e. non-object bits) as a word containing code unit count and various performance flags. The top 16 bits are for performance flags, which are not semantically relevant but communicate that some operations can be done more efficiently on this particular string, and the lower 48 are the code unit count (aka endIndex). ┌─────────┬───────┬────────┬───────┐ │ b63 │ b62 │ b61:48 │ b47:0 │ ├─────────┼───────┼────────┼───────┤ │ isASCII │ isNFC │ TBD │ count │ └─────────┴───────┴────────┴───────┘ isASCII: set when all code units are known to be ASCII, enabling: - Trivial Unicode scalars, they're just the code units - Trivial UTF-16 transcoding (just bit-extend) - Also, isASCII always implies isNFC isNFC: set when the contents are in normal form C, enable: - Trivial lexicographical comparisons: just memcmp Allocation of more performance flags is TBD, un-used bits will be reserved for future use. Count stores the number of code units: corresponds to `endIndex`. */ #if arch(i386) || arch(arm) extension _StringObject.Flags { @inlinable internal var isASCII: Bool { @inline(__always) get { return _value & 0x8000 != 0 } } @inlinable internal var isNFC: Bool { @inline(__always) get { return _value & 0x4000 != 0 } } @inlinable @inline(__always) init(isASCII: Bool) { // ASCII also entails NFC self._value = isASCII ? 0xC000 : 0x0000 } #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { if isASCII { _internalInvariant(isNFC) } } #endif // INTERNAL_CHECKS_ENABLED } #else extension _StringObject.CountAndFlags { @inlinable @inline(__always) internal init(count: Int) { self.init(zero:()) self.count = count _invariantCheck() } @inlinable @inline(__always) internal init(count: Int, isASCII: Bool) { self.init(zero:()) self.count = count if isASCII { // ASCII implies NFC self._storage |= 0xC000_0000_0000_0000 } _invariantCheck() } @inlinable internal var countMask: UInt { @inline(__always) get { return 0x0000_FFFF_FFFF_FFFF } } @inlinable internal var flagsMask: UInt { @inline(__always) get { return ~countMask} } @inlinable internal var count: Int { @inline(__always) get { return Int(bitPattern: _storage & countMask) } @inline(__always) set { _internalInvariant(newValue <= countMask, "too large") _storage = (_storage & flagsMask) | UInt(bitPattern: newValue) } } @inlinable internal var isASCII: Bool { return 0 != _storage & 0x8000_0000_0000_0000 } @inlinable internal var isNFC: Bool { return 0 != _storage & 0x4000_0000_0000_0000 } #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { if isASCII { _internalInvariant(isNFC) } } #endif // INTERNAL_CHECKS_ENABLED } #endif // Extract extension _StringObject { @inlinable internal var largeCount: Int { @inline(__always) get { _internalInvariant(isLarge) #if arch(i386) || arch(arm) return _count #else return _countAndFlags.count #endif } @inline(__always) set { #if arch(i386) || arch(arm) _count = newValue #else _countAndFlags.count = newValue #endif _internalInvariant(newValue == largeCount) _invariantCheck() } } @inlinable internal var largeAddressBits: UInt { @inline(__always) get { _internalInvariant(isLarge) return undiscriminatedObjectRawBits } } @inlinable internal var nativeUTF8Start: UnsafePointer<UInt8> { @inline(__always) get { _internalInvariant(largeFastIsNative) return UnsafePointer( bitPattern: largeAddressBits &+ _StringObject.nativeBias )._unsafelyUnwrappedUnchecked } } @inlinable internal var nativeUTF8: UnsafeBufferPointer<UInt8> { @inline(__always) get { _internalInvariant(largeFastIsNative) return UnsafeBufferPointer(start: nativeUTF8Start, count: largeCount) } } // Resilient way to fetch a pointer @usableFromInline @inline(never) @_effects(releasenone) internal func getSharedUTF8Start() -> UnsafePointer<UInt8> { _internalInvariant(largeFastIsShared) #if _runtime(_ObjC) if largeIsCocoa { return _cocoaUTF8Pointer(cocoaObject)._unsafelyUnwrappedUnchecked } #endif return sharedStorage.start } @usableFromInline internal var sharedUTF8: UnsafeBufferPointer<UInt8> { @_effects(releasenone) @inline(never) get { _internalInvariant(largeFastIsShared) let start = self.getSharedUTF8Start() return UnsafeBufferPointer(start: start, count: largeCount) } } internal var nativeStorage: _StringStorage { @inline(__always) get { #if arch(i386) || arch(arm) guard case .native(let storage) = _variant else { _internalInvariantFailure() } return _unsafeUncheckedDowncast(storage, to: _StringStorage.self) #else _internalInvariant(hasNativeStorage) return Builtin.reinterpretCast(largeAddressBits) #endif } } internal var sharedStorage: _SharedStringStorage { @inline(__always) get { #if arch(i386) || arch(arm) guard case .native(let storage) = _variant else { _internalInvariantFailure() } return _unsafeUncheckedDowncast(storage, to: _SharedStringStorage.self) #else _internalInvariant(largeFastIsShared && !largeIsCocoa) _internalInvariant(hasSharedStorage) return Builtin.reinterpretCast(largeAddressBits) #endif } } internal var cocoaObject: AnyObject { @inline(__always) get { #if arch(i386) || arch(arm) guard case .bridged(let object) = _variant else { _internalInvariantFailure() } return object #else _internalInvariant(largeIsCocoa && !isImmortal) return Builtin.reinterpretCast(largeAddressBits) #endif } } } // Aggregate queries / abstractions extension _StringObject { // The number of code units stored // // TODO(String micro-performance): Check generated code @inlinable internal var count: Int { @inline(__always) get { return isSmall ? smallCount : largeCount } } // // Whether the string is all ASCII // @inlinable internal var isASCII: Bool { @inline(__always) get { if isSmall { return smallIsASCII } #if arch(i386) || arch(arm) return _flags.isASCII #else return _countAndFlags.isASCII #endif } } @inlinable internal var isNFC: Bool { @inline(__always) get { if isSmall { // TODO(String performance): Worth implementing more sophisiticated // check, or else performing normalization on- construction. For now, // approximate it with isASCII return smallIsASCII } #if arch(i386) || arch(arm) return _flags.isNFC #else return _countAndFlags.isNFC #endif } } // Get access to fast UTF-8 contents for large strings which provide it. @inlinable internal var fastUTF8: UnsafeBufferPointer<UInt8> { @inline(__always) get { _internalInvariant(self.isLarge && self.providesFastUTF8) if _slowPath(self.largeFastIsShared) { return sharedUTF8 } return UnsafeBufferPointer( start: self.nativeUTF8Start, count: self.largeCount) } } // Whether the object stored can be bridged directly as a NSString @usableFromInline // @opaque internal var hasObjCBridgeableObject: Bool { @_effects(releasenone) get { // Currently, all mortal objects can zero-cost bridge return !self.isImmortal } } // Fetch the stored subclass of NSString for bridging @inlinable internal var objCBridgeableObject: AnyObject { @inline(__always) get { _internalInvariant(hasObjCBridgeableObject) return Builtin.reinterpretCast(largeAddressBits) } } // Whether the object provides fast UTF-8 contents that are nul-terminated @inlinable internal var isFastZeroTerminated: Bool { if _slowPath(!providesFastUTF8) { return false } // Small strings nul-terminate when spilling for contiguous access if isSmall { return true } // TODO(String performance): Use performance flag, which could be more // inclusive. For now, we only know native strings and small strings (when // accessed) are. We could also know about some shared strings. return largeFastIsNative } } // Object creation extension _StringObject { @inlinable @inline(__always) internal init(immortal bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { #if arch(i386) || arch(arm) self.init( count: bufPtr.count, variant: .immortal(start: bufPtr.baseAddress._unsafelyUnwrappedUnchecked), discriminator: .largeImmortal(), flags: Flags(isASCII: isASCII)) #else // We bias to align code paths for mortal and immortal strings let biasedAddress = UInt( bitPattern: bufPtr.baseAddress._unsafelyUnwrappedUnchecked ) &- _StringObject.nativeBias let countAndFlags = CountAndFlags(count: bufPtr.count, isASCII: isASCII) self.init( pointerBits: UInt64(truncatingIfNeeded: biasedAddress), discriminator: Nibbles.largeImmortal(), countAndFlags: countAndFlags) #endif } @inline(__always) internal init(_ storage: _StringStorage) { #if arch(i386) || arch(arm) self.init( count: storage._count, variant: .native(storage), discriminator: .largeMortal(), flags: storage._flags) #else self.init( object: storage, discriminator: Nibbles.largeMortal(), countAndFlags: storage._countAndFlags) #endif } internal init(_ storage: _SharedStringStorage, isASCII: Bool) { #if arch(i386) || arch(arm) self.init( count: storage._count, variant: .native(storage), discriminator: .largeSharedMortal(), flags: storage._flags) #else self.init( object: storage, discriminator: Nibbles.largeSharedMortal(), countAndFlags: storage._countAndFlags) #endif } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { #if arch(i386) || arch(arm) self.init( count: length, variant: .bridged(cocoa), discriminator: .largeCocoa(providesFastUTF8: providesFastUTF8), flags: Flags(isASCII: isASCII)) #else let countAndFlags = CountAndFlags(count: length, isASCII: isASCII) let discriminator = Nibbles.largeCocoa(providesFastUTF8: providesFastUTF8) self.init( object: cocoa, discriminator: discriminator, countAndFlags: countAndFlags) _internalInvariant(self.largeAddressBits == Builtin.reinterpretCast(cocoa)) _internalInvariant(self.providesFastUTF8 == providesFastUTF8) _internalInvariant(self.largeCount == length) #endif } } // Internal invariants extension _StringObject { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) _internalInvariant(MemoryLayout<_StringObject>.size == 12) _internalInvariant(MemoryLayout<_StringObject>.stride == 12) _internalInvariant(MemoryLayout<_StringObject>.alignment == 4) _internalInvariant(MemoryLayout<_StringObject?>.size == 12) _internalInvariant(MemoryLayout<_StringObject?>.stride == 12) _internalInvariant(MemoryLayout<_StringObject?>.alignment == 4) #else _internalInvariant(MemoryLayout<_StringObject>.size == 16) _internalInvariant(MemoryLayout<_StringObject?>.size == 16) #endif if isForeign { _internalInvariant(largeIsCocoa, "No other foreign forms yet") } if isSmall { _internalInvariant(isImmortal) _internalInvariant(smallCount <= 15) _internalInvariant(smallCount == count) _internalInvariant(!hasObjCBridgeableObject) } else { _internalInvariant(isLarge) _internalInvariant(largeCount == count) if providesFastUTF8 && largeFastIsNative { _internalInvariant(!isSmall) _internalInvariant(!largeIsCocoa) if isImmortal { _internalInvariant(!hasNativeStorage) _internalInvariant(!hasObjCBridgeableObject) } else { _internalInvariant(hasNativeStorage) _internalInvariant(hasObjCBridgeableObject) _internalInvariant(nativeStorage.count == self.count) } } if largeIsCocoa { _internalInvariant(hasObjCBridgeableObject) _internalInvariant(!isSmall) if isForeign { } else { _internalInvariant(largeFastIsShared) } } } #if arch(i386) || arch(arm) switch _variant { case .immortal: _internalInvariant(isImmortal) case .native: _internalInvariant(hasNativeStorage || hasSharedStorage) case .bridged: _internalInvariant(isLarge) _internalInvariant(largeIsCocoa) } #endif } #endif // INTERNAL_CHECKS_ENABLED @inline(never) internal func _dump() { #if INTERNAL_CHECKS_ENABLED let raw = self.rawBits let word0 = ("0000000000000000" + String(raw.0, radix: 16)).suffix(16) let word1 = ("0000000000000000" + String(raw.1, radix: 16)).suffix(16) #if arch(i386) || arch(arm) print(""" StringObject(\ <\(word0) \(word1)> \ count: \(String(_count, radix: 16)), \ variant: \(_variant), \ discriminator: \(_discriminator), \ flags: \(_flags)) """) #else print("StringObject(<\(word0) \(word1)>)") #endif let repr = _StringGuts(self)._classify() switch repr._form { case ._small: _SmallString(self)._dump() case ._immortal(address: let address): print(""" Immortal(\ start: \(UnsafeRawPointer(bitPattern: address)!), \ count: \(repr._count)) """) case ._native(_): print(""" Native(\ owner: \(repr._objectIdentifier!), \ count: \(repr._count), \ capacity: \(repr._capacity)) """) case ._cocoa(object: let object): let address: UnsafeRawPointer = Builtin.reinterpretCast(object) print("Cocoa(address: \(address))") } #endif // INTERNAL_CHECKS_ENABLED } }
29.133283
81
0.661118
08522e3de3458a5175cbe9d7668ad43808abad11
3,812
// // ChooseSeatVC+Layout.swift // Galaxy App // // Created by Ko Kyaw on 28/07/2021. // import UIKit extension ChooseSeatVC { func setupViews() { view.addSubview(backButton) backButton.snp.makeConstraints { (make) in make.top.equalTo(view.safeAreaLayoutGuide).inset(18) make.leading.equalToSuperview().inset(24) } setupTopSV() setupMiddleSV() setupBottomSV() [topSV!, middleSV!, bottomSV!, UIView()].forEach { contentStackView.addArrangedSubview($0) } contentStackView.setCustomSpacing(80, after: topSV!) view.addSubview(spinner) spinner.snp.makeConstraints { make in make.centerX.centerY.equalToSuperview() } } private func setupTopSV() { let projectorView = ProjectorView(frame: CGRect(x: -10, y: 0, width: view.frame.width - 20, height: 36)) topSV = UIStackView(subViews: [movieLabel, cinemaLabel, dateTimeLabel, projectorView], axis: .vertical, spacing: 0) topSV?.setCustomSpacing(6, after: cinemaLabel) topSV?.setCustomSpacing(20, after: dateTimeLabel) } private func setupMiddleSV() { let availableSeatLegend = createSeatLegend(title: "Available", color: .seatAvailable) let reservedSeatLegend = createSeatLegend(title: "Reserved", color: .seatReserved) let selectionSeatLegend = createSeatLegend(title: "Your selection", color: .galaxyViolet) let legendSV = UIStackView(arrangedSubviews: [availableSeatLegend, reservedSeatLegend, selectionSeatLegend]) legendSV.distribution = .fillEqually legendSV.isLayoutMarginsRelativeArrangement = true legendSV.layoutMargins = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 4) let dashLine = DashLine(color: .seatAvailable) dashLine.snp.makeConstraints { (make) in make.height.equalTo(2) } seatCollectionView.snp.makeConstraints { make in make.height.equalTo(600) } middleSV = UIStackView(subViews: [seatCollectionView, legendSV, dashLine], axis: .vertical, spacing: 20) middleSV?.setCustomSpacing(28, after: legendSV) middleSV?.isLayoutMarginsRelativeArrangement = true } private func setupBottomSV() { let ticketLabel = UILabel(text: "Tickets", font: .poppinsRegular, size: 20, color: .galaxyLightBlack) let seatsLabel = UILabel(text: "Seats", font: .poppinsRegular, size: 20, color: .galaxyLightBlack) [ticketLabel, seatsLabel].forEach { $0.snp.makeConstraints { (make) in make.width.equalTo(view.frame.width * 0.65) } } let ticketSV = UIStackView(arrangedSubviews: [ticketLabel, noOfTicketLabel]) let seatSV = UIStackView(arrangedSubviews: [seatsLabel, seatsNoLabel]) let sv = UIStackView(subViews: [ticketSV, seatSV], axis: .vertical, spacing: 16) buyTicketButton.snp.makeConstraints { (make) in make.width.equalTo(view.frame.width - 40) } bottomSV = UIStackView(subViews: [sv, buyTicketButton], axis: .vertical, spacing: 28) bottomSV?.alignment = .center } private func createSeatLegend(title: String, color: UIColor) -> UIStackView { let circle = UIView(backgroundColor: color) circle.snp.makeConstraints { (make) in make.width.height.equalTo(20) } circle.layer.cornerRadius = 20 / 2 let label = UILabel(text: title, font: .poppinsLight, size: 14, color: .galaxyBlack) let sv = UIStackView(arrangedSubviews: [circle, label]) sv.spacing = 8 return sv } }
37.372549
123
0.633526
bfb0c97bd640b5627f4dd6b44548299fcdc2c0fb
521
// // AddEventCell.swift // Operator // // Created by Frank Schmitt on 9/25/20. // Copyright © 2020 Apptentive, Inc. All rights reserved. // import UIKit class AddEventCell: UITableViewCell { @IBOutlet var textField: UITextField! override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.textField.becomeFirstResponder() } else { self.textField.resignFirstResponder() } } }
21.708333
65
0.648752
46342cf5bf911a15370f5af9b9e9a17ca8e71673
1,407
// // Bundle+FileKit.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Bundle { /// Returns an NSBundle for the given directory path. public convenience init?(path: Path) { self.init(path: path.absolute.rawValue) } }
37.026316
81
0.733475
64c3fbde571886543bbd8b7f21ccaa7a064d949e
3,339
// // Provider.swift // NFLSers-iOS // // Created by Qingyang Hu on 21/01/2018. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import Moya import SwiftyJSON import Cache import Result import ObjectMapper class AbstractProvider<T:TargetType> { let provider:MoyaProvider<T> public let notifier:MessageNotifier init() { provider = MainOAuth2().getRequestClosure(type: T.self) notifier = MessageNotifier() } internal func request<R:BaseMappable>( target: T, type: R.Type, success successCallback: @escaping (AbstractResponse<R>) -> Void, error errorCallback: ((_ error: Error) -> Void)? = nil, failure failureCallback: (() -> Void)? = nil ) { provider.request(target) { (result) in switch result { case let .success(response): if response.statusCode == 400 { if target.baseURL.absoluteString.hasPrefix("https://nfls.io") { NotificationCenter.default.post(name: NSNotification.Name(NotificationType.logout.rawValue), object: nil) self.notifier.showInfo("请重新登录。") } } else { if let json = JSON(response.data).dictionaryObject { do { let value = try AbstractResponse<R>(JSON: json) successCallback(value) } catch let error { debugPrint(error) do { let detail = try AbstractMessage(JSON: json) if let errorCallback = errorCallback { errorCallback(detail) } else { self.notifier.showNetworkError(detail) } } catch let errorWithError { debugPrint(errorWithError) if let errorCallback = errorCallback { errorCallback(AbstractError(status: 1001,message: errorWithError.localizedDescription)) } else { self.notifier.showNetworkError(AbstractError(status: 1001,message: errorWithError.localizedDescription)) } } } } else { debugPrint(String(data: response.data, encoding: .utf8) ?? "") if let failureCallback = failureCallback { failureCallback() } else { self.notifier.showNetworkError(AbstractError(status: 1002, message: "JSON解析失败,请检查网络及当前用户权限。")) } } } case .failure(let error): debugPrint(error) if let failureCallback = failureCallback { failureCallback() } else { self.notifier.showNetworkError(AbstractError(status: 0, message: "请求失败")) } } } } }
39.75
140
0.471399
2f004ac5834065cb0e6fccbf093da769ca8b51c4
3,913
// // MovieModel.swift // CineWatch // // Created by Andika on 25/10/21. // import Foundation public struct MovieModel: Equatable, Identifiable { public let id: Int public let posterPath, backdropPath: String public let isAdultRated: Bool public let overview: String public let releaseDate: Date? public let title: String public let language: String public let voteAverage: Double public var posterUrl: URL { return URL(string: "https://image.tmdb.org/t/p/w185" + posterPath)! } public var higherResolutionPosterUrl: URL { return URL(string: "https://image.tmdb.org/t/p/w500" + posterPath)! } public var backdropUrl: URL { return URL(string: "https://image.tmdb.org/t/p/w500" + backdropPath)! } public var higherResolutionBackdropUrl: URL { return URL(string: "https://image.tmdb.org/t/p/w780" + backdropPath)! } public var releaseYearDate: String { if releaseDate == Date(timeIntervalSince1970: 0) { return "-" } else { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY" return dateFormatter.string(from: releaseDate ?? Date(timeIntervalSince1970: 0)) } } public var releaseCompleteDate: String { if releaseDate == Date(timeIntervalSince1970: 0) { return "-" } else { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd, YYYY" return dateFormatter.string(from: releaseDate ?? Date(timeIntervalSince1970: 0)) } } public var capitalLanguage: String { return language.uppercased() } public init(id: Int, posterPath: String, backdropPath: String, isAdultRated: Bool, overview: String, releaseDate: Date?, title: String, language: String, voteAverage: Double) { self.id = id self.posterPath = posterPath self.backdropPath = backdropPath self.isAdultRated = isAdultRated self.overview = overview self.releaseDate = releaseDate self.title = title self.language = language self.voteAverage = voteAverage } } // swiftlint:disable line_length extension MovieModel { public static func fake() -> Self { return MovieModel(id: 438631, posterPath: "/d5NXSklXo0qyIYkgV94XAgMIckC.jpg", backdropPath: "/gOglaWhGx246MvzpnYMZ7HiBkiK.jpg", isAdultRated: true, overview: "Paul Atreides, a brilliant and gifted young man born into a great destiny beyond his understanding, must travel to the most dangerous planet in the universe to ensure the future of his family and his people. As malevolent forces explode into conflict over the planet's exclusive supply of the most precious resource in existence-a commodity capable of unlocking humanity's greatest potential-only those who can conquer their fear will survive.", releaseDate: Date(), title: "Dune", language: "en", voteAverage: 8.1) } public static func fakes() -> [Self] { return [ MovieModel(id: 438631, posterPath: "/d5NXSklXo0qyIYkgV94XAgMIckC.jpg", backdropPath: "/gOglaWhGx246MvzpnYMZ7HiBkiK.jpg", isAdultRated: false, overview: "Paul Atreides, a brilliant and gifted young man born into a great destiny beyond his understanding, must travel to the most dangerous planet in the universe to ensure the future of his family and his people. As malevolent forces explode into conflict over the planet's exclusive supply of the most precious resource in existence-a commodity capable of unlocking humanity's greatest potential-only those who can conquer their fear will survive.", releaseDate: Date(), title: "Dune", language: "en", voteAverage: 8.1) ] } } // swiftlint:enable line_length
40.760417
682
0.669563
c1e8f4a82ff7f83fd3f53bb0adb519c179670dce
443
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Evander", platforms: [ .iOS(.v12) ], products: [ .library( name: "Evander", targets: ["Evander"]), ], targets: [ .target( name: "Evander", dependencies: []) ] )
20.136364
96
0.541761
61662ac197f93ccb1931ae19d26b26482b352e0f
927
// // YNRefreshController.swift // YNRefreshController // // Created by Tommy on 15/3/14. // Copyright (c) 2015年 [email protected]. All rights reserved. // import Foundation import UIKit class YNRefreshController : NSObject { var scrollView: UIScrollView! init(scrollView: UIScrollView) { self.scrollView = scrollView super.init() } lazy var pullController: YNPullController = { return YNPullController() }() lazy var moreController: YNMoreController = { return YNMoreController(scrollView: self.scrollView) }() func pullHandler(handler: YNRefreshHandler) { // ... } func moreHandler(handler: YNRefreshHandler) { moreController.refreshHandler(handler) } func stopRefreshing() { // ... } func stopLoading() { self.moreController.refreshState = .Normal } }
21.068182
62
0.62028
f415eec800018608a55c10ee28097c0da796547c
493
// // ViewController.swift // Flix // // Created by Eshani K on 9/4/18. // Copyright © 2018 Eshani K. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
18.961538
80
0.659229