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
e91c9ba2866b94ba9b2e1fb36ea22259d5f72c81
4,711
// // TMDBClient.swift // TheMovieManager // // Created by Jarrod Parkes on 2/11/15. // Copyright (c) 2015 Jarrod Parkes. All rights reserved. // import Foundation // MARK: - TMDBClient: NSObject class TMDBClient : NSObject { // MARK: Properties // shared session var session = URLSession.shared // configuration object var config = TMDBConfig() // authentication state var requestToken: String? = nil var sessionID : String? = nil var userID : Int? = nil // MARK: Initializers override init() { super.init() } // MARK: GET //func taskForGETMethod(_ method: String, parameters: [String:AnyObject], completionHandlerForGET: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask {} // MARK: POST //func taskForPOSTMethod(_ method: String, parameters: [String:AnyObject], jsonBody: String, completionHandlerForPOST: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask {} // MARK: GET Image func taskForGETImage(_ size: String, filePath: String, completionHandlerForImage: @escaping (_ imageData: Data?, _ error: NSError?) -> Void) -> URLSessionTask { /* 1. Set the parameters */ // There are none... /* 2/3. Build the URL and configure the request */ let baseURL = URL(string: config.baseImageURLString)! let url = baseURL.appendingPathComponent(size).appendingPathComponent(filePath) let request = URLRequest(url: url) /* 4. Make the request */ let task = session.dataTask(with: request) { (data, response, error) in /* GUARD: Was there an error? */ guard (error == nil) else { print("There was an error with your request: \(error)") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else { print("Your request returned a status code other than 2xx!") return } /* GUARD: Was there any data returned? */ guard let data = data else { print("No data was returned by the request!") return } /* 5/6. Parse the data and use the data (happens in completion handler) */ completionHandlerForImage(data, nil) } /* 7. Start the request */ task.resume() return task } // MARK: Helpers // substitute the key for the value that is contained within the method name func substituteKeyInMethod(_ method: String, key: String, value: String) -> String? { if method.range(of: "{\(key)}") != nil { return method.replacingOccurrences(of: "{\(key)}", with: value) } else { return nil } } // given raw JSON, return a usable Foundation object private func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) { var parsedResult: AnyObject! = nil do { parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject } catch { let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"] completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo)) } completionHandlerForConvertData(parsedResult, nil) } // create a URL from parameters class func tmdbURLFromParameters(_ parameters: [String:AnyObject], withPathExtension: String? = nil) -> URL { var components = URLComponents() components.scheme = TMDBClient.Constants.ApiScheme components.host = TMDBClient.Constants.ApiHost components.path = TMDBClient.Constants.ApiPath + (withPathExtension ?? "") components.queryItems = [URLQueryItem]() for (key, value) in parameters { let queryItem = URLQueryItem(name: key, value: "\(value)") components.queryItems!.append(queryItem) } return components.url! } // MARK: Shared Instance class func sharedInstance() -> TMDBClient { struct Singleton { static var sharedInstance = TMDBClient() } return Singleton.sharedInstance } }
34.639706
208
0.594566
5629bd392e6769a766b92b07fea9d47d80df8f07
1,833
// // Usuario+CoreDataProperties.swift // roadtrip // // Created by Alejo Martín Arias Filippo on 21/01/2021. // Copyright © 2021 ual. All rights reserved. // // import Foundation import CoreData extension Usuario { @nonobjc public class func fetchRequest() -> NSFetchRequest<Usuario> { return NSFetchRequest<Usuario>(entityName: "Usuario") } @NSManaged public var contrasena: String? @NSManaged public var correo: String? @NSManaged public var nombre: String? @NSManaged public var ejex: Float @NSManaged public var ejey: Float @NSManaged public var registros: NSOrderedSet? } // MARK: Generated accessors for registros extension Usuario { @objc(insertObject:inRegistrosAtIndex:) @NSManaged public func insertIntoRegistros(_ value: Registro, at idx: Int) @objc(removeObjectFromRegistrosAtIndex:) @NSManaged public func removeFromRegistros(at idx: Int) @objc(insertRegistros:atIndexes:) @NSManaged public func insertIntoRegistros(_ values: [Registro], at indexes: NSIndexSet) @objc(removeRegistrosAtIndexes:) @NSManaged public func removeFromRegistros(at indexes: NSIndexSet) @objc(replaceObjectInRegistrosAtIndex:withObject:) @NSManaged public func replaceRegistros(at idx: Int, with value: Registro) @objc(replaceRegistrosAtIndexes:withRegistros:) @NSManaged public func replaceRegistros(at indexes: NSIndexSet, with values: [Registro]) @objc(addRegistrosObject:) @NSManaged public func addToRegistros(_ value: Registro) @objc(removeRegistrosObject:) @NSManaged public func removeFromRegistros(_ value: Registro) @objc(addRegistros:) @NSManaged public func addToRegistros(_ values: NSOrderedSet) @objc(removeRegistros:) @NSManaged public func removeFromRegistros(_ values: NSOrderedSet) }
29.095238
92
0.744681
3ac73193d7a455e376e4cd275be0bebbd35cd5c1
3,609
// // View+Position.swift // Proton // // Created by McDowell, Ian J [ITACD] on 4/5/16. // Copyright © 2016 Ian McDowell. All rights reserved. // public extension View { public func position(top top: Percent? = nil, bottom: Percent? = nil, left: Percent? = nil, right: Percent? = nil) -> Self { self.position.type = .Percent if top != nil { self.position.top = top?.value } if bottom != nil { self.position.bottom = bottom?.value } if left != nil { self.position.left = left?.value } if right != nil { self.position.right = right?.value } return self } public func position(top top: CGFloat? = nil, bottom: CGFloat? = nil, left: CGFloat? = nil, right: CGFloat? = nil) -> Self { self.position.type = .Absolute if top != nil { self.position.top = top } if bottom != nil { self.position.bottom = bottom } if left != nil { self.position.left = left } if right != nil { self.position.right = right } return self } public func positionCenter() -> Self { positionCenterX() positionCenterY() return self } public func positionCenterX() -> Self { self.position.centerX() return self } public func positionCenterY() -> Self { self.position.centerY() return self } public func positionTopLeft(offset: CGFloat? = 0) -> Self { self.position.type = .Absolute self.position.top = offset self.position.left = offset return self } public func positionTopRight(offset: CGFloat? = 0) -> Self { self.position.type = .Absolute self.position.top = offset self.position.right = offset return self } public func positionBottomLeft(offset: CGFloat? = 0) -> Self { self.position.type = .Absolute self.position.bottom = offset self.position.left = offset return self } public func positionBottomRight(offset: CGFloat? = 0) -> Self { self.position.type = .Absolute self.position.bottom = offset self.position.right = offset return self } public func positionTopLeft(offset: Percent) -> Self { self.position.type = .Percent self.position.top = offset.value self.position.left = offset.value return self } public func positionTopRight(offset: Percent) -> Self { self.position.type = .Percent self.position.top = offset.value self.position.right = offset.value return self } public func positionBottomLeft(offset: Percent) -> Self { self.position.type = .Percent self.position.bottom = offset.value self.position.left = offset.value return self } public func positionBottomRight(offset: Percent) -> Self { self.position.type = .Percent self.position.bottom = offset.value self.position.right = offset.value return self } public func positionFill(offset: CGFloat? = 0) -> Self { self.position = LayoutPosition(type: .Absolute, top: offset, bottom: offset, left: offset, right: offset) return self } public func positionFill(offset: Percent) -> Self { self.position = LayoutPosition(type: .Percent, top: offset.value, bottom: offset.value, left: offset.value, right: offset.value) return self } }
31.112069
136
0.581324
efb0e3a67d8f84978185d7c67ac3746119101914
171
// // BaseSectionCell.swift // Pods // // Created by Vikas Goyal on 15/09/15. // // import Foundation public protocol BaseCellModel { func identifier()->String; }
13.153846
39
0.666667
bbd524c8e367354776883a72c000b9c1fa07ed80
1,463
// // Weather.swift // HeWeatherIO // // Created by iMac on 2018/5/30. // Copyright © 2018年 iMac. All rights reserved. // import Foundation public class Weather: HeWeatherBase { let current: CurrentForecast? let dailyForecast: [DailyForecast]? let hourly: [HourlyForecast]? let lifestyle: [Lifestyle]? required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Weather.CodingKeys.self) current = try container.decode(CurrentForecast.self, forKey: .current) dailyForecast = try container.decode([DailyForecast].self, forKey: .dailyForecast) hourly = try container.decode([HourlyForecast].self, forKey: .hourly) lifestyle = try container.decode([Lifestyle].self, forKey: .lifestyle) try super.init(from: decoder) } override public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Weather.CodingKeys.self) try container.encode(current, forKey: .current) try container.encode(dailyForecast, forKey: .dailyForecast) try container.encode(hourly, forKey: .hourly) try container.encode(lifestyle, forKey: .lifestyle) try super.encode(to: encoder) } private enum CodingKeys: String, CodingKey { case dailyForecast = "daily_forecast" case hourly = "hourly" case lifestyle = "lifestyle" case current = "now" } }
29.26
90
0.678059
f835dc441f73e8cd6a822489969edb8a82f29a2e
362
// // AnimationNavgator.swift // testdemo // // Created by 常仲伟 on 2022/3/6. // Copyright © 2022 常仲伟. All rights reserved. // import UIKit enum AnimationChapter: CaseIterable, ViewControllerMaker, Navigation { case animation var viewController: UIViewController { switch self { case .animation: return AnimationViewController() } } }
17.238095
70
0.698895
461c0a6c93fff4f48d54f85b9bb0b8ad8bfd6a84
7,797
// // File.swift // // // Created by Fu Lam Diep on 14.01.21. // import Foundation /// A dependency resolver class, that automtically finds the class that conforms /// a given protocol and creates an instance of it. /// /// If a property is declared with a protocol type, this class can be used to /// assign the initial value. /// /// Requirements: The protocol to be resolved must be visible to the Objective-C /// environment (`@objc`). To resolve such a protocol, there must be at least one /// class in the project that conforms to this protocol on the one hand, but also /// conforms to the protocol `Injectable` to be detected by the resolvers scan /// method. /// /// When trying to use the resolver method `one`, `many` or `optional`, the /// type specified by the generic parameter should be the same as the `Protocol` /// type passed to the method. E.g.: /// /// ``` /// var service: Service = Resolver.one(Service.self) /// var services: [Service] = Resolver.many(Service.self) /// var service: Service? = Resolver.optional(Service.self) /// ``` /// - Note: It is recommended to use the same protocol type for both, the generic /// type and the type passed to the method. Unfortunatley generic and meta types /// cannot be put into relation with type `Protocol`. But `Protocol` is needed to /// limit the type to pass to the methods and to check for protocol conformance. /// Hence the relation between the generic type and the type passed to the method /// cannot be checked at compile time. /// /// - TODO: Implement mechanism for singletons/cache and named instances public final class Resolver { // MARK: Properties /// Provides the set of active profiles. Injectable classes may specify the /// static property `profile` or `profiles` to indicate that these classes /// are available for resolution when at least one profile is contained in /// this set. public private(set) var profiles: Set<String> = Set() /// Provides the count of injectable types found by the scan method. public var count: Int { resolvableTypes.count } /// Provides the list of all types that conforms to the `Injectable` protocol. private let resolvableTypes: [Resolvable.Type] /// Provides a filtered list of injectable types according to the list of /// active profiles. private var activeResolvableTypes: [Resolvable.Type] = [] /// Indicates, whether the resolver needs an update or not. This may be true /// before the very first call of scan within an application lifecycle or /// after `setProfiles(_:)` has been called. private var needsUpdate: Bool = true /// Provides a dictionary of resolvable instances where key is the fully /// qualified class name of the instance itself. This dictionary is used to /// store resolvables that are marked as singleton. private var resolvablesByKey: [String: Resolvable] = [:] // MARK: Initialization /// Initalizes the resolver. private init () { resolvableTypes = class_getInjectables() } // MARK: Managing Profiles /// Sets the list of profiles to indicate which implementation to use when /// resolving classes. This will also invoke `scan()`. public func setProfiles (_ profiles: [String]) { self.profiles = Set(profiles) needsUpdate = true scan() } // MARK: Scanning for Injectables /// Scans the project for injectable classes according to the list of active /// profiles and stores them in a temporary list. This method needs to be /// called before using the resolver or after setting the profiles. @discardableResult public func scan (flushCache: Bool = false) -> Int { guard needsUpdate else { return resolvableTypes.count } activeResolvableTypes = resolvableTypes.filter({ if let profile = $0.profile { return profiles.contains(profile) || profile.isEmpty } if let profiles = $0.profiles { return profiles.contains { profile in self.profiles.contains(profile) || profile.isEmpty } } return true }) if flushCache { self.flushCache() } needsUpdate = false return resolvableTypes.count } /// Flushes the cache of singletons public func flushCache () { resolvablesByKey = [:] } // MARK: Resolving Candidates /// Returns the list of candidates for the given protocol to resolve. This is /// a common function used by resolver methods `one`, `many`, `some`, to /// have a unified filter method. internal func candidates (_ proto: Protocol) -> [Resolvable.Type] { if needsUpdate { fatalError("Fetching candidates failed: scan() needs to be " + "invoked before use or after calling setProfiles()") } return activeResolvableTypes.filter({ ChaosCore.class_conformsToProtocol($0, proto) }) } /// Attempts to resolve the given protocol to an instance. This method is used /// to require a type. The method fails with an `fatalError`, if either more /// than one or no candidate has been found. public func one<T> (_ proto: Protocol) -> T { guard let instance: T = optional(proto) else { fatalError("Resolving dependency failed: No candidate found.") } return instance } /// Returns a list of instances of each class conforming the given protocol. public func many<T> (_ proto: Protocol) -> [T] { return self.candidates(proto) .map({ guard let instance = build($0) as? T else { fatalError("Resolving dependency failed: unable to " + "downcast resolvable '\($0.self)' to type \(T.self)") } return instance }) } /// Attempts to resolve the given protocol to the implicit type T. This method /// fails with `fatalError()`, if either the type to resolve is ambigous or /// the given protocol is unrelated to the implicit type T. public func optional<T> (_ proto: Protocol) -> T? { let candidates = self.candidates(proto) // Ambigous type if candidates.count > 1 { fatalError("Resolving dependency failed: Candidate is ambigous " + "(\(candidates.count)).") } // No class found, but thats okay, since this is optional guard let first = candidates.first else { return nil } // Types are unrelated guard let instance = build(first) as? T else { fatalError("Resolving dependency failed: given protocol and type " + "'\(T.self)' are unrelated.") } return instance } /// Builds the according instance to the given class passed. If the type /// responds to `singleton` with true, the method tries to get the instance /// from cache and if it fails it creates a new instance at put it into cache. private func build (_ type: Resolvable.Type) -> Resolvable { guard type.singleton == true else { return type.init() } let key = NSStringFromClass(type) return resolvablesByKey.insertIfNotExists(type.init(), forKey: key) } } // MARK: - Static Properties public extension Resolver { static let main = Resolver() static func scan () -> Int { main.scan() } static func one<T> (_ proto: Protocol) -> T { main.one(proto) } static func many<T> (_ proto: Protocol) -> [T] { main.many(proto) } static func some<T> (_ proto: Protocol) -> T? { main.optional(proto) } }
36.778302
85
0.640246
bbf52b6d356de4e1a958fe4d9e7145646ff12c5a
853
// Atom // // Copyright (c) 2020 Alaska Airlines // // 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 public extension BaseURL { /// List of supported scheme types. enum Scheme { /// The hyper text transfer protocol. case http /// The hyper text transfer protocol secure. case https } }
29.413793
75
0.704572
39ac2f7f07c76c279c30cb89a23009de5dda70d3
5,041
/* * Copyright (c) 2011-2018, Zingaya, Inc. All rights reserved. */ import UIKit import UserNotifications import AVFoundation import Dispatch class UIHelper { fileprivate static var incomingCallAlert: UIAlertController? fileprivate static var player: AVAudioPlayer? class func ShowError(error: String!, action: UIAlertAction? = nil) { if let rootViewController = AppDelegate.instance().window?.rootViewController { let alert = UIAlertController(title: "Error", message: error, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) if let alertAction = action { alert.addAction(alertAction) } DispatchQueue.main.async { () -> Void in rootViewController.present(alert, animated: true, completion: nil) } } } class func ShowIncomingCallAlert(for uuid: UUID!, completion: @escaping ()-> Void) { if let rootViewController = AppDelegate.instance().window?.rootViewController, let callManager = AppDelegate.instance().voxImplant!.callManager, let descriptor = callManager.call(uuid: uuid) { var userName = ""; if let userDisplayName = descriptor.call!.endpoints.first!.userDisplayName { userName = " from \(userDisplayName)" } incomingCallAlert = UIAlertController(title: "Voximplant", message: String(format: "Incoming %@ call%@", descriptor.withVideo ? "video" : "audio", userName), preferredStyle: .alert) incomingCallAlert!.addAction(UIAlertAction(title: "Reject", style: .destructive) { action in completion() AppDelegate.instance().voxImplant!.rejectCall(call: descriptor, mode: .decline) }) incomingCallAlert!.addAction(UIAlertAction(title: descriptor.withVideo ? "Audio" : "Answer", style: .default) { action in completion() descriptor.withVideo = false AppDelegate.instance().voxImplant!.startCall(call: descriptor) }) if (descriptor.withVideo) { incomingCallAlert!.addAction(UIAlertAction(title: "Video", style: .default) { action in completion() AppDelegate.instance().voxImplant!.startCall(call: descriptor) }) } DispatchQueue.main.async { () -> Void in rootViewController.present(incomingCallAlert!, animated: true, completion: nil) } } } class func DismissIncomingCallAlert(completion: @escaping ()-> Void) { if let _ = incomingCallAlert, let rootViewController = AppDelegate.instance().window?.rootViewController { rootViewController.dismiss(animated: true) { completion() } incomingCallAlert = nil } } class func ShowCallScreen() { if let rootViewController = AppDelegate.instance().window?.rootViewController { rootViewController.performSegue(withIdentifier: "CallController", sender: nil) } } } //MARK: - Playing call ringtone extension UIHelper { /** `StartPlayingRingtone` creates `AVAudioPlayer` for playing a custom ringtone when the app is in the foreground. To stop playing ringtone when the app is in the foreground you should use `StopPlayingRingtone` For playing a custom ringtone when the app is in the background you should use `UNMutableNotificationContent()`: ``` ... let content = UNMutableNotificationContent() ... content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "ringtone.aiff")) ... ``` */ class func StartPlayingRingtone() { do { player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: String(format: "%@/ringtone.aiff", Bundle.main.resourcePath!))) player?.numberOfLoops = -1 let audioSession = AVAudioSession.sharedInstance() if #available(iOS 10.0, *) { try audioSession.setCategory(AVAudioSession.Category.ambient, mode: .default) } else { // Workaround until https://forums.swift.org/t/using-methods-marked-unavailable-in-swift-4-2/14949 is fixed audioSession.perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.ambient) } try audioSession.setActive(true) player?.prepareToPlay() player?.play() } catch { Log.e("\(error.localizedDescription)") } } /** Opposite to `StartPlayingRingtone` */ class func StopPlayingRingtone() { guard let player = player else { return } player.stop() do { try AVAudioSession.sharedInstance().setActive(false) } catch { Log.e("\(error.localizedDescription)") } } }
37.619403
200
0.617139
50981038042ceee757472a3c271ae0aaf4924575
45,793
import Foundation let input = [ "bkwzkqsxq-tovvilokx-nozvyiwoxd-172[fstek]", "wifilzof-wbiwifuny-yhachyylcha-526[qrazx]", "jvyyvzpcl-jhukf-shivyhavyf-487[zhtsi]", "kwvacumz-ozilm-kivlg-kwvbiqvumvb-694[gknyw]", "mvhkvbdib-kmjezxodgz-mvwwdo-omvdidib-837[dmvbi]", "nzydfxpc-rclop-qwzhpc-lnbftdtetzy-171[cptzd]", "vhehkyne-unggr-inkvatlbgz-813[gnehk]", "tcorcikpi-hnqygt-octmgvkpi-570[nzewo]", "xmtjbzidx-wvnfzo-jkzmvodjin-447[uyzlp]", "willimcpy-mwupyhayl-bohn-mufym-734[stjoc]", "sbejpbdujwf-cvooz-xpsltipq-961[azfnd]", "jchipqat-qphzti-rjhidbtg-htgkxrt-271[thigj]", "npmhcargjc-zsllw-pcqcypaf-158[mzwnx]", "luxciuwncpy-jfumncw-alumm-qilembij-318[mucil]", "bxaxipgn-vgpst-rpcsn-rdpixcv-htgkxrth-427[ywazt]", "zekvierkzferc-tyftfcrkv-ivtvzmzex-295[evzfk]", "enzcntvat-qlr-hfre-grfgvat-143[rtaef]", "mvkccspson-bkllsd-nofovyzwoxd-224[oscdk]", "enzcntvat-zvyvgnel-tenqr-pnaql-pbngvat-ratvarrevat-429[zymbs]", "nwzekwypera-xwogap-pnwejejc-992[lkiwn]", "ajmrxjlcren-ajkkrc-lxwcjrwvnwc-667[ezynd]", "bxaxipgn-vgpst-hrpktcvtg-wjci-advxhixrh-661[lytku]", "owshgfarwv-vqw-kzahhafy-190[ahwfv]", "jqwpihizlwca-moo-twoqabqka-512[ncdyv]", "apwmeclga-pyzzgr-rcaflmjmew-886[amceg]", "tyepcyletzylw-ojp-wzrtdetnd-951[mxqsy]", "dlhwvupglk-kfl-hjxbpzpapvu-773[nrotd]", "fab-eqodqf-dmnnuf-bgdotmeuzs-612[dchyk]", "qjopwxha-bhksan-skngodkl-940[kahno]", "lsyrkjkbnyec-dyz-combod-cmkfoxqob-rexd-bomosfsxq-718[lktzs]", "zixppfcfba-bdd-jxohbqfkd-939[sqtor]", "vxupkizork-kmm-ktmotkkxotm-852[dsqjh]", "excdklvo-mkxni-mykdsxq-nozkbdwoxd-952[zspmc]", "bnqqnrhud-eknvdq-sqzhmhmf-391[qhndm]", "gzefmnxq-otaoaxmfq-ogefayqd-eqdhuoq-716[zinwb]", "qzoggwtwsr-qobrm-ghcfous-428[goqrs]", "gpbepvxcv-ltpedcxots-qphzti-steadnbtci-193[ignjy]", "hvbizodx-nxvqzibzm-cpio-hvmfzodib-265[hixfe]", "wkqxodsm-lexxi-kxkvicsc-926[xkcis]", "bknsykmdsfo-myxcewob-qbkno-oqq-zebmrkcsxq-380[utqrz]", "lejkrscv-wcfnvi-kirzezex-711[ecikr]", "htwwtxnaj-idj-btwpxmtu-255[itgmd]", "zsxyfgqj-jll-ijufwyrjsy-931[wrpgt]", "iuxxuyobk-yigbktmkx-natz-gtgreyoy-384[ygktx]", "qjopwxha-xqjju-zalhkuiajp-628[esmxk]", "lxaaxbren-ljwmh-anbnjalq-745[stjqy]", "gokzyxsjon-zvkcdsm-qbkcc-dbksxsxq-380[tsyqk]", "qzoggwtwsr-qobrm-qcohwbu-rsdofhasbh-168[obhqr]", "pelbtravp-pnaql-fgbentr-325[pabel]", "xzwrmkbqtm-akidmvomz-pcvb-mvoqvmmzqvo-122[mvoqz]", "sbnqbhjoh-ezf-fohjoffsjoh-233[xskyb]", "jyddc-yrwxefpi-fewoix-hiwmkr-412[pdekg]", "fab-eqodqf-rxaiqd-xmnadmfadk-690[sicjl]", "xcitgcpixdcpa-rpcsn-htgkxrth-427[stznv]", "rflsjynh-rnqnyfwd-lwfij-jll-xytwflj-229[lfjnw]", "zotts-wlsiayhcw-vumeyn-fuvilunils-500[ilsun]", "odiih-yujbcrl-pajbb-dbna-cnbcrwp-147[bcadi]", "udskkaxawv-tmffq-klgjsyw-996[tmnfc]", "emixwvqhml-kpwkwtibm-wxmzibqwva-278[zomvn]", "dfcxsqhwzs-dzoghwq-ufogg-zcuwghwqg-116[kmijn]", "dwbcjkun-ouxfna-mnbrpw-745[nbuwa]", "jchipqat-rwdrdapit-pcpanhxh-973[hglvu]", "fkqbokxqflkxi-avb-zlkqxfkjbkq-861[wdnor]", "wbhsfbohwcboz-foppwh-qighcasf-gsfjwqs-480[fhswb]", "dzczkrip-xiruv-szfyrqriuflj-treup-kvtyefcfxp-451[rfipu]", "fmsledevhsyw-fyrrc-eguymwmxmsr-698[yzoxu]", "udskkaxawv-jsttal-wfyafwwjafy-840[nlkda]", "sno-rdbqds-idkkxadzm-sqzhmhmf-287[lngzc]", "crwwv-yxphbq-rpbo-qbpqfkd-341[bpqrw]", "odiih-mhn-anjlzdrbrcrxw-563[xadcy]", "jyddc-ikk-wlmttmrk-698[lmstk]", "buzahisl-wshzapj-nyhzz-klzpnu-149[pjxor]", "odkasqzuo-eomhqzsqd-tgzf-ymzmsqyqzf-560[frqmp]", "gokzyxsjon-bkllsd-yzobkdsyxc-874[nbtmv]", "excdklvo-pvygob-bocokbmr-952[tyzxa]", "jvsvymbs-jovjvshal-aljouvsvnf-253[zgtdm]", "hafgnoyr-qlr-erfrnepu-637[refna]", "pelbtravp-sybjre-fnyrf-299[tjoim]", "fodvvlilhg-gbh-vwrudjh-621[hvdgl]", "kgjgrypw-epybc-bwc-bcnjmwkclr-678[smijy]", "myxcewob-qbkno-mrymyvkdo-dbksxsxq-458[bkmox]", "joufsobujpobm-fhh-dpoubjonfou-311[uvksy]", "rflsjynh-ojqqdgjfs-ijajqturjsy-697[jqsfr]", "vetllbybxw-vtgwr-kxtvjnblbmbhg-709[athym]", "ajvyjprwp-ajmrxjlcren-kdwwh-lxwcjrwvnwc-433[qsaxt]", "zbytomdsvo-mkxni-mykdsxq-myxdksxwoxd-952[xdmko]", "esyfwlau-bwddqtwsf-suimakalagf-684[stvip]", "jef-iushuj-fhezusjybu-fbqijys-whqii-huiuqhsx-582[uhijs]", "tpspahyf-nyhkl-jovjvshal-bzly-alzapun-565[sdprn]", "apwmeclga-hcjjwzcyl-umpiqfmn-132[shfrg]", "kwtwznct-jcvvg-lmxizbumvb-148[vbcmt]", "rmn-qcapcr-aylbw-umpiqfmn-366[juftv]", "sorozgxe-mxgjk-hgyqkz-yzuxgmk-748[xuvst]", "bkwzkqsxq-wsvsdkbi-qbkno-mkxni-mykdsxq-yzobkdsyxc-822[ksbqx]", "ryexqpqhteki-vbemuh-skijecuh-iuhlysu-842[tszmj]", "ikhcxvmbex-wrx-wxlbzg-501[zhqis]", "lsyrkjkbnyec-mrymyvkdo-nozvyiwoxd-978[enkfi]", "wdjcvuvmyjpn-mvhkvbdib-agjrzm-nojmvbz-395[tcxne]", "uwtojhynqj-gfxpjy-fhvznxnynts-567[kqpvs]", "iqmbazulqp-pkq-dqoquhuzs-534[ntpuq]", "gntmfefwitzx-ojqqdgjfs-ijajqturjsy-385[jfqtg]", "sebehvkb-fhezusjybu-zubboruqd-husuylydw-972[ytsim]", "nzcczdtgp-nsznzwlep-hzcvdsza-405[yotgu]", "joufsobujpobm-fhh-ufdiopmphz-675[tsymn]", "cxy-bnlanc-snuuhknjw-anbnjalq-823[nabcj]", "shoewudys-rkddo-huiuqhsx-374[dhsuo]", "vagreangvbany-rtt-jbexfubc-403[ynepo]", "aoubshwq-dzoghwq-ufogg-aobousasbh-714[oabgh]", "njmjubsz-hsbef-dipdpmbuf-qvsdibtjoh-805[bdjsf]", "zovldbkfz-gbiivybxk-lmboxqflkp-653[nyajo]", "yknnkoera-xwogap-hkceopeyo-628[ybmzc]", "nij-mywlyn-wbiwifuny-guleyncha-396[nyiwl]", "ocipgvke-ecpfa-eqcvkpi-vgejpqnqia-258[jsiqz]", "encuukhkgf-hnqygt-vgejpqnqia-882[dxzer]", "odiih-ljwmh-anbnjalq-927[ahijl]", "fkqbokxqflkxi-zxkav-ixyloxqlov-861[nxgja]", "udskkaxawv-xmrrq-uzgugdslw-sfsdqkak-216[msfyx]", "owshgfarwv-bwddqtwsf-kzahhafy-216[wafhd]", "oaxadrgx-dmnnuf-ruzmzouzs-794[uqhse]", "ziuxioqvo-akidmvomz-pcvb-zmikycqaqbqwv-616[iqvmo]", "bqvvu-xqjju-opknwca-550[yzhum]", "xgjougizobk-lruckx-gtgreyoy-670[nbfmk]", "bxaxipgn-vgpst-uadltg-bpgztixcv-323[gptxa]", "vcibutulxiom-jfumncw-alumm-nluchcha-448[ucmla]", "irgyyolokj-xghhoz-uvkxgzouty-930[ogyhk]", "kyelcrga-aylbw-amyrgle-umpiqfmn-782[almye]", "jsvagsulanw-xdgowj-kzahhafy-138[dblcm]", "ixccb-fkrfrodwh-uhdftxlvlwlrq-881[mblzw]", "chnylhuncihuf-mwupyhayl-bohn-guleyncha-422[hnuyc]", "irdgrxzex-treup-tfrkzex-uvgrikdvek-165[sjbnk]", "xzwrmkbqtm-akidmvomz-pcvb-zmikycqaqbqwv-434[sanut]", "ykhknbqh-zua-iwjwcaiajp-524[kjlio]", "jlidywncfy-mwupyhayl-bohn-uwkocmcncih-916[cyhnw]", "nuatmlmdpage-omzpk-eqdhuoqe-326[ljtsm]", "xmrrq-kusnwfywj-zmfl-suimakalagf-684[afmkl]", "foadouwbu-qvcqczohs-rsgwub-116[oubcq]", "etyyx-bgnbnkzsd-kzanqzsnqx-391[pnmlv]", "pinovwgz-wvnfzo-hvmfzodib-291[ovzfi]", "qekrixmg-gsrwyqiv-kvehi-fewoix-ywiv-xiwxmrk-828[iwxek]", "jqwpihizlwca-xtiabqk-oziaa-kcabwumz-amzdqkm-928[aizkm]", "qekrixmg-jpsaiv-stivexmsrw-672[etmsq]", "excdklvo-gokzyxsjon-mrymyvkdo-bomosfsxq-562[okmsx]", "qczcftiz-pibbm-aobousasbh-532[zynvo]", "wbhsfbohwcboz-suu-gsfjwqsg-506[bdhxv]", "lxwbdvna-pajmn-ajkkrc-anlnrerwp-563[anrjk]", "lsyrkjkbnyec-pvygob-cobfsmoc-900[uyrgf]", "cqwdujys-sxesebqju-ixyffydw-374[nyjvi]", "odiih-ouxfna-anlnrerwp-433[naior]", "rzvkjiduzy-xviyt-xjvodib-vxlpdndodji-993[aousd]", "ltpedcxots-qphzti-rjhidbtg-htgkxrt-453[rjlkn]", "krxqjijamxdb-kdwwh-fxatbqxy-823[wctav]", "froruixo-edvnhw-vwrudjh-829[rdhou]", "jvyyvzpcl-jhukf-aljouvsvnf-201[uwkic]", "nij-mywlyn-vumeyn-zchuhwcha-266[hnycm]", "ydjuhdqjyedqb-zubboruqd-tufbeocudj-244[vmkln]", "qlm-pbzobq-mixpqfz-doxpp-mrozexpfkd-575[zswni]", "qvbmzvibqwvit-moo-tijwzibwzg-330[ibvwz]", "pbeebfvir-fpniratre-uhag-freivprf-949[gvxlm]", "wfummczcyx-jfumncw-alumm-uwkocmcncih-890[vturj]", "dwbcjkun-npp-cajrwrwp-355[kstqo]", "dpssptjwf-cbtlfu-vtfs-uftujoh-441[ftsuj]", "vrurcjah-pajmn-npp-anbnjalq-303[tozvd]", "wfruflnsl-ojqqdgjfs-xfqjx-775[fjqls]", "pbafhzre-tenqr-qlr-qrirybczrag-897[yszub]", "sehheiylu-rkddo-udwyduuhydw-322[qbyad]", "upq-tfdsfu-cbtlfu-nbobhfnfou-103[vpxyh]", "ajvyjprwp-npp-dbna-cnbcrwp-901[stevo]", "bkzrrhehdc-bzmcx-bnzshmf-qdrdzqbg-833[msuya]", "amlqskcp-epybc-aylbw-rcaflmjmew-730[arbyn]", "wbhsfbohwcboz-dzoghwq-ufogg-gozsg-272[gobhw]", "ksodcbwnsr-dfcxsqhwzs-gqojsbusf-vibh-obozmgwg-194[rwimn]", "mfklstdw-usfvq-hmjuzskafy-424[ulgym]", "wfruflnsl-ojqqdgjfs-qfgtwfytwd-177[xbofz]", "sedikcuh-whqtu-isqludwuh-xkdj-jhqydydw-218[dhuqw]", "ltpedcxots-raphhxuxts-qphzti-advxhixrh-765[jahpi]", "zgmfyxypbmsq-djmucp-rcaflmjmew-548[aeoiv]", "qspkfdujmf-ezf-nbobhfnfou-207[lnkrt]", "fbebmtkr-zktwx-pxtihgbsxw-ietlmbv-zktll-kxlxtkva-943[hajmb]", "apwmeclga-hcjjwzcyl-bctcjmnkclr-548[yxnzl]", "rflsjynh-kqtbjw-btwpxmtu-177[tbjwf]", "kfg-jvtivk-treup-uvgcfpdvek-373[vkefg]", "upq-tfdsfu-kfmmzcfbo-nbobhfnfou-285[vsglz]", "chnylhuncihuf-mwupyhayl-bohn-xypyfijgyhn-266[pwahm]", "apwmeclga-zyqicr-dglylagle-886[lagce]", "jlidywncfy-xsy-qilembij-188[uxjts]", "jqwpihizlwca-lgm-lmaqov-954[laimq]", "qcffcgwjs-foppwh-gozsg-246[fgcop]", "bqxnfdmhb-rbzudmfdq-gtms-cdrhfm-287[dmbfh]", "gifavtkzcv-wcfnvi-rthlzjzkzfe-763[tmniq]", "uqtqbizg-ozilm-kivlg-kwibqvo-tijwzibwzg-720[qndzg]", "sxdobxkdsyxkv-mkxni-bomosfsxq-848[zyubw]", "qfmcusbwq-foppwh-kcfygvcd-662[cfpqw]", "sehheiylu-fbqijys-whqii-skijecuh-iuhlysu-660[kdjyq]", "sedikcuh-whqtu-uww-bqrehqjeho-660[dtawl]", "veqtekmrk-wgezirkiv-lyrx-eguymwmxmsr-464[emrkg]", "lqwhuqdwlrqdo-exqqb-uhdftxlvlwlrq-231[ydznk]", "sno-rdbqds-bzmcx-otqbgzrhmf-183[gomah]", "ujqgywfau-jsttal-hmjuzskafy-476[lghae]", "yrwxefpi-jpsaiv-gsrxemrqirx-100[yazxo]", "udglrdfwlyh-exqqb-sxufkdvlqj-569[dlqfu]", "ugjjgkanw-uzgugdslw-esjcwlafy-736[rnxjs]", "pdjqhwlf-sodvwlf-judvv-orjlvwlfv-673[vldfj]", "xekdwvwnzkqo-fahhuxawj-ajcejaanejc-524[ajewc]", "pwcvonofrcig-pibbm-fsqswjwbu-766[myazu]", "tcrjjzwzvu-wcfnvi-glityrjzex-893[bkuyx]", "lugjuacha-wbiwifuny-omyl-nymncha-448[mosph]", "ckgvutofkj-inuiurgzk-jkvgxzsktz-228[kguzi]", "ydjuhdqjyedqb-sqdto-ijehqwu-868[ozqsj]", "sxdobxkdsyxkv-zvkcdsm-qbkcc-myxdksxwoxd-640[xdksc]", "odkasqzuo-dmnnuf-dqmocgueufuaz-482[wfbke]", "wpuvcdng-tcddkv-wugt-vguvkpi-414[hayjs]", "lqwhuqdwlrqdo-edvnhw-uhfhlylqj-439[bjzye]", "wpuvcdng-dwppa-ceswkukvkqp-674[mxnkj]", "qzlozfhmf-bkzrrhehdc-okzrshb-fqzrr-zbpthrhshnm-365[hrzbf]", "raphhxuxts-rpcsn-rdpixcv-rjhidbtg-htgkxrt-635[yozvr]", "tfejldvi-xiruv-gcrjkzt-xirjj-tljkfdvi-jvimztv-321[veyxs]", "ryexqpqhteki-sxesebqju-iqbui-868[qebar]", "eqpuwogt-itcfg-hnqygt-tgegkxkpi-648[ywzjl]", "uzfqdzmfuazmx-pkq-bgdotmeuzs-482[zmudf]", "sbnqbhjoh-cbtlfu-bdrvjtjujpo-441[taquv]", "gokzyxsjon-bkwzkqsxq-lexxi-bomosfsxq-354[xoskq]", "oazegyqd-sdmpq-iqmbazulqp-dmnnuf-geqd-fqefuzs-456[qdefm]", "dwbcjkun-ljwmh-lxjcrwp-anbnjalq-875[hoynm]", "udskkaxawv-eadalsjq-yjsvw-xdgowj-klgjsyw-216[cnwyi]", "surmhfwloh-exqqb-sxufkdvlqj-439[tspmq]", "ksodcbwnsr-foppwh-zcuwghwqg-402[vopuk]", "zsxyfgqj-hmthtqfyj-fhvznxnynts-697[fhnty]", "yflexwxoalrp-yxphbq-bkdfkbbofkd-653[jzvpm]", "ltpedcxots-tvv-rdcipxcbtci-557[ctdip]", "slqryzjc-djmucp-qyjcq-756[cjqyd]", "rgndvtcxr-qphzti-bpcpvtbtci-817[tcpbi]", "ftzgxmbv-fbebmtkr-zktwx-vtgwr-vhtmbgz-lmhktzx-371[wzxvl]", "htqtwkzq-hfsid-yjhmstqtld-463[rxszy]", "rwcnawjcrxwju-yujbcrl-pajbb-mnenuxyvnwc-979[gkutb]", "gokzyxsjon-tovvilokx-kmaescsdsyx-562[dwlah]", "iutyaskx-mxgjk-lruckx-iayzuskx-ykxboik-826[kxiuy]", "vhglnfxk-zktwx-yehpxk-hixktmbhgl-891[diznt]", "sedikcuh-whqtu-kdijqrbu-sqdto-seqjydw-iuhlysui-790[lksjh]", "jyfvnlupj-zjhclunly-obua-vwlyhapvuz-617[pirsw]", "iuruxlar-sgmtkzoi-hgyqkz-zkinturume-670[qatsn]", "wkqxodsm-mrymyvkdo-mecdywob-cobfsmo-250[hgarm]", "odiih-kjbtnc-nwprwnnarwp-381[qpodn]", "kfg-jvtivk-tyftfcrkv-kirzezex-373[srcvd]", "gcfcnuls-aluxy-zotts-wuhxs-omyl-nymncha-552[clnsu]", "xmtjbzidx-zbb-xpnojhzm-nzmqdxz-421[mnkio]", "qjopwxha-acc-iwngapejc-160[jimst]", "emixwvqhml-kivlg-kwibqvo-aitma-564[qspyb]", "nvrgfezqvu-avccpsvre-cfxzjkztj-529[lmnsh]", "emixwvqhml-ktiaaqnqml-xtiabqk-oziaa-ikycqaqbqwv-746[ozadu]", "zhdsrqlchg-hjj-orjlvwlfv-751[hjlrv]", "cybyjqho-whqtu-uww-qsgkyiyjyed-478[szxuo]", "clxalrtyr-nsznzwlep-wzrtdetnd-405[lnrtz]", "sgmtkzoi-yigbktmkx-natz-rghuxgzuxe-722[gktxz]", "hjgbwuladw-tskcwl-sfsdqkak-502[txdsw]", "yrwxefpi-hci-vigimzmrk-646[hdmzy]", "hqcfqwydw-hqrryj-jusxdebewo-946[qwdeh]", "wsvsdkbi-qbkno-cmkfoxqob-rexd-yzobkdsyxc-276[wptxs]", "qfmcusbwq-qvcqczohs-zcuwghwqg-870[mnybx]", "clxalrtyr-nsznzwlep-cpdplcns-743[rtycz]", "fbebmtkr-zktwx-ktuubm-ybgtgvbgz-553[osmdy]", "jvuzbtly-nyhkl-yhtwhnpun-jovjvshal-ylzlhyjo-773[hlyjn]", "slqryzjc-aylbw-pcacgtgle-782[nxkri]", "tfcfiwlc-wcfnvi-wzeretzex-971[smobe]", "jef-iushuj-uww-qsgkyiyjyed-556[xzrwq]", "crwwv-yxphbq-xkxivpfp-653[pxvwb]", "hqcfqwydw-zubboruqd-husuylydw-244[lqeho]", "oxmeeuruqp-qss-eqdhuoqe-534[equos]", "qxdwpopgsdjh-rgndvtcxr-gpqqxi-gthtpgrw-687[gpdqr]", "mybbycsfo-mrymyvkdo-bocokbmr-692[pymza]", "myvybpev-oqq-yzobkdsyxc-250[sxytw]", "fnjyxwrinm-kdwwh-uxprbcrlb-329[natqu]", "aietsrmdih-nippcfier-gsrxemrqirx-958[iremp]", "xmrrq-tmffq-vwhdgqewfl-138[fqmrw]", "oqnidbshkd-bzmcx-sdbgmnknfx-599[nzdyx]", "eqttqukxg-ecpfa-eqcvkpi-ewuvqogt-ugtxkeg-128[mytkp]", "nchhg-ntwemz-amzdqkma-252[kmbop]", "bjfutsneji-jll-zxjw-yjxynsl-775[ndbsw]", "ktwbhtvmbox-lvtoxgzxk-angm-mxvaghehzr-319[ijqxb]", "kyelcrga-afmamjyrc-pcqcypaf-210[acyfm]", "myxcewob-qbkno-mkxni-oxqsxoobsxq-484[oxbqk]", "esyfwlau-vqw-kzahhafy-788[jikae]", "oqnidbshkd-eknvdq-btrsnldq-rdquhbd-391[njzml]", "qjopwxha-bhksan-opknwca-888[ahkno]", "udskkaxawv-jsttal-vwhdgqewfl-190[hqmnt]", "excdklvo-lexxi-crszzsxq-458[uavnl]", "frqvxphu-judgh-fdqgb-frdwlqj-wudlqlqj-179[bimaq]", "iuruxlar-kmm-ykxboiky-852[tijpz]", "tyepcyletzylw-mldvpe-lylwjdtd-509[lydet]", "frqvxphu-judgh-gbh-whfkqrorjb-101[mhbes]", "xqvwdeoh-edvnhw-zrunvkrs-699[zmudw]", "irdgrxzex-treup-fgvirkzfej-893[fbsyn]", "cxy-bnlanc-ljwmh-orwjwlrwp-771[ngpmz]", "eqpuwogt-itcfg-gii-ucngu-388[hzgae]", "ikhcxvmbex-cxeeruxtg-wxlbzg-553[mvnfs]", "mrxivrexmsrep-fyrrc-asvowlst-854[codsq]", "npmhcargjc-aylbw-qcptgacq-366[ditsg]", "ftzgxmbv-ietlmbv-zktll-phkdlahi-241[ltbhi]", "hqcfqwydw-tou-bewyijysi-270[hnvux]", "emixwvqhml-kivlg-abwziom-590[imlvw]", "pejji-nio-mecdywob-cobfsmo-926[wrjmp]", "bknsykmdsfo-oqq-dbksxsxq-640[naysz]", "gifavtkzcv-vxx-tfekrzedvek-789[cnwtp]", "kmjezxodgz-diozmivodjivg-agjrzm-xjiovdihzio-915[yqktj]", "shoewudys-vbemuh-qsgkyiyjyed-946[nqsjd]", "htqtwkzq-ojqqdgjfs-rfwpjynsl-749[hryqo]", "rmn-qcapcr-zyqicr-pcacgtgle-340[znstw]", "bnqqnrhud-bzmcx-bnmszhmldms-729[yfetv]", "surmhfwloh-gbh-rshudwlrqv-725[dsaym]", "jchipqat-tvv-itrwcdadvn-505[povhu]", "zgmfyxypbmsq-njyqrga-epyqq-rcaflmjmew-340[mqyae]", "froruixo-exqqb-pdunhwlqj-283[nmuqd]", "lnkfaypeha-xwogap-odellejc-784[ytrsz]", "jlidywncfy-xsy-fuvilunils-864[ilyfn]", "joufsobujpobm-dipdpmbuf-sftfbsdi-545[rwjnm]", "tvsnigxmpi-gerhc-gsexmrk-eguymwmxmsr-932[pivem]", "tfejldvi-xiruv-srjbvk-ivjvrity-815[vijrt]", "zuv-ykixkz-yigbktmkx-natz-zkinturume-410[kzitu]", "enzcntvat-pubpbyngr-qrcyblzrag-117[oywbs]", "wsvsdkbi-qbkno-lkcuod-nofovyzwoxd-744[xnuqc]", "wbhsfbohwcboz-foppwh-aobousasbh-246[nfsml]", "uiovmbqk-jcvvg-abwziom-720[nbqaz]", "etaqigpke-fag-fgrnqaogpv-674[gaefp]", "ejpanjwpekjwh-nwxxep-hkceopeyo-238[bmscu]", "qjopwxha-bhksan-wjwhuoeo-940[xenwh]", "etyyx-bzmcx-bnzshmf-qdzbpthrhshnm-729[hbmzn]", "uqtqbizg-ozilm-lgm-abwziom-356[tspmz]", "excdklvo-mybbycsfo-tovvilokx-psxkxmsxq-874[axwon]", "mvydjvxodqz-xviyt-xjvodib-pnzm-oznodib-187[nflym]", "ixccb-zhdsrqlchg-edvnhw-xvhu-whvwlqj-465[hcvwd]", "qspkfdujmf-votubcmf-tdbwfohfs-ivou-bdrvjtjujpo-181[esuzg]", "fkqbokxqflkxi-qlm-pbzobq-bdd-jxohbqfkd-601[dcgym]", "mtzslklcozfd-prr-nfdezxpc-dpcgtnp-301[tmnrk]", "xekdwvwnzkqo-lhwopey-cnwoo-wymqeoepekj-290[rzsnk]", "fubrjhqlf-sodvwlf-judvv-pdqdjhphqw-725[dfhjq]", "shoewudys-zubboruqd-skijecuh-iuhlysu-608[ushbd]", "zlkprjbo-doxab-zxkav-rpbo-qbpqfkd-679[bkopa]", "nzcczdtgp-mldvpe-opawzjxpye-587[tkbms]", "apuut-nxvqzibzm-cpio-yzkvmohzio-655[rsozd]", "rgllk-ngzzk-ymdwqfuzs-300[yhzxu]", "cvabijtm-jcvvg-uiviomumvb-538[ixajz]", "oazegyqd-sdmpq-otaoaxmfq-pqbmdfyqzf-248[qadfm]", "rtqlgevkng-fag-nqikuvkeu-960[nqdom]", "bnknqetk-cxd-cdrhfm-183[mfpwa]", "ohmnuvfy-wuhxs-wiuncha-lyuwkocmcncih-552[chunw]", "hqtyeqsjylu-jef-iushuj-tou-fkhsxqiydw-296[isfmy]", "kwtwznct-kwvacumz-ozilm-jiasmb-uiviomumvb-746[qmjyz]", "qfmcusbwq-foppwh-twbobqwbu-298[bwqfo]", "ykhknbqh-xqjju-owhao-472[hjtck]", "dszphfojd-tdbwfohfs-ivou-mbcpsbupsz-103[sbdfo]", "lahxpnwrl-ljwmh-nwprwnnarwp-641[srtpm]", "ckgvutofkj-lruckx-jkvruesktz-878[zjlyk]", "dyz-combod-zvkcdsm-qbkcc-nocsqx-926[yvute]", "ktwbhtvmbox-wrx-nlxk-mxlmbgz-345[lsuwt]", "nwilwcejc-nwxxep-zalhkuiajp-186[bznxr]", "uzfqdzmfuazmx-otaoaxmfq-bgdotmeuzs-846[mzafo]", "oxmeeuruqp-omzpk-oamfuzs-oazfmuzyqzf-352[ypdzg]", "zhdsrqlchg-fdqgb-ghsduwphqw-361[hdgqs]", "nchhg-jiasmb-amzdqkma-278[qklti]", "tfiifjzmv-upv-wzeretzex-295[itvos]", "eqttqukxg-ecpfa-ujkrrkpi-830[kepqr]", "clotzlnetgp-mldvpe-nzyeltyxpye-145[xfpsy]", "mbiyqoxsm-myvybpev-mkxni-mykdsxq-yzobkdsyxc-900[ymxbk]", "plolwdub-judgh-vfdyhqjhu-kxqw-vhuylfhv-621[zqwmy]", "atyzghrk-vxupkizork-jek-giwaoyozout-228[abrmv]", "zotts-xsy-mufym-162[mstyf]", "vhehkyne-ktuubm-mktbgbgz-293[qmytr]", "kwvacumz-ozilm-zijjqb-ivitgaqa-616[fkoxt]", "yaxsnlcrun-ajvyjprwp-snuuhknjw-anlnrerwp-771[zpyld]", "raphhxuxts-bpvctixr-eaphixr-vgphh-bpcpvtbtci-115[phtxb]", "nuatmlmdpage-odkasqzuo-qss-dqmocgueufuaz-768[umnqw]", "yknnkoera-lhwopey-cnwoo-nawymqeoepekj-680[eonkw]", "pybgmyargtc-aylbw-qyjcq-886[buzfp]", "gzefmnxq-ngzzk-iadwetab-638[zaegn]", "sbnqbhjoh-kfmmzcfbo-usbjojoh-129[acdkb]", "lxaaxbren-lujbbrornm-ljwmh-lxjcrwp-mnyjacvnwc-355[yzsuk]", "nchhg-lgm-nqvivkqvo-200[dystz]", "plolwdub-judgh-udeelw-rshudwlrqv-335[sihdt]", "wlsiayhcw-vumeyn-lymyulwb-292[zbrux]", "ytu-xjhwjy-hfsid-htfynsl-qtlnxynhx-411[adxmu]", "wkqxodsm-tovvilokx-ckvoc-822[uhgov]", "chnylhuncihuf-vumeyn-nluchcha-500[rcbmn]", "tfiifjzmv-lejkrscv-tyftfcrkv-jyzggzex-243[fjtvz]", "eqpuwogt-itcfg-tcddkv-tgugctej-310[pyemh]", "iuruxlar-xgsvgmotm-pkrrehkgt-xkykgxin-956[btwqp]", "shoewudys-sxesebqju-qdqboiyi-894[seqbd]", "zlkprjbo-doxab-gbiivybxk-pxibp-861[azyjx]", "ckgvutofkj-inuiurgzk-lotgtiotm-982[qszly]", "thnulapj-jshzzpmplk-jhukf-vwlyhapvuz-747[hpjlu]", "pybgmyargtc-hcjjwzcyl-qcptgacq-782[bxsuc]", "xgsvgmotm-vrgyzoi-mxgyy-iutzgotsktz-150[gtmoy]", "laffe-yigbktmkx-natz-jkyomt-696[ktafm]", "zvyvgnel-tenqr-pubpbyngr-znexrgvat-507[wfjhu]", "pelbtravp-pnaql-znantrzrag-403[cbyja]", "jqwpihizlwca-akidmvomz-pcvb-apqxxqvo-850[oxymv]", "cvabijtm-ntwemz-twoqabqka-954[atbmq]", "zixppfcfba-avb-zlkqxfkjbkq-809[zlmjc]", "sebehvkb-zubboruqd-tufqhjcudj-556[budeh]", "lqwhuqdwlrqdo-fdqgb-ghvljq-621[qdlgh]", "qlm-pbzobq-crwwv-zxkav-zlxqfkd-rpbo-qbpqfkd-731[ciyxw]", "pwcvonofrcig-gqojsbusf-vibh-qighcasf-gsfjwqs-740[csebm]", "mvydjvxodqz-kmjezxodgz-kgvnodx-bmvnn-yzqzgjkhzio-239[zdovg]", "kzgwomvqk-xtiabqk-oziaa-tijwzibwzg-564[menyj]", "ksodcbwnsr-xszzmpsob-kcfygvcd-454[mbaod]", "ejpanjwpekjwh-xwogap-hwxknwpknu-472[wpjkn]", "mvydjvxodqz-hvbizodx-wpiit-hvivbzhzio-967[ivzdh]", "mvydjvxodqz-mvwwdo-nzmqdxzn-681[jryzk]", "enqvbnpgvir-rtt-freivprf-871[lgqrc]", "hvbizodx-wpiit-kpmxcvndib-291[dyjmn]", "molgbzqfib-mixpqfz-doxpp-xkxivpfp-965[pxfib]", "fbebmtkr-zktwx-cxeeruxtg-nlxk-mxlmbgz-137[dckut]", "luxciuwncpy-luvvcn-mbcjjcha-500[qsvzt]", "apwmeclga-hcjjwzcyl-qyjcq-704[cjalq]", "wpuvcdng-eqttqukxg-uecxgpigt-jwpv-cpcnauku-830[ucgpt]", "iehepwnu-cnwza-fahhuxawj-pnwejejc-940[ewahj]", "pbybeshy-pbeebfvir-pnaql-pbngvat-freivprf-715[uyzwp]", "htsxzrjw-lwfij-ojqqdgjfs-zxjw-yjxynsl-957[iyonc]", "sxdobxkdsyxkv-wsvsdkbi-qbkno-zvkcdsm-qbkcc-bomosfsxq-536[mbyan]", "fruurvlyh-fkrfrodwh-uhdftxlvlwlrq-335[rflhu]", "froruixo-hjj-orjlvwlfv-387[uyawn]", "myvybpev-lexxi-vklybkdybi-978[ybvei]", "chnylhuncihuf-vohhs-xymcah-240[yxnmh]", "tagzsrsjvgmk-vqw-vwhsjlewfl-606[svwgj]", "zbytomdsvo-lexxi-domrxyvyqi-250[oxydi]", "qfkkj-clmmte-opgpwzaxpye-821[pekma]", "lgh-kwujwl-udskkaxawv-jsttal-hmjuzskafy-320[axyrm]", "irdgrxzex-nvrgfezqvu-avccpsvre-cfxzjkztj-191[sclzh]", "mhi-lxvkxm-xzz-etuhktmhkr-319[rcomn]", "lhkhszqx-fqzcd-dff-sdbgmnknfx-391[ugevx]", "apwmeclga-aylbw-ylyjwqgq-314[izfye]", "yflexwxoalrp-zlkprjbo-doxab-ciltbo-qbzeklildv-341[byclp]", "cvabijtm-kwzzwaqdm-ntwemz-abwziom-252[rdmvn]", "qfkkj-upwwjmply-epnsyzwzrj-899[okhgz]", "jxdkbqfz-avb-zlkqxfkjbkq-861[wptxb]", "gpsxdprixkt-qphzti-hwxeexcv-947[krgwe]", "nij-mywlyn-wuhxs-wiuncha-lymyulwb-968[wylnu]", "sbnqbhjoh-kfmmzcfbo-ufdiopmphz-987[bfhmo]", "guahyncw-jfumncw-alumm-xyjfisgyhn-500[htamn]", "ytu-xjhwjy-jll-ijxnls-879[duthg]", "lgh-kwujwl-usfvq-ugslafy-esfsywewfl-944[ilszy]", "tvsnigxmpi-tpewxmg-kveww-xiglrspskc-152[gipsw]", "joufsobujpobm-cbtlfu-dvtupnfs-tfswjdf-129[fubjo]", "rwcnawjcrxwju-bljenwpna-qdwc-mnyuxhvnwc-225[wncja]", "qzchnzbshud-okzrshb-fqzrr-rzkdr-989[rzhbd]", "qzoggwtwsr-pogysh-rsjszcdasbh-896[sghor]", "gzefmnxq-dmnnuf-xmnadmfadk-326[tvuiw]", "qzoggwtwsr-pibbm-zopcfohcfm-792[jsmfu]", "mvydjvxodqz-xviyt-xjvodib-hvivbzhzio-369[iceny]", "wkqxodsm-lkcuod-cdybkqo-224[dkocq]", "veqtekmrk-ikk-wxsveki-542[keivm]", "zlkprjbo-doxab-yxphbq-pqloxdb-419[ckdtm]", "buzahisl-ibuuf-klzpnu-721[stjnm]", "hwdtljsnh-kqtbjw-ijajqturjsy-515[plnqy]", "luxciuwncpy-jfumncw-alumm-lyuwkocmcncih-474[lqpco]", "tinnm-ibghopzs-rms-aobousasbh-506[sboah]", "pbeebfvir-rtt-ratvarrevat-403[tdokj]", "dmybmsuzs-pkq-efadmsq-300[msdqa]", "ujqgywfau-tmffq-dgyaklauk-970[yxmid]", "ovbunmneqbhf-enoovg-hfre-grfgvat-481[efgno]", "hqfxxnknji-kzeed-uqfxynh-lwfxx-wjhjnansl-957[nxfhj]", "plolwdub-judgh-edvnhw-pdqdjhphqw-985[dsxhg]", "nwlddtqtpo-awldetn-rcldd-nfdezxpc-dpcgtnp-353[dnptc]", "bwx-amkzmb-xzwrmkbqtm-ntwemz-amzdqkma-668[swmnl]", "bqxnfdmhb-qzaahs-rdquhbdr-443[bdhqa]", "egdytrixat-ide-htrgti-uadltg-steadnbtci-297[zampy]", "gsrwyqiv-kvehi-gerhc-gsexmrk-erepcwmw-880[bkwts]", "nsyjwsfyntsfq-gfxpjy-jslnsjjwnsl-749[lvzus]", "dfcxsqhwzs-pibbm-gvwddwbu-246[dqbem]", "mtzslklcozfd-ojp-fdpc-epdetyr-613[dpcef]", "gbc-frperg-ohaal-erfrnepu-351[reafg]", "gvaaz-cbtlfu-efqbsunfou-311[dvnmz]", "ugdgjxmd-tskcwl-umklgewj-kwjnauw-892[wgjku]", "iruzfrtkzmv-avccpsvre-nfibjyfg-243[jzoyc]", "shoewudys-hqrryj-bqrehqjeho-296[heqrj]", "hwdtljsnh-kqtbjw-htsyfnsrjsy-827[dntpc]", "zilqwikbqdm-kivlg-uiviomumvb-902[imvbk]", "rsvxltspi-sfnigx-wxsveki-984[sixve]", "surmhfwloh-gbh-xvhu-whvwlqj-387[hwluv]", "ubhatstkwhnl-yehpxk-wxlbzg-137[raqjb]", "oknkvcta-itcfg-uecxgpigt-jwpv-ocpcigogpv-596[cgpio]", "amjmpdsj-djmucp-nspafyqgle-470[ztpqn]", "zixppfcfba-avb-abpfdk-471[abfpc]", "owshgfarwv-jsttal-vwkayf-944[smcyx]", "vjpwncrl-ljwmh-lxjcrwp-lxwcjrwvnwc-589[irbxq]", "qvbmzvibqwvit-ziuxioqvo-lgm-amzdqkma-928[hgfln]", "lxuxaodu-kjbtnc-jwjuhbrb-147[bjuxa]", "etaqigpke-fag-yqtmujqr-440[qaegt]", "zekvierkzferc-irdgrxzex-jtrmvexvi-ylek-rthlzjzkzfe-633[gkyzp]", "mfklstdw-hdsklau-yjskk-kwjnauwk-762[vnfzg]", "pkl-oaynap-fahhuxawj-oanreyao-706[mdfpn]", "hwdtljsnh-hmthtqfyj-rfsfljrjsy-359[sxziu]", "fab-eqodqf-ngzzk-bgdotmeuzs-144[kxags]", "tagzsrsjvgmk-tskcwl-vwhsjlewfl-424[ejuah]", "kzgwomvqk-jiasmb-uizsmbqvo-590[mbiko]", "qjopwxha-xqjju-oanreyao-758[ubmon]", "hvbizodx-xmtjbzidx-nxvqzibzm-cpio-yzkgjthzio-889[rmyqo]", "iuruxlar-kmm-jkvruesktz-644[kruma]", "ujqgywfau-jsttal-vwhdgqewfl-710[hbdlx]", "jlidywncfy-wuhxs-wiuncha-yhachyylcha-630[hycaw]", "lugjuacha-wlsiayhcw-dyffsvyuh-uhufsmcm-890[juefh]", "hjgbwuladw-xdgowj-hmjuzskafy-398[wqigl]", "yuxufmdk-sdmpq-pkq-etubbuzs-456[wldkg]", "vcibutulxiom-dyffsvyuh-qilembij-110[jdnmz]", "nzwzcqfw-clmmte-dpcgtnpd-509[cdmnp]", "aczupnetwp-nlyoj-nzletyr-zapcletzyd-665[zelnp]", "htsxzrjw-lwfij-wfintfhynaj-kqtbjw-knsfshnsl-983[kytzm]", "enqvbnpgvir-onfxrg-qrirybczrag-611[rgnbi]", "molgbzqfib-ciltbo-xkxivpfp-159[biflo]", "plolwdub-judgh-fkrfrodwh-ghyhorsphqw-517[hdorw]", "gzefmnxq-omzpk-oazfmuzyqzf-872[zkycu]", "qjopwxha-lhwopey-cnwoo-naoawnyd-186[cvyno]", "jyfvnlupj-ipvohghykvbz-jovjvshal-ylzlhyjo-435[xlenk]", "ajmrxjlcren-kjbtnc-jwjuhbrb-329[klcuz]", "wdjcvuvmyjpn-ezggtwzvi-jkzmvodjin-603[gmveh]", "muqfedyput-fbqijys-whqii-bqrehqjeho-192[vdlge]", "ktfitzbgz-xzz-ftgtzxfxgm-605[izfql]", "bknsykmdsfo-oqq-wkbuodsxq-458[stifb]", "slqryzjc-hcjjwzcyl-yaosgqgrgml-314[qymir]", "gpewwmjmih-veffmx-xvemrmrk-126[itcvu]", "rdadguja-gpqqxi-ldgzhwde-297[hnvso]", "lxaaxbren-mhn-cnlqwxuxph-251[xvjuz]", "xst-wigvix-fewoix-gsrxemrqirx-698[xireg]", "iehepwnu-cnwza-zua-wymqeoepekj-108[sdnmj]", "oknkvcta-itcfg-rncuvke-itcuu-hkpcpekpi-908[pgfbe]", "enqvbnpgvir-ohaal-hfre-grfgvat-351[hsgdf]", "ixccb-iorzhu-hqjlqhhulqj-647[hqcij]", "apuut-agjrzm-jkzmvodjin-915[jamuz]", "hqcfqwydw-rqiauj-ijehqwu-530[qwhij]", "vhehkyne-ktwbhtvmbox-lvtoxgzxk-angm-kxvxbobgz-683[tsurp]", "gntmfefwitzx-idj-knsfshnsl-723[fnsit]", "ajvyjprwp-bljenwpna-qdwc-ujkxajcxah-563[yskxv]", "joufsobujpobm-dboez-dpbujoh-mbcpsbupsz-259[bopuj]", "xlrypetn-prr-nzyeltyxpye-847[yeprl]", "zuv-ykixkz-xgsvgmotm-lruckx-jkvgxzsktz-696[ijlfz]", "jqwpihizlwca-moo-lmxtwgumvb-798[nkzsr]", "jsvagsulanw-kusnwfywj-zmfl-klgjsyw-736[ectrq]", "ykhknbqh-nwxxep-nawymqeoepekj-758[cfvdy]", "kzeed-gfxpjy-tujwfyntsx-385[aunmy]", "slqryzjc-qaytclecp-fslr-dglylagle-184[lcyae]", "laffe-vrgyzoi-mxgyy-iutzgotsktz-410[gtyzf]", "gpbepvxcv-hrpktcvtg-wjci-stktadebtci-141[zoqhx]", "yaxsnlcrun-lqxlxujcn-mnyuxhvnwc-641[nxclu]", "tagzsrsjvgmk-kusnwfywj-zmfl-dstgjslgjq-294[gayon]", "kwzzwaqdm-zijjqb-xczkpiaqvo-902[mkgjt]", "mfklstdw-usfvq-ugslafy-xafsfuafy-684[fsaul]", "zvyvgnel-tenqr-ovbunmneqbhf-sybjre-fgbentr-117[shfce]", "emixwvqhml-akidmvomz-pcvb-amzdqkma-720[relbk]", "rdggdhxkt-eaphixr-vgphh-hwxeexcv-973[xozyv]", "bqvvu-zua-iwngapejc-992[nmdax]", "bjfutsneji-kqtbjw-wjxjfwhm-203[irjmx]", "bdavqofuxq-nmewqf-abqdmfuaze-976[vgzhc]", "vdzonmhydc-okzrshb-fqzrr-rzkdr-313[rzdhk]", "sawlkjevaz-oywrajcan-dqjp-wjwhuoeo-836[ajwoe]", "fruurvlyh-gbh-sxufkdvlqj-413[kftmo]", "fruurvlyh-sodvwlf-judvv-ghsorbphqw-569[tadzk]", "sbejpbdujwf-tdbwfohfs-ivou-dpoubjonfou-103[rbqio]", "oxmeeuruqp-otaoaxmfq-xasuefuoe-222[ozipy]", "rdggdhxkt-qphzti-ejgrwphxcv-921[tusrb]", "dkqjcbctfqwu-fag-yqtmujqr-882[kzvuf]", "gzefmnxq-dmnnuf-mzmxkeue-248[menfu]", "kgjgrypw-epybc-aylbw-kylyeckclr-314[mlvhs]", "bwx-amkzmb-akidmvomz-pcvb-abwziom-148[nmtyw]", "ckgvutofkj-sorozgxe-mxgjk-xghhoz-xkykgxin-670[gkxoh]", "zhdsrqlchg-fkrfrodwh-ghsorbphqw-803[cjybd]", "hvbizodx-wvnfzo-adivixdib-603[xwstz]", "tvsnigxmpi-gerhc-hitpscqirx-204[icghp]", "jrncbavmrq-cynfgvp-tenff-npdhvfvgvba-741[ybszn]", "mbiyqoxsm-pvygob-psxkxmsxq-952[mjfnc]", "gsrwyqiv-kvehi-veffmx-gywxsqiv-wivzmgi-282[bdrgj]", "clxalrtyr-xtwtelcj-rclop-awldetn-rcldd-cpdplcns-847[lcdrt]", "ahngzyzqcntr-bzmcx-sdbgmnknfx-287[fmyqt]", "zgmfyxypbmsq-aylbw-amyrgle-bctcjmnkclr-340[mybcl]", "fydelmwp-prr-nzyeltyxpye-717[gfjxa]", "rnqnyfwd-lwfij-rflsjynh-wfggny-xfqjx-931[fnjwy]", "zilqwikbqdm-xtiabqk-oziaa-twoqabqka-278[ftonr]", "bjfutsneji-gzssd-uzwhmfxnsl-827[sfjnu]", "ojk-nzxmzo-pinovwgz-agjrzm-jkzmvodjin-733[zjomn]", "ygcrqpkbgf-dcumgv-fgukip-570[vmhxn]", "dzczkrip-xiruv-srjbvk-jyzggzex-945[uzneh]", "bkzrrhehdc-bzmcx-lzmzfdldms-287[eclvd]", "ziuxioqvo-kpwkwtibm-lmxizbumvb-564[txsru]", "kzgwomvqk-lgm-lmxizbumvb-122[mbgkl]", "htsxzrjw-lwfij-idj-xjwanhjx-463[obdze]", "gntmfefwitzx-kqtbjw-wjxjfwhm-749[qzutv]", "htsxzrjw-lwfij-jll-tujwfyntsx-671[xugan]", "ymszqfuo-rxaiqd-etubbuzs-118[ubqsz]", "vdzonmhydc-azrjds-lzqjdshmf-989[dzhjm]", "dyz-combod-bkllsd-oxqsxoobsxq-354[nrmkx]", "pyknyegle-afmamjyrc-yaosgqgrgml-626[zdlfg]", "oxmeeuruqp-vqxxknqmz-oazfmuzyqzf-352[rnsyt]", "qjopwxha-xqjju-pnwejejc-654[jepqw]", "wifilzof-jfumncw-alumm-xypyfijgyhn-604[fjerw]", "vagreangvbany-enoovg-fuvccvat-533[gncot]", "avw-zljyla-zjhclunly-obua-thuhnltlua-669[wathd]", "ynssr-lvtoxgzxk-angm-mxvaghehzr-345[vopnm]", "cvabijtm-uqtqbizg-ozilm-xtiabqk-oziaa-lmdmtwxumvb-928[imabt]", "frqvxphu-judgh-sodvwlf-judvv-pdqdjhphqw-751[azovy]", "qmpmxevc-kvehi-jyddc-fyrrc-qerekiqirx-282[ygmhv]", "fodvvlilhg-udeelw-pdunhwlqj-153[sndmo]", "gpsxdprixkt-ytaanqtpc-gthtpgrw-765[tpgar]", "cvabijtm-kpwkwtibm-bmkpvwtwog-174[wbkmt]", "vetllbybxw-yehpxk-wxlbzg-891[yekxl]", "nzwzcqfw-nlyoj-dezclrp-275[zclnw]", "qmpmxevc-kvehi-glsgspexi-gsrxemrqirx-828[exgim]", "xtwtelcj-rclop-dnlgpyrpc-sfye-hzcvdsza-873[xmpon]", "jrncbavmrq-pnaql-jbexfubc-793[bacjn]", "ohmnuvfy-yaa-lymyulwb-266[yalmu]", "nzwzcqfw-aczupnetwp-awldetn-rcldd-pyrtyppctyr-613[pctwd]", "vqr-ugetgv-uecxgpigt-jwpv-rwtejcukpi-752[geptu]", "tfcfiwlc-lejkrscv-upv-rthlzjzkzfe-607[tcfns]", "hwdtljsnh-uqfxynh-lwfxx-knsfshnsl-229[xtngb]", "iuruxlar-igtje-iayzuskx-ykxboik-930[kmghr]", "xjgjmapg-ezggtwzvi-hvivbzhzio-421[gzivh]", "gpbepvxcv-hrpktcvtg-wjci-hwxeexcv-349[xswrp]", "tcorcikpi-eqttqukxg-gii-hkpcpekpi-622[ruxyk]", "ygcrqpkbgf-ejqeqncvg-ucngu-440[gcqen]", "etyyx-dff-qdbdhuhmf-729[wskto]", "tfiifjzmv-upv-vexzevvizex-399[veizf]", "houngfgxjuay-sorozgxe-mxgjk-jek-aykx-zkyzotm-566[aimhd]", "hcd-gsqfsh-dzoghwq-ufogg-aobousasbh-714[ynfie]", "foadouwbu-qobrm-qcohwbu-zopcfohcfm-792[obcfu]", "ynukcajey-oywrajcan-dqjp-wjwhuoeo-680[jaowy]", "rflsjynh-jll-rfsfljrjsy-489[jlfrs]", "vkrhzxgbv-pxtihgbsxw-yehpxk-mktbgbgz-917[igtvy]", "hjgbwuladw-tskcwl-dgyaklauk-294[aklwd]", "cvabijtm-jcvvg-zmikycqaqbqwv-772[vcqab]", "odiih-yujbcrl-pajbb-vjwjpnvnwc-849[jbcin]", "tinnm-tzcksf-igsf-hsghwbu-220[bnamt]", "pbeebfvir-wryylorna-jbexfubc-637[egouk]", "xmtjbzidx-xviyt-yzqzgjkhzio-265[vxsry]", "avw-zljyla-zjhclunly-obua-klwhyatlua-201[sjayl]", "dfcxsqhwzs-qvcqczohs-fsgsofqv-246[dosrp]", "rzvkjiduzy-xviyt-xjvodib-kpmxcvndib-291[cwzla]", "gcfcnuls-aluxy-mwupyhayl-bohn-wihnuchgyhn-968[hnuyc]", "dyz-combod-lsyrkjkbnyec-bkllsd-domrxyvyqi-328[vtxzd]", "fruurvlyh-mhoobehdq-dftxlvlwlrq-907[jlves]", "mrxivrexmsrep-gerhc-gsexmrk-tyvglewmrk-152[wzuly]", "votubcmf-gmpxfs-pqfsbujpot-883[fpbmo]", "bljenwpna-qdwc-anbnjalq-329[lcwmy]", "xekdwvwnzkqo-ydkykhwpa-wjwhuoeo-550[toavy]", "yhkpvhjapcl-yhiipa-jbzavtly-zlycpjl-201[lpyah]", "xjinphzm-bmvyz-wvnfzo-nzmqdxzn-681[ykfxe]", "pbeebfvir-rtt-ybtvfgvpf-507[bftve]", "gvcskirmg-ikk-hizipstqirx-750[iyquj]", "yhwooebeaz-lhwopey-cnwoo-oanreyao-108[tmuag]", "wlqqp-jtrmvexvi-ylek-nfibjyfg-581[tnrhf]", "tfiifjzmv-avccpsvre-jyzggzex-477[mvnjr]", "xjmmjndqz-zbb-yzndbi-811[bzdjm]", "qjopwxha-xwogap-nayaerejc-160[isjqz]", "qzlozfhmf-azrjds-knfhrshbr-573[dfmys]", "vhglnfxk-zktwx-vetllbybxw-vtgwr-vhtmbgz-ybgtgvbgz-761[gbtvl]", "etaqigpke-ecpfa-eqcvkpi-cpcnauku-336[eyxtb]", "lqwhuqdwlrqdo-fdqgb-frdwlqj-zrunvkrs-933[tvijl]", "gvcskirmg-tvsnigxmpi-gerhc-gsexmrk-wlmttmrk-828[szawg]", "irdgrxzex-kfg-jvtivk-wcfnvi-jyzggzex-269[givxz]", "cqwdujys-sqdto-iqbui-270[siyeh]", "bnqqnrhud-bgnbnkzsd-trdq-sdrshmf-807[dnbqr]", "rgndvtcxr-hrpktcvtg-wjci-prfjxhxixdc-193[yjsht]", "qekrixmg-hci-xvemrmrk-282[mreik]", "xcitgcpixdcpa-snt-apqdgpidgn-349[mfywv]", "wkqxodsm-pvygob-wkbuodsxq-978[ysamp]", "aoubshwq-qvcqczohs-kcfygvcd-558[ytvls]", "tyepcyletzylw-qwzhpc-opalcexpye-301[gamdn]", "tfcfiwlc-treup-uvjzxe-607[nrthm]", "ubhatstkwhnl-lvtoxgzxk-angm-inkvatlbgz-865[tagkl]", "wihmogyl-aluxy-yaa-qilembij-890[emvct]", "bxaxipgn-vgpst-ltpedcxots-gpqqxi-hidgpvt-245[pgtxi]", "jfifqxov-doxab-mixpqfz-doxpp-obpbxoze-107[ghpyi]", "gvaaz-dpssptjwf-sbccju-fohjoffsjoh-675[pfzwa]", "gzefmnxq-eomhqzsqd-tgzf-efadmsq-378[qefmz]", "emixwvqhml-kivlg-zmkmqdqvo-876[dcfin]", "fodvvlilhg-fdqgb-frqwdlqphqw-725[qdflg]", "laffe-pkrrehkgt-rumoyzoiy-670[dyjut]", "egdytrixat-qphzti-tcvxcttgxcv-245[tcxgi]", "htqtwkzq-wfintfhynaj-xhfajsljw-mzsy-jslnsjjwnsl-645[eynzi]", "vrurcjah-pajmn-npp-mnyuxhvnwc-563[npach]", "ejpanjwpekjwh-acc-klanwpekjo-576[jaekp]", "kwvacumz-ozilm-kpwkwtibm-uizsmbqvo-876[mikwz]", "hjgbwuladw-xdgowj-esfsywewfl-866[byzdm]", "pbybeshy-wryylorna-npdhvfvgvba-351[stmxy]", "qjopwxha-ywjzu-hkceopeyo-654[tysoa]", "lhkhszqx-fqzcd-dff-vnqjrgno-417[fqdhn]", "rgllk-otaoaxmfq-fdmuzuzs-768[vkqac]", "ohmnuvfy-xsy-omyl-nymncha-214[hmtfs]", "enzcntvat-cynfgvp-tenff-nanylfvf-455[cuimh]", "sedikcuh-whqtu-sehheiylu-tou-bqrehqjeho-868[ydaux]", "tyepcyletzylw-ojp-opalcexpye-145[wciks]", "udpsdjlqj-hjj-frqwdlqphqw-309[gbpcz]", "eqpuwogt-itcfg-lgnnadgcp-vtckpkpi-388[gpcti]", "rkpqxyib-pzxsbkdbo-erkq-zrpqljbo-pbosfzb-133[bpkoq]", "kdijqrbu-sxesebqju-tufqhjcudj-114[tdbva]", "gsvvswmzi-wgezirkiv-lyrx-irkmriivmrk-412[twsrk]", "ucynmlgxcb-qaytclecp-fslr-amlryglkclr-704[lcrya]", "xst-wigvix-veffmx-wxsveki-100[ocvmr]", "surmhfwloh-vfdyhqjhu-kxqw-frqwdlqphqw-829[hqwfd]", "xmrrq-usfvq-esfsywewfl-528[alidm]", "zhdsrqlchg-lqwhuqdwlrqdo-sodvwlf-judvv-ghsorbphqw-777[rtnmj]", "egdytrixat-xcitgcpixdcpa-rwdrdapit-uxcpcrxcv-245[cdabn]", "yrwxefpi-ikk-gywxsqiv-wivzmgi-152[iwgkv]", "qcffcgwjs-foppwh-obozmgwg-558[zotsu]", "veqtekmrk-gerhc-gsexmrk-hitpscqirx-568[nczdq]", "gzefmnxq-pkq-pqbmdfyqzf-794[jxrmh]", "eadalsjq-yjsvw-usfvq-ugslafy-ugflsafewfl-632[fsalu]", "esyfwlau-usfvq-ugslafy-vwhdgqewfl-684[flsuw]", "ktfitzbgz-fbebmtkr-zktwx-utldxm-wxlbzg-683[afwhg]", "wihmogyl-aluxy-vohhs-uwkocmcncih-292[wzryd]", "bkzrrhehdc-idkkxadzm-lzmzfdldms-677[oxwvn]", "clxalrtyr-qwzhpc-lnbftdtetzy-249[zryvn]", "rgllk-fab-eqodqf-vqxxknqmz-pqbxakyqzf-222[qfkxa]", "xjinphzm-bmvyz-xviyt-mzxzdqdib-603[xnhfs]", "htsxzrjw-lwfij-hmthtqfyj-wjfhvznxnynts-385[zreuy]", "myvybpev-gokzyxsjon-oqq-nozvyiwoxd-692[iyzuj]", "hcd-gsqfsh-pogysh-gvwddwbu-480[mysuk]", "hcd-gsqfsh-foppwh-rsgwub-428[kvtfs]", "frqvxphu-judgh-exqqb-uhvhdufk-621[wtgmn]", "vhglnfxk-zktwx-vahvhetmx-vhgmtbgfxgm-345[hnamj]", "tagzsrsjvgmk-usfvq-ugslafy-ugflsafewfl-892[yckbv]", "joufsobujpobm-gmpxfs-vtfs-uftujoh-233[foujs]", "zsxyfgqj-ojqqdgjfs-zxjw-yjxynsl-593[jqsxy]", "bnknqetk-atmmx-qdzbpthrhshnm-131[ecnmt]", "hmsdqmzshnmzk-dff-sqzhmhmf-859[dnxcz]", "hqtyeqsjylu-tou-udwyduuhydw-348[uydhq]", "ktiaaqnqml-kpwkwtibm-zmikycqaqbqwv-772[tlrsg]", "nzydfxpc-rclop-mtzslklcozfd-mfyyj-nfdezxpc-dpcgtnp-951[cpdfz]", "ckgvutofkj-hatte-gtgreyoy-644[tgeko]", "iwcjapey-zua-paydjkhkcu-628[hntmg]", "bnknqetk-okzrshb-fqzrr-trdq-sdrshmf-729[tuzoy]", "qmpmxevc-kvehi-yrwxefpi-glsgspexi-wlmttmrk-828[hsyvf]", "amjmpdsj-njyqrga-epyqq-qcptgacq-106[bhysd]", "dwbcjkun-ljwmh-mnyuxhvnwc-641[wuyrz]", "gspsvjyp-jpsaiv-hiwmkr-854[zthel]", "gsrwyqiv-kvehi-gerhc-stivexmsrw-750[whgse]", "xjgjmapg-wpiit-ozxcijgjbt-889[ytsop]", "xgjougizobk-kmm-rghuxgzuxe-280[cwrty]", "zovldbkfz-oxjmxdfkd-oxyyfq-ixyloxqlov-653[snkwb]", "qczcftiz-qvcqczohs-gsfjwqsg-142[cqszf]", "krxqjijamxdb-mhn-ldbcxvna-bnaerln-771[ravbt]", "pybgmyargtc-bwc-bcqgel-860[bcgya]", "wyvqljapsl-jovjvshal-shivyhavyf-773[vahjl]", "pbafhzre-tenqr-onfxrg-bcrengvbaf-221[zyaro]", "glrcplyrgmlyj-bwc-pcqcypaf-132[clpyg]", "dpmpsgvm-dboez-dpbujoh-tfswjdft-545[bdmzf]", "dkqjcbctfqwu-rncuvke-itcuu-cpcnauku-700[cuknq]", "ajmrxjlcren-yujbcrl-pajbb-anbnjalq-459[yslvg]", "oazegyqd-sdmpq-bxmefuo-sdmee-fqotzaxask-586[vfmnu]", "ugdgjxmd-jsttal-ksdwk-632[hfjix]", "aietsrmdih-gvcskirmg-tpewxmg-kveww-vigimzmrk-412[kfcim]", "drxevkzt-jtrmvexvi-ylek-uvgcfpdvek-685[vekdr]", "excdklvo-bkllsd-nozvyiwoxd-250[dlokv]", "uwtojhynqj-hfsid-wjxjfwhm-281[fqsmx]", "plolwdub-judgh-udeelw-uhfhlylqj-205[ludhe]", "oqnidbshkd-dff-zmzkxrhr-729[cvlkx]", "bknsykmdsfo-tovvilokx-bomosfsxq-328[boqly]", "dpotvnfs-hsbef-qspkfdujmf-cvooz-tijqqjoh-961[zmnyi]", "gspsvjyp-fyrrc-gsrxemrqirx-490[rsgpx]", "gifavtkzcv-szfyrqriuflj-wcfnvi-uvmvcfgdvek-139[zadfj]", "gsrwyqiv-kvehi-wgezirkiv-lyrx-wxsveki-490[alpzb]", "ykhknbqh-ydkykhwpa-zalhkuiajp-862[khayp]", "dmybmsuzs-yuxufmdk-sdmpq-bxmefuo-sdmee-fqotzaxask-586[nwikx]", "nwzekwypera-bhksan-nayaerejc-940[xnmta]", "wrs-vhfuhw-hjj-zrunvkrs-283[hrjsu]", "ajyqqgdgcb-pyzzgr-amlryglkclr-782[lozts]", "ohmnuvfy-jfumncw-alumm-womnigyl-mylpcwy-110[mqrgd]", "foadouwbu-suu-obozmgwg-792[hgkuj]", "wdjcvuvmyjpn-ytz-yzkgjthzio-109[jyztv]", "ucynmlgxcb-pyzzgr-qfgnngle-210[iftry]", "ymszqfuo-omzpk-oamfuzs-pqhqxabyqzf-872[qzfmo]", "clotzlnetgp-ojp-opawzjxpye-769[pnhtz]", "mhi-lxvkxm-yehpxk-ftgtzxfxgm-657[etajx]", "surmhfwloh-fkrfrodwh-uhfhlylqj-699[rkslj]", "iruzfrtkzmv-tyftfcrkv-kirzezex-841[emztq]", "bdavqofuxq-nmewqf-ogefayqd-eqdhuoq-352[jpmyv]", "bdavqofuxq-otaoaxmfq-xasuefuoe-326[aofqu]", "gpsxdprixkt-tvv-ldgzhwde-219[dgptv]", "pbeebfvir-rtt-bcrengvbaf-897[enlaq]", "jchipqat-gpqqxi-bpgztixcv-375[cnqyt]", "glrcplyrgmlyj-qaytclecp-fslr-pcqcypaf-574[clpyr]", "pejji-oqq-vyqscdsmc-640[qcjsd]", "houngfgxjuay-yigbktmkx-natz-xkykgxin-774[mszcw]", "ltpedcxots-jchipqat-gpqqxi-bpcpvtbtci-219[isgfv]", "gifavtkzcv-tyftfcrkv-drerxvdvek-659[vbdyz]", "vjpwncrl-mhn-orwjwlrwp-641[wrjln]", "vjpwncrl-ouxfna-bcxajpn-511[ydzfw]", "rzvkjiduzy-xviyt-xjvodib-adivixdib-187[idvxb]", "tinnm-suu-twbobqwbu-272[datjf]", "apuut-xviyt-vxlpdndodji-941[zrtso]", "jxdkbqfz-zixppfcfba-mixpqfz-doxpp-jxohbqfkd-705[fpxbd]", "zilqwikbqdm-lgm-kwvbiqvumvb-876[bqpme]", "jyddc-wgezirkiv-lyrx-wxsveki-256[sjntv]", "ahngzyzqcntr-qzaahs-zbpthrhshnm-963[fzvai]", "ksodcbwnsr-qfmcusbwq-suu-qighcasf-gsfjwqs-350[wyezk]", "atyzghrk-igtje-iugzotm-jkyomt-462[ksuli]", "dwbcjkun-ajmrxjlcren-yujbcrl-pajbb-nwprwnnarwp-563[tjsqg]", "aoubshwq-dzoghwq-ufogg-aofyshwbu-896[hwcmz]", "apwmeclga-npmhcargjc-njyqrga-epyqq-rpyglgle-340[dgtsc]", "apwmeclga-aylbw-amyrgle-dglylagle-210[iumzy]", "ydjuhdqjyedqb-rkddo-sedjqydcudj-738[ycbmx]", "iuxxuyobk-xgjougizobk-pkrrehkgt-sgtgmksktz-644[pzsmw]", "bnmrtldq-fqzcd-bgnbnkzsd-vnqjrgno-521[nbdqg]", "wfruflnsl-gzssd-wjhjnansl-177[wtmsg]", "yhwooebeaz-ywjzu-klanwpekjo-680[eowaj]", "pynffvsvrq-cynfgvp-tenff-ernpdhvfvgvba-663[vbduy]", "zilqwikbqdm-ntwemz-uizsmbqvo-356[yhenq]", "jvsvymbs-zjhclunly-obua-jvuahputlua-721[uajlv]", "fhezusjybu-rqiauj-tufbeocudj-400[ecamb]", "ftzgxmbv-wrx-xgzbgxxkbgz-293[xgbzf]", "chnylhuncihuf-xsy-xypyfijgyhn-578[jigcy]", "vhkkhlbox-pxtihgbsxw-cxeeruxtg-wxlbzg-111[hsuty]", "foadouwbu-tzcksf-gozsg-246[ofgsu]", "xzwrmkbqtm-moo-nqvivkqvo-434[moqvk]", "gvaaz-cvooz-dpoubjonfou-415[mcnzb]", "pbafhzre-tenqr-enoovg-grpuabybtl-169[bktjl]", "uwtojhynqj-gzssd-ywfnsnsl-723[phguv]", "dlhwvupglk-zjhclunly-obua-klwhyatlua-227[luahk]", "vhkkhlbox-vhehkyne-vahvhetmx-ybgtgvbgz-215[hvbeg]", "qlm-pbzobq-gbiivybxk-lmboxqflkp-809[blqik]", "forwcoqhwjs-qvcqczohs-ghcfous-792[mtuqn]", "eqpuwogt-itcfg-dwppa-fgrnqaogpv-570[gpafo]", "lxuxaodu-bljenwpna-qdwc-jwjuhbrb-121[rbqfd]", "ykhknbqh-xqjju-oanreyao-680[ahjkn]", "ugfkmewj-yjsvw-hdsklau-yjskk-kzahhafy-918[kahjs]", "gbc-frperg-fpniratre-uhag-fnyrf-897[dskta]", "myxcewob-qbkno-lexxi-wkxkqowoxd-770[spdoc]", "cqwdujys-fbqijys-whqii-huiuqhsx-998[uhebs]", "ckgvutofkj-igtje-iugzotm-rghuxgzuxe-774[gutei]", "excdklvo-lexxi-psxkxmsxq-302[ypsmx]", "mbiyqoxsm-dyz-combod-mkxni-mykdsxq-zebmrkcsxq-692[fnhpz]", "zlkprjbo-doxab-gbiivybxk-xkxivpfp-809[ydtxn]", "wdjcvuvmyjpn-ezggtwzvi-hvmfzodib-603[vzdgi]", "njmjubsz-hsbef-fhh-bobmztjt-649[mxkjw]", "wsvsdkbi-qbkno-oqq-ecob-docdsxq-796[rglok]", "htsxzrjw-lwfij-gfxpjy-fsfqdxnx-307[uyteb]", "wpuvcdng-ejqeqncvg-yqtmujqr-882[svamn]", "tagzsrsjvgmk-hdsklau-yjskk-ugflsafewfl-606[tysrn]", "kwtwznct-akidmvomz-pcvb-zmamizkp-200[skpom]", "dpmpsgvm-dboez-dpbujoh-fohjoffsjoh-311[fknst]", "rnqnyfwd-lwfij-hmthtqfyj-xytwflj-567[gzkol]", "zntargvp-pnaql-hfre-grfgvat-923[yijbm]", "dzczkrip-xiruv-treup-tfrkzex-drerxvdvek-347[vrmsu]", "ajyqqgdgcb-afmamjyrc-sqcp-rcqrgle-522[cqagr]", "pelbtravp-ohaal-erprvivat-715[jnbmz]", "irdgrxzex-sleep-ivrthlzjzkzfe-113[bmsnw]", "eqpuwogt-itcfg-tcddkv-fgxgnqrogpv-804[gtcdf]", "cvabijtm-moo-ivitgaqa-226[darfu]", "ytu-xjhwjy-xhfajsljw-mzsy-zxjw-yjxynsl-281[wzjeb]", "fkqbokxqflkxi-yxphbq-obxznrfpfqflk-809[dcasb]", "gokzyxsjon-sxdobxkdsyxkv-mkxni-ecob-docdsxq-276[zypso]", "ibghopzs-suu-kcfygvcd-402[cgsub]", "tfiifjzmv-srjbvk-uvjzxe-581[sovtj]", "gntmfefwitzx-gfxpjy-xmnuunsl-619[fnxgm]", "lgh-kwujwl-bwddqtwsf-vwhsjlewfl-788[tlejf]", "hjgbwuladw-wyy-ghwjslagfk-164[wgahj]", "nzwzcqfw-ojp-qtylyntyr-431[ynqtw]", "sbejpbdujwf-sbccju-vtfs-uftujoh-909[kujit]", "vhkkhlbox-wrx-ftkdxmbgz-241[uwzex]", "lahxpnwrl-bljenwpna-qdwc-cajrwrwp-381[yjzno]", "lugjuacha-jfumncw-alumm-jolwbumcha-838[uamcj]", "gvcskirmg-glsgspexi-jmrergmrk-828[smeyi]", "thnulapj-ihzrla-thyrlapun-955[ahlnp]", "sno-rdbqds-bzmcx-btrsnldq-rdquhbd-937[dbqrs]", "vdzonmhydc-eknvdq-dmfhmddqhmf-781[dmhfn]", "iehepwnu-cnwza-xqjju-ykjpwejiajp-368[jepwa]", "dfcxsqhwzs-dzoghwq-ufogg-cdsfohwcbg-974[gcdfh]", "sbqiiyvyut-tou-jhqydydw-608[okbzs]", "htsxzrjw-lwfij-gzssd-uzwhmfxnsl-801[nmtjq]", "hvbizodx-rzvkjiduzy-xviyt-yzqzgjkhzio-213[zivyd]", "ajmrxjlcren-ljwmh-lxjcrwp-bqryyrwp-745[kheat]", "vkppo-shoewudys-tou-udwyduuhydw-556[udowy]", "dpotvnfs-hsbef-dmbttjgjfe-gmpxfs-nbslfujoh-363[qapli]", "glrcplyrgmlyj-djmucp-qrmpyec-158[clmpr]", "emixwvqhml-xtiabqk-oziaa-wxmzibqwva-642[rkpba]", "qczcftiz-dzoghwq-ufogg-aofyshwbu-298[lmcuy]", "cvabijtm-zilqwikbqdm-akidmvomz-pcvb-nqvivkqvo-746[ynxzo]", "pkl-oaynap-acc-wjwhuoeo-134[jxlai]", "xjmmjndqz-kgvnodx-bmvnn-rjmfncjk-291[njmdk]", "ejpanjwpekjwh-nwxxep-nayaerejc-550[lisvd]", "htwwtxnaj-htsxzrjw-lwfij-hfsid-htfynsl-wjfhvznxnynts-541[hntwf]", "mbiyqoxsm-mkxni-mykdsxq-crszzsxq-770[zhowm]", "rmn-qcapcr-ucynmlgxcb-cee-pcqcypaf-886[cpaem]", "rtqlgevkng-ejqeqncvg-fgxgnqrogpv-466[zktns]", "fydelmwp-mfyyj-nfdezxpc-dpcgtnp-769[anfej]", "yuxufmdk-sdmpq-otaoaxmfq-pqbxakyqzf-742[ohxti]", "vxupkizork-igtje-xkgiwaoyozout-592[bmwjf]", "veqtekmrk-tvsnigxmpi-gerhc-gsexmrk-gywxsqiv-wivzmgi-802[dglps]", "nsyjwsfyntsfq-uqfxynh-lwfxx-ijuqtdrjsy-931[ymnhu]", "gifavtkzcv-avccpsvre-fgvirkzfej-841[ypigz]", "krxqjijamxdb-kdwwh-mnyjacvnwc-641[krnma]", "dszphfojd-ezf-sftfbsdi-805[fdszb]", "xmrrq-tmffq-lwuzfgdgyq-372[fqgmr]", "tagzsrsjvgmk-xdgowj-vwhsjlewfl-788[gjswl]", "lsyrkjkbnyec-mkxni-nofovyzwoxd-614[knoyx]", "dwbcjkun-mhn-bjunb-173[mykra]", "vhehkyne-vtgwr-nlxk-mxlmbgz-319[eghkl]", "bkzrrhehdc-bnqqnrhud-bzmcx-bnzshmf-otqbgzrhmf-677[xaszn]", "oxmeeuruqp-bxmefuo-sdmee-abqdmfuaze-248[udtec]", "jlidywncfy-mwupyhayl-bohn-uhufsmcm-500[yhmuc]", "xjmmjndqz-zbb-mzvxlpdndodji-239[djmzb]", "yuxufmdk-sdmpq-omzpk-qzsuzqqduzs-534[ofrpg]", "tfejldvi-xiruv-vxx-uvgrikdvek-659[cnesm]", "yaxsnlcrun-ajkkrc-anbnjalq-979[nmivs]", "tvsnigxmpi-ikk-wivzmgiw-880[agunv]", "mrxivrexmsrep-tpewxmg-kveww-viwievgl-698[evwim]", "nglmtuex-yehpxk-labiibgz-241[begil]", "zuv-ykixkz-ixeumktoi-igtje-iugzotm-aykx-zkyzotm-670[pjybl]", "forwcoqhwjs-dzoghwq-ufogg-difqvogwbu-272[xkwoz]", "ajyqqgdgcb-qaytclecp-fslr-bcqgel-886[mkvsi]", "myxcewob-qbkno-mkxni-mykdsxq-wkbuodsxq-770[zmijb]", "uwtojhynqj-kqtbjw-yjhmstqtld-333[jtqhw]", "wsvsdkbi-qbkno-lkcuod-dbksxsxq-406[biaoe]", "gpbepvxcv-rpcsn-rdpixcv-advxhixrh-895[dcwgp]", "muqfedyput-isqludwuh-xkdj-mehaixef-712[betdq]", "ckgvutofkj-inuiurgzk-xkgiwaoyozout-956[sazyo]", "wfruflnsl-uqfxynh-lwfxx-btwpxmtu-541[fxluw]", "qfmcusbwq-rms-igsf-hsghwbu-246[sbfgh]", "ynukcajey-nwxxep-qoan-paopejc-602[htmbv]", "ujqgywfau-uzgugdslw-jwkwsjuz-138[newms]", "yflexwxoalrp-zxkav-cfkxkzfkd-705[ctnsy]", "vjpwncrl-lqxlxujcn-mnyuxhvnwc-953[nawmz]", "willimcpy-wuhxs-lyuwkocmcncih-786[cilwh]", "mtzslklcozfd-clmmte-cpnptgtyr-119[tjkgv]", "xlrypetn-awldetn-rcldd-cplnbftdtetzy-795[tdlen]", "vkppo-rqiauj-huqsgkyiyjyed-452[yijkp]", "vxupkizork-lruckx-jkbkruvsktz-124[eumyz]", "diozmivodjivg-agjrzm-nzmqdxzn-915[otpfl]", "owshgfarwv-hdsklau-yjskk-klgjsyw-918[qcjim]", "zuv-ykixkz-igtje-iugzotm-zkinturume-202[plvqf]", "zlilocri-oxyyfq-bkdfkbbofkd-835[bswmn]", "ziuxioqvo-lgm-amzdqkma-798[maioq]", "xqvwdeoh-sodvwlf-judvv-ghyhorsphqw-517[hvdow]", "ovbunmneqbhf-enqvbnpgvir-onfxrg-qrfvta-507[nvbfq]", "gbc-frperg-pnaql-genvavat-351[pmzkq]", "eadalsjq-yjsvw-jsttal-suimakalagf-580[zjghy]", "rdadguja-rpcsn-rdpixcv-apqdgpidgn-245[dpagr]", "tbxmlkfwba-pzxsbkdbo-erkq-abpfdk-523[vifrq]", "ocipgvke-uecxgpigt-jwpv-ugtxkegu-544[abfsh]", "ovbunmneqbhf-zvyvgnel-tenqr-wryylorna-ybtvfgvpf-481[hxymg]", "pinovwgz-xjinphzm-bmvyz-agjrzm-ozxcijgjbt-681[cqlnu]", "tinnm-qobrm-ghcfous-220[hyczt]", "iuruxlar-yigbktmkx-natz-ykxboiky-748[kixya]", "bkzrrhehdc-bzmcx-bnzshmf-cdrhfm-209[hbcmr]", "gpsxdprixkt-tvv-uxcpcrxcv-973[xcpvr]", "forwcoqhwjs-rms-hfowbwbu-974[stzrm]", "zovldbkfz-fkqbokxqflkxi-mixpqfz-doxpp-cfkxkzfkd-705[tsmfo]", "vetllbybxw-lvtoxgzxk-angm-ftgtzxfxgm-371[sbemy]", "hwbba-ejqeqncvg-tgugctej-232[iyrqv]", "vqr-ugetgv-lgnnadgcp-wugt-vguvkpi-596[gvunp]", "xgvnndadzy-wpiit-yzndbi-343[rawyd]", "jxdkbqfz-oxyyfq-qbzeklildv-107[qbdfk]", "wlsiayhcw-luvvcn-mufym-656[jbvne]", "surmhfwloh-fdqgb-ghvljq-621[ymnve]", "mvkccspson-bkllsd-vklybkdybi-432[yscux]", "dszphfojd-sbccju-dvtupnfs-tfswjdf-129[itbfs]", "lsyrkjkbnyec-lexxi-crszzsxq-978[sxcek]", "qlm-pbzobq-mixpqfz-doxpp-zlkqxfkjbkq-211[satyb]", "bknsykmdsfo-nio-kmaescsdsyx-744[tspif]", "bpvctixr-rpcsn-rjhidbtg-htgkxrt-713[rtbcg]", "sebehvkb-rqiauj-udwyduuhydw-140[udbeh]", "zhdsrqlchg-fdqgb-hqjlqhhulqj-387[zptrs]", "qxdwpopgsdjh-rpcsn-sthxvc-635[nbixj]", "pualyuhapvuhs-msvdly-klzpnu-721[ulpah]", "sbqiiyvyut-shoewudys-isqludwuh-xkdj-jhqydydw-894[dysuh]", "wsvsdkbi-qbkno-lexxi-dbksxsxq-614[onzwh]", "ydjuhdqjyedqb-rqiauj-efuhqjyedi-894[ocdpe]", "kwzzwaqdm-ntwemz-wxmzibqwva-434[nwzml]", "qspkfdujmf-fhh-nbobhfnfou-571[zpyau]", "bxaxipgn-vgpst-tvv-detgpixdch-583[xwiac]", "qfmcusbwq-dfcxsqhwzs-xszzmpsob-fsqswjwbu-402[lstrx]", "dpmpsgvm-dboez-sfdfjwjoh-337[dfjmo]", "dzoghwq-ufogg-fsgsofqv-636[gfoqs]", "nzwzcqfw-dnlgpyrpc-sfye-qtylyntyr-509[milhd]", "xgsvgmotm-pkrrehkgt-vaxingyotm-176[jubcm]", "xgsvgmotm-jek-cuxqynuv-644[soxwn]", "cxy-bnlanc-lahxpnwrl-kdwwh-fxatbqxy-485[zamhj]", "irgyyolokj-inuiurgzk-sgtgmksktz-982[vzkrq]", "xgvnndadzy-xcjxjgvoz-xjiovdihzio-733[ozhyu]", "gvcskirmg-nippcfier-xiglrspskc-334[bastq]", "zlilocri-gbiivybxk-obxznrfpfqflk-367[ntyda]", "pyknyegle-pyzzgr-pcqcypaf-886[nxvzy]", "zhdsrqlchg-gbh-frqwdlqphqw-361[nqzts]", "kyelcrga-cee-yaosgqgrgml-808[izdqr]", "hplazytkpo-prr-cpnptgtyr-379[prtya]", ] let rooms = parse_input(input) .filter(is_real) for room in rooms { print("\(decrypt(room)) -> \(room.sector)") }
46.20888
67
0.770685
79b4ee6a7789b02c24dfdb7925614918559a4736
427
// // DiscoverItem.swift // CosmoQuiz // // Created by Pablo Escriva on 18/04/2019. // Copyright © 2019 Pablo Escriva. All rights reserved. // import Foundation import Alamofire class ApodItem{ var title:String var image:UIImage var description:String var date:Date init(){ self.title = "" self.image = UIImage() self.description = "" self.date = Date() } }
15.814815
56
0.606557
75e3969264db6bca8e0df9b009551b04950f18f9
201
// // JournalData.swift // Feedetite // // Created by Vigneshwar Devendran on 17/05/18. // Copyright © 2018 Vigneshwar Devendran. All rights reserved. // import Foundation class JournalData{ }
13.4
63
0.706468
d6348b79bcabc52b3557b4e9add03be1e8c159ae
31,062
// // Toast.swift // Toast-Swift // // Copyright (c) 2015-2019 Charles Scalesse. // // 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 import ObjectiveC /** Toast is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code. The `makeToast` methods create a new view and then display it as toast. The `showToast` methods display any view as toast. */ public extension UIView { /** Keys used for associated objects. */ private struct ToastKeys { static var timer = "com.toast-swift.timer" static var duration = "com.toast-swift.duration" static var point = "com.toast-swift.point" static var completion = "com.toast-swift.completion" static var activeToasts = "com.toast-swift.activeToasts" static var activityView = "com.toast-swift.activityView" static var queue = "com.toast-swift.queue" } /** Swift closures can't be directly associated with objects via the Objective-C runtime, so the (ugly) solution is to wrap them in a class that can be used with associated objects. */ private class ToastCompletionWrapper { let completion: ((Bool) -> Void)? init(_ completion: ((Bool) -> Void)?) { self.completion = completion } } private enum ToastError: Error { case missingParameters } private var activeToasts: NSMutableArray { get { if let activeToasts = objc_getAssociatedObject(self, &ToastKeys.activeToasts) as? NSMutableArray { return activeToasts } else { let activeToasts = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.activeToasts, activeToasts, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return activeToasts } } } private var queue: NSMutableArray { get { if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray { return queue } else { let queue = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return queue } } } // MARK: - Make Toast Methods /** Creates and presents a new toast view. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.missingParameters { print("Error: message, title, and image are all nil") } catch {} } /** Creates a new toast view and presents it at a given center point. @param message The message to be displayed @param duration The toast duration @param point The toast's center point @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, point: point, completion: completion) } catch ToastError.missingParameters { print("Error: message, title, and image cannot all be nil") } catch {} } // MARK: - Show Toast Methods /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's position @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) { let point = position.centerPoint(forToast: toast, inSuperview: self) showToast(toast, duration: duration, point: point, completion: completion) } /** Displays any view as toast at a provided center point and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param point The toast's center point @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) { objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); if ToastManager.shared.isQueueEnabled, activeToasts.count > 0 { objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); queue.add(toast) } else { showToast(toast, duration: duration, point: point) } } // MARK: - Hide Toast Methods /** Hides the active toast. If there are multiple toasts active in a view, this method hides the oldest toast (the first of the toasts to have been presented). @see `hideAllToasts()` to remove all active toasts from a view. @warning This method has no effect on activity toasts. Use `hideToastActivity` to hide activity toasts. */ func hideToast() { guard let activeToast = activeToasts.firstObject as? UIView else { return } hideToast(activeToast) } /** Hides an active toast. @param toast The active toast view to dismiss. Any toast that is currently being displayed on the screen is considered active. @warning this does not clear a toast view that is currently waiting in the queue. */ func hideToast(_ toast: UIView) { guard activeToasts.contains(toast) else { return } hideToast(toast, fromTap: false) } /** Hides all toast views. @param includeActivity If `true`, toast activity will also be hidden. Default is `false`. @param clearQueue If `true`, removes all toast views from the queue. Default is `true`. */ func hideAllToasts(includeActivity: Bool = false, clearQueue: Bool = true) { if clearQueue { clearToastQueue() } activeToasts.compactMap { $0 as? UIView } .forEach { hideToast($0) } if includeActivity { hideToastActivity() } } /** Removes all toast views from the queue. This has no effect on toast views that are active. Use `hideAllToasts(clearQueue:)` to hide the active toasts views and clear the queue. */ func clearToastQueue() { queue.removeAllObjects() } // MARK: - Activity Methods /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's position */ func makeToastActivity(_ position: ToastPosition) { // sanity guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return } let toast = createToastActivityView() let point = position.centerPoint(forToast: toast, inSuperview: self) makeToastActivity(toast, point: point) } /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param point The toast's center point */ func makeToastActivity(_ point: CGPoint) { // sanity guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return } let toast = createToastActivityView() makeToastActivity(toast, point: point) } /** Dismisses the active toast activity indicator view. */ func hideToastActivity() { if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - Private Activity Methods private func makeToastActivity(_ toast: UIView, point: CGPoint) { toast.alpha = 0.0 toast.center = point objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { toast.alpha = 1.0 }) } private func createToastActivityView() -> UIView { let style = ToastManager.shared.style let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height)) activityView.backgroundColor = style.activityBackgroundColor activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.layer.cornerRadius = style.cornerRadius if style.displayShadow { activityView.layer.shadowColor = style.shadowColor.cgColor activityView.layer.shadowOpacity = style.shadowOpacity activityView.layer.shadowRadius = style.shadowRadius activityView.layer.shadowOffset = style.shadowOffset } let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge) activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0) activityView.addSubview(activityIndicatorView) activityIndicatorView.color = style.activityIndicatorColor activityIndicatorView.startAnimating() return activityView } // MARK: - Private Show/Hide Methods private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) { toast.center = point toast.alpha = 0.0 if ToastManager.shared.isTapToDismissEnabled { let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(recognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } activeToasts.add(toast) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { toast.alpha = 1.0 }) { _ in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: .common) objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func hideToast(_ toast: UIView, fromTap: Bool) { if let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer { timer.invalidate() } UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() self.activeToasts.remove(toast) if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion { completion(fromTap) } if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue) } } } // MARK: - Events @objc private func handleToastTapped(_ recognizer: UITapGestureRecognizer) { guard let toast = recognizer.view else { return } hideToast(toast, fromTap: true) } @objc private func toastTimerDidFinish(_ timer: Timer) { guard let toast = timer.userInfo as? UIView else { return } hideToast(toast) } // MARK: - Toast Construction /** Creates a new toast view with any combination of message, title, and image. The look and feel is configured via the style. Unlike the `makeToast` methods, this method does not present the toast view automatically. One of the `showToast` methods must be used to present the resulting view. @warning if message, title, and image are all nil, this method will throw `ToastError.missingParameters` @param message The message to be displayed @param title The title @param image The image @param style The style. The shared style will be used when nil @throws `ToastError.missingParameters` when message, title, and image are all nil @return The newly created toast view */ func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity guard message != nil || title != nil || image != nil else { throw ToastError.missingParameters } var messageLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.backgroundColor = style.backgroundColor wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = style.cornerRadius if style.displayShadow { wrapperView.layer.shadowColor = UIColor.black.cgColor wrapperView.layer.shadowOpacity = style.shadowOpacity wrapperView.layer.shadowRadius = style.shadowRadius wrapperView.layer.shadowOffset = style.shadowOffset } if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFit imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height) } var imageRect = CGRect.zero if let imageView = imageView { imageRect.origin.x = style.horizontalPadding imageRect.origin.y = style.verticalPadding imageRect.size.width = imageView.bounds.size.width imageRect.size.height = imageView.bounds.size.height } if let title = title { titleLabel = UILabel() titleLabel?.numberOfLines = style.titleNumberOfLines titleLabel?.font = style.titleFont titleLabel?.textAlignment = style.titleAlignment titleLabel?.lineBreakMode = .byTruncatingTail titleLabel?.textColor = style.titleColor titleLabel?.backgroundColor = UIColor.clear titleLabel?.text = title; let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let titleSize = titleLabel?.sizeThatFits(maxTitleSize) if let titleSize = titleSize { titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height) } } if let message = message { messageLabel = UILabel() messageLabel?.text = message messageLabel?.numberOfLines = style.messageNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textAlignment = style.messageAlignment messageLabel?.lineBreakMode = .byTruncatingTail; messageLabel?.textColor = style.messageColor messageLabel?.backgroundColor = UIColor.clear let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let messageSize = messageLabel?.sizeThatFits(maxMessageSize) if let messageSize = messageSize { let actualWidth = min(messageSize.width, maxMessageSize.width) let actualHeight = min(messageSize.height, maxMessageSize.height) messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) } } var titleRect = CGRect.zero if let titleLabel = titleLabel { titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding titleRect.origin.y = style.verticalPadding titleRect.size.width = titleLabel.bounds.size.width titleRect.size.height = titleLabel.bounds.size.height } var messageRect = CGRect.zero if let messageLabel = messageLabel { messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding messageRect.size.width = messageLabel.bounds.size.width messageRect.size.height = messageLabel.bounds.size.height } let longerWidth = max(titleRect.size.width, messageRect.size.width) let longerX = max(titleRect.origin.x, messageRect.origin.x) let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) if let titleLabel = titleLabel { titleRect.size.width = longerWidth titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageRect.size.width = longerWidth messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } } // MARK: - Toast Style /** `ToastStyle` instances define the look and feel for toast views created via the `makeToast` methods as well for toast views created directly with `toastViewForMessage(message:title:image:style:)`. @warning `ToastStyle` offers relatively simple styling options for the default toast view. If you require a toast view with more complex UI, it probably makes more sense to create your own custom UIView subclass and present it with the `showToast` methods. */ public struct ToastStyle { public init() {} /** The background color. Default is `.black` at 80% opacity. */ public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8) /** The title color. Default is `UIColor.whiteColor()`. */ public var titleColor: UIColor = .white /** The message color. Default is `.white`. */ public var messageColor: UIColor = .white /** A percentage value from 0.0 to 1.0, representing the maximum width of the toast view relative to it's superview. Default is 0.8 (80% of the superview's width). */ public var maxWidthPercentage: CGFloat = 0.8 { didSet { maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0) } } /** A percentage value from 0.0 to 1.0, representing the maximum height of the toast view relative to it's superview. Default is 0.8 (80% of the superview's height). */ public var maxHeightPercentage: CGFloat = 0.8 { didSet { maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0) } } /** The spacing from the horizontal edge of the toast view to the content. When an image is present, this is also used as the padding between the image and the text. Default is 10.0. */ public var horizontalPadding: CGFloat = 10.0 /** The spacing from the vertical edge of the toast view to the content. When a title is present, this is also used as the padding between the title and the message. Default is 10.0. On iOS11+, this value is added added to the `safeAreaInset.top` and `safeAreaInsets.bottom`. */ public var verticalPadding: CGFloat = 10.0 /** The corner radius. Default is 10.0. */ public var cornerRadius: CGFloat = 10.0; /** The title font. Default is `.boldSystemFont(16.0)`. */ public var titleFont: UIFont = .boldSystemFont(ofSize: 16.0) /** The message font. Default is `.systemFont(ofSize: 16.0)`. */ public var messageFont: UIFont = .systemFont(ofSize: 16.0) /** The title text alignment. Default is `NSTextAlignment.Left`. */ public var titleAlignment: NSTextAlignment = .left /** The message text alignment. Default is `NSTextAlignment.Left`. */ public var messageAlignment: NSTextAlignment = .left /** The maximum number of lines for the title. The default is 0 (no limit). */ public var titleNumberOfLines = 0 /** The maximum number of lines for the message. The default is 0 (no limit). */ public var messageNumberOfLines = 0 /** Enable or disable a shadow on the toast view. Default is `false`. */ public var displayShadow = false /** The shadow color. Default is `.black`. */ public var shadowColor: UIColor = .black /** A value from 0.0 to 1.0, representing the opacity of the shadow. Default is 0.8 (80% opacity). */ public var shadowOpacity: Float = 0.8 { didSet { shadowOpacity = max(min(shadowOpacity, 1.0), 0.0) } } /** The shadow radius. Default is 6.0. */ public var shadowRadius: CGFloat = 6.0 /** The shadow offset. The default is 4 x 4. */ public var shadowOffset = CGSize(width: 4.0, height: 4.0) /** The image size. The default is 80 x 80. */ public var imageSize = CGSize(width: 80.0, height: 80.0) /** The size of the toast activity view when `makeToastActivity(position:)` is called. Default is 100 x 100. */ public var activitySize = CGSize(width: 100.0, height: 100.0) /** The fade in/out animation duration. Default is 0.2. */ public var fadeDuration: TimeInterval = 0.2 /** Activity indicator color. Default is `.white`. */ public var activityIndicatorColor: UIColor = .white /** Activity background color. Default is `.black` at 80% opacity. */ public var activityBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8) } // MARK: - Toast Manager /** `ToastManager` provides general configuration options for all toast notifications. Backed by a singleton instance. */ public class ToastManager { /** The `ToastManager` singleton instance. */ public static let shared = ToastManager() /** The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called with with a nil style. */ public var style = ToastStyle() /** Enables or disables tap to dismiss on toast views. Default is `true`. */ public var isTapToDismissEnabled = true /** Enables or disables queueing behavior for toast views. When `true`, toast views will appear one after the other. When `false`, multiple toast views will appear at the same time (potentially overlapping depending on their positions). This has no effect on the toast activity view, which operates independently of normal toast views. Default is `false`. */ public var isQueueEnabled = false /** The default duration. Used for the `makeToast` and `showToast` methods that don't require an explicit duration. Default is 3.0. */ public var duration: TimeInterval = 3.0 /** Sets the default position. Used for the `makeToast` and `showToast` methods that don't require an explicit position. Default is `ToastPosition.Bottom`. */ public var position: ToastPosition = .bottom /** Sets the top offset when making a toast on top. `makeToast` or `showToast` with position set to `ToastPosition.top`. */ public var topOffset: CGFloat = 0 /** Sets the bottom offset when making a toast on bottom. `makeToast` or `showToast` with position set to `ToastPosition.bottom`. */ public var bottomOffset: CGFloat = 0 } // MARK: - ToastPosition public enum ToastPosition { case top case center case bottom fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint { let topPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.top let bottomPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.bottom switch self { case .top: return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + topPadding + ToastManager.shared.topOffset) case .center: return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0) case .bottom: return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding - ToastManager.shared.bottomOffset) } } } // MARK: - Private UIView Extensions private extension UIView { var csSafeAreaInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return self.safeAreaInsets } else { return .zero } } }
39.120907
290
0.651117
01081e95d7627fafb341c96b4292f53226e743df
9,341
// // Created by Kornel on 22/12/2016. // Copyright © 2016 Sparkle Project. All rights reserved. // import Foundation let maxVersionsInFeed = 5 func findElement(name: String, parent: XMLElement) -> XMLElement? { if let found = try? parent.nodes(forXPath: name) { if found.count > 0 { if let element = found[0] as? XMLElement { return element } } } return nil } func findOrCreateElement(name: String, parent: XMLElement) -> XMLElement { if let element = findElement(name: name, parent: parent) { return element } let element = XMLElement(name: name) parent.addChild(element) return element } func text(_ text: String) -> XMLNode { return XMLNode.text(withStringValue: text) as! XMLNode } func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle" var doc: XMLDocument do { let options: XMLNode.Options = [ XMLNode.Options.nodeLoadExternalEntitiesNever, XMLNode.Options.nodePreserveCDATA, XMLNode.Options.nodePreserveWhitespace, ] doc = try XMLDocument(contentsOf: appcastDestPath, options: options) } catch { let root = XMLElement(name: "rss") root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode) root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode) doc = XMLDocument(rootElement: root) doc.isStandalone = true } var channel: XMLElement let rootNodes = try doc.nodes(forXPath: "/rss") if rootNodes.count != 1 { throw makeError(code: .appcastError, "Weird XML? \(appcastDestPath.path)") } let root = rootNodes[0] as! XMLElement let channelNodes = try root.nodes(forXPath: "channel") if channelNodes.count > 0 { channel = channelNodes[0] as! XMLElement } else { channel = XMLElement(name: "channel") channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement) root.addChild(channel) } var numItems = 0 for update in updates { var item: XMLElement let existingItems = try channel.nodes(forXPath: "item[enclosure[@sparkle:version=\"\(update.version)\"]]") let createNewItem = existingItems.count == 0 // Update all old items, but aim for less than 5 in new feeds if createNewItem && numItems >= maxVersionsInFeed { continue } numItems += 1 if createNewItem { item = XMLElement.element(withName: "item") as! XMLElement channel.addChild(item) } else { item = existingItems[0] as! XMLElement } if nil == findElement(name: "title", parent: item) { item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement) } if nil == findElement(name: "pubDate", parent: item) { item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement) } if let html = update.releaseNotesHTML { let descElement = findOrCreateElement(name: "description", parent: item) let cdata = XMLNode(kind: .text, options: .nodeIsCDATA) cdata.stringValue = html descElement.setChildren([cdata]) } var minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item) if nil == minVer { minVer = XMLElement.element(withName: SUAppcastElementMinimumSystemVersion, uri: sparkleNS) as? XMLElement item.addChild(minVer!) } minVer?.setChildren([text(update.minimumSystemVersion)]) let releaseNotesXpath = "\(SUAppcastElementReleaseNotesLink)" let results = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])? .filter { !($0.attributes ?? []) .contains(where: { $0.name == SUXMLLanguage }) } let relElement = results?.first if let url = update.releaseNotesURL { if nil == relElement { item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement) } } else if let childIndex = relElement?.index { item.removeChild(at: childIndex) } let languageNotesNodes = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])? .map { ($0, $0.attribute(forName: SUXMLLanguage)?.stringValue )} .filter { $0.1 != nil } ?? [] for (node, language) in languageNotesNodes.reversed() where !update.localizedReleaseNotes().contains(where: { $0.0 == language }) { item.removeChild(at: node.index) } for (language, url) in update.localizedReleaseNotes() { if !languageNotesNodes.contains(where: { $0.1 == language }) { let localizedNode = XMLNode.element(withName: SUAppcastElementReleaseNotesLink, children: [XMLNode.text(withStringValue: url.lastPathComponent) as! XMLNode], attributes: [XMLNode.attribute(withName: SUXMLLanguage, stringValue: language) as! XMLNode, ]) item.addChild(localizedNode as! XMLNode) } } var enclosure = findElement(name: "enclosure", parent: item) if nil == enclosure { enclosure = XMLElement.element(withName: "enclosure") as? XMLElement item.addChild(enclosure!) } guard let archiveURL = update.archiveURL?.absoluteString else { throw makeError(code: .appcastError, "Bad archive name or feed URL") } var attributes = [ XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeVersion, uri: sparkleNS, stringValue: update.version) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeShortVersionString, uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(update.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: update.mimeType) as! XMLNode, ] if let sig = update.edSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } if let sig = update.dsaSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } enclosure!.attributes = attributes if update.deltas.count > 0 { var deltas = findElement(name: SUAppcastElementDeltas, parent: item) if nil == deltas { deltas = XMLElement.element(withName: SUAppcastElementDeltas, uri: sparkleNS) as? XMLElement item.addChild(deltas!) } else { deltas!.setChildren([]) } for delta in update.deltas { var attributes = [ XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeVersion, uri: sparkleNS, stringValue: update.version) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeShortVersionString, uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeDeltaFrom, uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: "application/octet-stream") as! XMLNode, ] if let sig = delta.edSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } if let sig = delta.dsaSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement) } } } let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint] let docData = doc.xmlData(options: options) _ = try XMLDocument(data: docData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! try docData.write(to: appcastDestPath) }
47.176768
252
0.631089
0819099771cba9b21d2b3214efa964b51fec35a0
989
// // ExtrasHeaderView.swift // InventoryManager // // Created by Alex Grimes on 2/10/20. // Copyright © 2020 Alex Grimes. All rights reserved. // import UIKit class ExtrasHeaderView: UIView { // MARK: - Properties let barImageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: "dragBar") return imageView }() override func layoutSubviews() { super.layoutSubviews() backgroundColor = .white addSubview(barImageView) NSLayoutConstraint.activate([ barImageView.topAnchor.constraint(equalTo: topAnchor, constant: Spacing.four), barImageView.widthAnchor.constraint(equalToConstant: 50), barImageView.centerXAnchor.constraint(equalTo: centerXAnchor), barImageView.heightAnchor.constraint(equalToConstant: 25) ]) } }
26.72973
90
0.658241
fe925102a86f5c471b79f4fbe7470477e0ba8512
8,703
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // // EdgeAnchorGroup+RelationOperators.swift // Layman // // Created by Brian Strobach on 1/4/19. // Copyright © 2019 Brian Strobach. All rights reserved. // // MARK: EdgeAnchorGroup attribute inferred from Anchor // MARK: EdgeAnchorGroup == Anchor @discardableResult public func .= (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroup) -> EdgeAnchorGroup.Solution { return lhs.equal(to: rhs) } // MARK: EdgeAnchorGroup <= Anchor @discardableResult public func ≤ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroup) -> EdgeAnchorGroup.Solution { return lhs.lessThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >= Anchor @discardableResult public func ≥ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroup) -> EdgeAnchorGroup.Solution { return lhs.greaterThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >=< Anchor @discardableResult public func ≥≤ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroup) -> EdgeAnchorGroup.Solution { return lhs.insetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup <=> Anchor @discardableResult public func ≤≥ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroup) -> EdgeAnchorGroup.Solution { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup attribute inferred from Anchor collection // MARK: EdgeAnchorGroup == [Anchor] @discardableResult public func .= (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroup]) -> [EdgeAnchorGroup.Solution] { return lhs.equal(to: rhs) } // MARK: EdgeAnchorGroup <= [Anchor] @discardableResult public func ≤ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroup]) -> [EdgeAnchorGroup.Solution] { return lhs.lessThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >= [Anchor] @discardableResult public func ≥ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroup]) -> [EdgeAnchorGroup.Solution] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >=< [Anchor] @discardableResult public func ≥≤ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroup]) -> [EdgeAnchorGroup.Solution] { return lhs.insetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup <=> [Anchor] @discardableResult public func ≤≥ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroup]) -> [EdgeAnchorGroup.Solution] { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup array attributes inferred from Anchor // MARK: [EdgeAnchorGroup] == Anchor @discardableResult public func .= (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroup) -> [EdgeAnchorGroup.Solution] { return lhs.equal(to: rhs) } // MARK: [EdgeAnchorGroup] <= Anchor @discardableResult public func ≤ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroup) -> [EdgeAnchorGroup.Solution] { return lhs.lessThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >= Anchor @discardableResult public func ≥ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroup) -> [EdgeAnchorGroup.Solution] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >=< Anchor @discardableResult public func ≥≤ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroup) -> [EdgeAnchorGroup.Solution] { return lhs.insetOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] <=> Anchor @discardableResult public func ≤≥ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroup) -> [EdgeAnchorGroup.Solution] { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup array attributes inferred from Anchor collection // MARK: [EdgeAnchorGroup] == [Anchor] @discardableResult public func .= (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroup]) -> [[EdgeAnchorGroup.Solution]] { return lhs.equal(to: rhs) } // MARK: [EdgeAnchorGroup] <= [Anchor] @discardableResult public func ≤ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroup]) -> [[EdgeAnchorGroup.Solution]] { return lhs.lessThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >= [Anchor] @discardableResult public func ≥ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroup]) -> [[EdgeAnchorGroup.Solution]] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >=< [Anchor] @discardableResult public func ≥≤ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroup]) -> [[EdgeAnchorGroup.Solution]] { return lhs.insetOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] <=> [Anchor] @discardableResult public func ≤≥ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroup]) -> [[EdgeAnchorGroup.Solution]] { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup attribute inferred from expression // MARK: EdgeAnchorGroup == Expression @discardableResult public func .= (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroupExpression) -> EdgeAnchorGroup.Solution { return lhs.equal(to: rhs) } // MARK: EdgeAnchorGroup <= Expression @discardableResult public func ≤ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroupExpression) -> EdgeAnchorGroup.Solution { return lhs.lessThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >= Expression @discardableResult public func ≥ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroupExpression) -> EdgeAnchorGroup.Solution { return lhs.greaterThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >=< Expression @discardableResult public func ≥≤ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroupExpression) -> EdgeAnchorGroup.Solution { return lhs.insetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup <=> Expression @discardableResult public func ≤≥ (lhs: EdgeAnchorGroup, rhs: EdgeAnchorGroupExpression) -> EdgeAnchorGroup.Solution { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup attribute inferred from expression collection // MARK: EdgeAnchorGroup == Expressions @discardableResult public func .= (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroupExpression]) -> [EdgeAnchorGroup.Solution] { return lhs.equal(to: rhs) } // MARK: EdgeAnchorGroup <= Expressions @discardableResult public func ≤ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroupExpression]) -> [EdgeAnchorGroup.Solution] { return lhs.lessThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >= Expressions @discardableResult public func ≥ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroupExpression]) -> [EdgeAnchorGroup.Solution] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: EdgeAnchorGroup >=< Expression @discardableResult public func ≥≤ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroupExpression]) -> [EdgeAnchorGroup.Solution] { return lhs.insetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup <=> Expression @discardableResult public func ≤≥ (lhs: EdgeAnchorGroup, rhs: [EdgeAnchorGroupExpression]) -> [EdgeAnchorGroup.Solution] { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup array attributes inferred from Expression // MARK: [EdgeAnchorGroup] == Expression @discardableResult public func .= (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroupExpression) -> [EdgeAnchorGroup.Solution] { return lhs.equal(to: rhs) } // MARK: [EdgeAnchorGroup] <= Expression @discardableResult public func ≤ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroupExpression) -> [EdgeAnchorGroup.Solution] { return lhs.lessThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >= Expression @discardableResult public func ≥ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroupExpression) -> [EdgeAnchorGroup.Solution] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >=< Expression @discardableResult public func ≥≤ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroupExpression) -> [EdgeAnchorGroup.Solution] { return lhs.insetOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] <=> Expression @discardableResult public func ≤≥ (lhs: [EdgeAnchorGroup], rhs: EdgeAnchorGroupExpression) -> [EdgeAnchorGroup.Solution] { return lhs.outsetOrEqual(to: rhs) } // MARK: EdgeAnchorGroup array attributes inferred from expression collection // MARK: [EdgeAnchorGroup] == [Expression] @discardableResult public func .= (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroupExpression]) -> [[EdgeAnchorGroup.Solution]] { return lhs.equal(to: rhs) } // MARK: [EdgeAnchorGroup] <= [Expression] @discardableResult public func ≤ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroupExpression]) -> [[EdgeAnchorGroup.Solution]] { return lhs.lessThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >= [Expression] @discardableResult public func ≥ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroupExpression]) -> [[EdgeAnchorGroup.Solution]] { return lhs.greaterThanOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] >=< [Expression] @discardableResult public func ≥≤ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroupExpression]) -> [[EdgeAnchorGroup.Solution]] { return lhs.insetOrEqual(to: rhs) } // MARK: [EdgeAnchorGroup] <=> [Expression] @discardableResult public func ≤≥ (lhs: [EdgeAnchorGroup], rhs: [EdgeAnchorGroupExpression]) -> [[EdgeAnchorGroup.Solution]] { return lhs.outsetOrEqual(to: rhs) }
32.595506
107
0.738021
9cf57f49ab596b1039c89d9fbb781699981e094c
276
// // CColorerController.swift // CColorer // // Created by Дмитрий Ахмеров on 02.08.2021. // import UIKit open class CColorerViewController: UIViewController { public func CCchange(color: UIColor, forView view: UIView) { view.backgroundColor = color } }
18.4
64
0.699275
5d6b1fa0ec93c29d9d95f4d2464d48e7af8d0269
11,880
import Foundation import RxSwift import Bow import BowEffects /// Witness for the `ObservableK<A>` data type. To be used in simulated Higher Kinded Types. public final class ForObservableK {} /// Partial application of the ObservableK type constructor, omitting the last type parameter. public typealias ObservableKPartial = ForObservableK /// Higher Kinded Type alias to improve readability over `Kind<ForObservableK, A>`. public typealias ObservableKOf<A> = Kind<ForObservableK, A> public extension Observable { /// Creates a higher-kinded version of this object. /// /// - Returns: An `ObservableK` wrapping this object. func k() -> ObservableK<Element> { ObservableK<Element>(self) } } extension Observable { func blockingGet() -> Element? { var result: Element? let flag = Atomic(false) let _ = self.asObservable().subscribe(onNext: { element in if result == nil { result = element } flag.value = true }, onError: { _ in flag.value = true }, onCompleted: { flag.value = true }, onDisposed: { flag.value = true }) while(!flag.value) {} return result } } /// ObservableK is a Higher Kinded Type wrapper over RxSwift's `Observable` data type. public final class ObservableK<A>: ObservableKOf<A> { /// Wrapped `Observable` value. public let value: Observable<A> /// Safe downcast. /// /// - Parameter value: Value in the higher-kind form. /// - Returns: Value cast to ObservableK. public static func fix(_ value: ObservableKOf<A>) -> ObservableK<A> { value as! ObservableK<A> } /// Provides an empty `ObservableK`. /// /// - Returns: An `ObservableK` that does not provide any value. public static func empty() -> ObservableK<A> { Observable.empty().k() } /// Creates an `ObservableK` from the result of evaluating a function, suspending its execution. /// /// - Parameter f: Function providing the value to be provided in the underlying `Observable`. /// - Returns: An `ObservableK` that provides the value obtained from the closure. public static func from(_ f: @escaping () throws -> A) -> ObservableK<A> { ForObservableK.defer { do { return pure(try f()) } catch { return raiseError(error) } }^ } /// Creates an `ObservableK` from the result of evaluating a function, suspending its execution. /// /// - Parameter f: Function providing the value to be provided in the underlying `Observable`. /// - Returns: An `ObservableK` that provides the value obtained from the closure. public static func invoke(_ f: @escaping () throws -> ObservableKOf<A>) -> ObservableK<A> { ForObservableK.defer { do { return try f() } catch { return raiseError(error) } }^ } /// Initializes a value of this type with the underlying `Observable` value. /// /// - Parameter value: Wrapped `Observable` value. public init(_ value: Observable<A>) { self.value = value } /// Wrapper over `Observable.concatMap(_:)`. /// /// - Parameter f: Function to be mapped. /// - Returns: An ObservableK resulting from the application of the function. public func concatMap<B>(_ f: @escaping (A) -> ObservableKOf<B>) -> ObservableK<B> { value.concatMap { a in f(a)^.value }.k() } } /// Safe downcast. /// /// - Parameter value: Value in higher-kind form. /// - Returns: Value cast to ObservableK. public postfix func ^<A>(_ value: ObservableKOf<A>) -> ObservableK<A> { ObservableK.fix(value) } // MARK: Instance of `Functor` for `ObservableK` extension ObservableKPartial: Functor { public static func map<A, B>( _ fa: ObservableKOf<A>, _ f: @escaping (A) -> B) -> ObservableKOf<B> { fa^.value.map(f).k() } } // MARK: Instance of `Applicative` for `ObservableK` extension ObservableKPartial: Applicative { public static func pure<A>(_ a: A) -> ObservableKOf<A> { Observable.just(a).k() } } // MARK: Instance of `Selective` for `ObservableK` extension ObservableKPartial: Selective {} // MARK: Instance of `Monad` for `ObservableK` extension ObservableKPartial: Monad { public static func flatMap<A, B>( _ fa: ObservableKOf<A>, _ f: @escaping (A) -> ObservableKOf<B>) -> ObservableKOf<B> { fa^.value.flatMap { a in f(a)^.value }.k() } public static func tailRecM<A, B>( _ a: A, _ f: @escaping (A) -> ObservableKOf<Either<A, B>>) -> ObservableKOf<B> { _tailRecM(a, f).run() } private static func _tailRecM<A, B>( _ a: A, _ f: @escaping (A) -> ObservableKOf<Either<A, B>>) -> Trampoline<ObservableKOf<B>> { .defer { let either = f(a)^.value.blockingGet()! return either.fold({ a in _tailRecM(a, f)}, { b in .done(Observable.just(b).k()) }) } } } // MARK: Instance of `ApplicativeError` for `ObservableK` extension ObservableKPartial: ApplicativeError { public typealias E = Error public static func raiseError<A>(_ e: Error) -> ObservableKOf<A> { Observable.error(e).k() } public static func handleErrorWith<A>( _ fa: ObservableKOf<A>, _ f: @escaping (Error) -> ObservableKOf<A>) -> ObservableKOf<A> { fa^.value.catchError { e in f(e)^.value }.k() } } // MARK: Instance of `MonadError` for `ObservableK` extension ObservableKPartial: MonadError {} // MARK: Instance of `Foldable` for `ObservableK` extension ObservableKPartial: Foldable { public static func foldLeft<A, B>( _ fa: ObservableKOf<A>, _ b: B, _ f: @escaping (B, A) -> B) -> B { fa^.value.reduce(b, accumulator: f).blockingGet()! } public static func foldRight<A, B>( _ fa: ObservableKOf<A>, _ b: Eval<B>, _ f: @escaping (A, Eval<B>) -> Eval<B>) -> Eval<B> { func loop(_ fa: ObservableK<A>) -> Eval<B> { if let get = fa.value.blockingGet() { return f(get, Eval.defer { loop(fa.value.skip(1).k()) } ) } else { return b } } return Eval.defer { loop(ObservableK.fix(fa)) } } } // MARK: Instance of `Traverse` for `ObservableK` extension ObservableKPartial: Traverse { public static func traverse<G: Applicative, A, B>( _ fa: ObservableKOf<A>, _ f: @escaping (A) -> Kind<G, B>) -> Kind<G, ObservableKOf<B>> { fa.foldRight(Eval.always { G.pure(Observable<B>.empty().k() as ObservableKOf<B>) }, { a, eval in G.map2Eval(f(a), eval, { x, y in Observable.concat(Observable.just(x), y^.value).k() as ObservableKOf<B> }) }).value() } } // MARK: Instance of `MonadDefer` for `ObservableK` extension ObservableKPartial: MonadDefer { public static func `defer`<A>(_ fa: @escaping () -> ObservableKOf<A>) -> ObservableKOf<A> { Observable.deferred { fa()^.value }.k() } } // MARK: Instance of `Async` for `ObservableK` extension ObservableKPartial: Async { public static func asyncF<A>( _ procf: @escaping (@escaping (Either<Error, A>) -> Void) -> ObservableKOf<Void>) -> ObservableKOf<A> { Observable.create { emitter in procf { either in either.fold( { error in emitter.on(.error(error)) }, { value in emitter.on(.next(value)); emitter.on(.completed) }) }^.value.subscribe(onError: { e in emitter.on(.error(e)) }) }.k() } public static func continueOn<A>(_ fa: ObservableKOf<A>, _ queue: DispatchQueue) -> ObservableKOf<A> { fa^.value.observeOn(SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: queue.label)).k() } public static func runAsync<A>(_ fa: @escaping ((Either<ForObservableK.E, A>) -> Void) throws -> Void) -> ObservableKOf<A> { Observable.create { emitter in do { try fa { either in either.fold({ e in emitter.onError(e) }, { a in emitter.onNext(a); emitter.onCompleted() }) } } catch {} return Disposables.create() }.k() } } // MARK: Instance of `Effect` for `ObservableK` extension ObservableKPartial: Effect { public static func runAsync<A>( _ fa: ObservableKOf<A>, _ callback: @escaping (Either<Error, A>) -> ObservableKOf<Void>) -> ObservableKOf<Void> { fa^.value.flatMap { a in callback(Either.right(a))^.value } .catchError { e in callback(Either.left(e))^.value }.k() } } // MARK: Instance of `Concurrent` for `ObservableK` extension ObservableKPartial: Concurrent { public static func race<A, B>( _ fa: ObservableKOf<A>, _ fb: ObservableKOf<B>) -> ObservableKOf<Either<A, B>> { let left = fa.map(Either<A, B>.left)^.value let right = fb.map(Either<A, B>.right)^.value return left.amb(right).k() } public static func parMap<A, B, Z>( _ fa: ObservableKOf<A>, _ fb: ObservableKOf<B>, _ f: @escaping (A, B) -> Z) -> ObservableKOf<Z> { Observable.zip(fa^.value, fb^.value, resultSelector: f).k() } public static func parMap<A, B, C, Z>( _ fa: ObservableKOf<A>, _ fb: ObservableKOf<B>, _ fc: ObservableKOf<C>, _ f: @escaping (A, B, C) -> Z) -> ObservableKOf<Z> { Observable.zip(fa^.value, fb^.value, fc^.value, resultSelector: f).k() } } // MARK: Instance of `ConcurrentEffect` for `ObservableK` extension ObservableKPartial: ConcurrentEffect { public static func runAsyncCancellable<A>( _ fa: ObservableKOf<A>, _ callback: @escaping (Either<ForObservableK.E, A>) -> ObservableKOf<Void>) -> ObservableKOf<BowEffects.Disposable> { Observable.create { _ in let disposable = ObservableK.fix(ObservableK.fix(fa).runAsync(callback)).value.subscribe() return Disposables.create { disposable.dispose() } }.k() } } // MARK: Instance of `Bracket` for `ObservableK` extension ObservableKPartial: Bracket { public static func bracketCase<A, B>( acquire fa: ObservableKOf<A>, release: @escaping (A, ExitCase<Error>) -> ObservableKOf<Void>, use: @escaping (A) throws -> ObservableKOf<B>) -> ObservableKOf<B> { Observable.create { emitter in fa.handleErrorWith { e in ObservableK.from { emitter.on(.error(e)) }.value.flatMap { _ in Observable.error(e) }.k() }^ .concatMap { a in ObservableK.invoke { try use(a)^ } .value .do(onError: { t in _ = ObservableK.defer { release(a, .error(t)) }^.value .subscribe(onNext: { emitter.onError(t) }, onError: { e in emitter.onError(e) }) }, onCompleted: { _ = ObservableK.defer { release(a, .completed) }^.value.subscribe(onNext: { emitter.onCompleted() }, onError: emitter.onError) }, onDispose: { _ = ObservableK.defer { release(a, .canceled) }^.value.subscribe() }).k() }.value.subscribe(onNext: emitter.onNext) }.k() } }
35.675676
158
0.574916
5dd022fdcaa42de2740e8046b2ebb196e97b862f
1,982
// // TitleScene.swift // ios-spritekit-flappy-flying-bird // // Created by Astemir Eleev on 06/05/2018. // Copyright © 2018 Astemir Eleev. All rights reserved. // import SpriteKit class TitleScene: RoutingUtilityScene { // MARK: - Overrides override func didMove(to view: SKView) { super.didMove(to: view) loadSelectedPlayer() let isSoundOn = UserDefaults.standard.bool(for: .isSoundOn) if !isSoundOn { let audioNode = childNode(withName: "Audio Node") as? SKAudioNode audioNode?.isPaused = true audioNode?.removeAllActions() audioNode?.removeFromParent() } } // MARK: - Private methods private func loadSelectedPlayer() { guard let targetNode = childNode(withName: "Animated Bird") else { return } let playableCharacter = UserDefaults.standard.playableCharacter(for: .character) ?? .bird let assetName = playableCharacter.getAssetName() let playerSize = CGSize(width: 200, height: 200) switch playableCharacter { case .bird: let birdNode = BirdNode(animationTimeInterval: 0.1, withTextureAtlas: assetName, size: playerSize) birdNode.isAffectedByGravity = false birdNode.position = targetNode.position birdNode.zPosition = targetNode.zPosition scene?.addChild(birdNode) case .coinCat, .gamecat, .hipCat, .jazzCat, .lifelopeCat: let player = NyancatNode(animatedGif: assetName, correctAspectRatioFor: playerSize.width) player.xScale = 1.0 player.yScale = 1.0 player.isAffectedByGravity = false player.position = targetNode.position player.zPosition = targetNode.zPosition scene?.addChild(player) } targetNode.removeFromParent() } }
31.460317
110
0.606458
095b390f5429ca5085ff7e430cf5d78c00826945
1,927
// ---------------------------------------------------------------------------- // // LogcatLogger.Debug.swift // // @author Alexander Bragin <[email protected]> // @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved. // @link https://www.roxiemobile.com/ // // ---------------------------------------------------------------------------- import OSLog import SwiftCommonsLang // ---------------------------------------------------------------------------- extension LogcatLogger { // MARK: - Methods /// Formats and sends a debug log message. /// /// - Parameters: /// - tag: Used to identify the source of a log message. It usually identifies the class /// where the log call occurs. /// - message: The message you would like logged. /// - file: The file name. The default is the file where function is called. /// - line: The line number. The default is the line number where function is called. /// public func d(_ tag: String, _ message: String, file: StaticString = #file, line: UInt = #line) { let level = Logger.LogLevel.debug if Logger.isLoggable(level) { os_log("%@", type: .info, Logger.description(level, tag, message)) } } /// Formats and sends a debug log message. /// /// - Parameters: /// - type: Used to identify the source of a log message. It usually identifies the class /// where the log call occurs. /// - message: The message you would like logged. /// - file: The file name. The default is the file where function is called. /// - line: The line number. The default is the line number where function is called. /// public func d(_ type: Any.Type, _ message: String, file: StaticString = #file, line: UInt = #line) { d(Reflection(of: type).type.fullName, message, file: file, line: line) } }
39.326531
104
0.548521
bbbdd4a5ff29055aa2b46effb248a42797de3206
1,500
// // File.swift // // // Created by Alan Chu on 9/13/20. // import GeohashKit import NationalWeatherService extension WXPNationalWeatherService { public static var region: Set<Geohash.Hash> { return [ // Lower 48th "c0", "f0", "f2", "f8", "9p", "9r", "9x", "9z", "dp", "dr", "9n", "9q", "9w", "9y", "dn", "dq", "9m", "9t", "9v", "dj", "9u", "dh", // Below 49th parallel, up to Wisconsin-ish "c28", "c29", "c2d", "c2e", "c2s", "c2t", "c2w", "c2x", "c88", "c89", "c8d", "c8e", "c8s", "c8t", "c8w", "c8x", "cb8", "cb9", "cbd", "cbe", "cbs", "cbt", "cbw", "cbx", "c22", "c23", "c26", "c27", "c2k", "c2m", "c2q", "c2r", "c82", "c83", "c86", "c87", "c8k", "c8m", "c8q", "c8r", "cb2", "cb3", "cb6", "cb7", "cbk", "cbm", "cbq", "cbr", "c20", "c21", "c24", "c25", "c2h", "c2j", "c2n", "c2p", "c80", "c81", "c84", "c85", "c8h", "c8j", "c8n", "c8p", "cb0", "cb1", "cb4", "cb5", "cbh", "cbj", "cbn", "cbp", // Maine exclave "f2j", "f2n", "f2p", "f80", "f2q", "f2r", // Alaska "bk", "bs", "bu", "b5", "b7", "be", "bg", "b6", "bd", "bf", "c4", "c1", "zc", "b1", "b3", // Hawaii "87", "8e" ] } // TODO: DRY this static var trie: Trie = { let trie = Trie() region.forEach { trie.insert(word: $0) } return trie }() }
31.914894
77
0.404
e4301b0d4ef68b2240b957bdad97c1d13efeb9de
1,614
import UIKit open class Label: UILabel { public typealias Action = (Label) -> Swift.Void fileprivate var actionOnTouch: Action? open var insets: UIEdgeInsets = .zero override open func drawText(in rect: CGRect) { // super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) super.drawText(in: rect.inset(by: insets)) } // Override -intrinsicContentSize: for Auto layout code override open var intrinsicContentSize: CGSize { var contentSize = super.intrinsicContentSize contentSize.height += insets.top + insets.bottom contentSize.width += insets.left + insets.right return contentSize } // Override -sizeThatFits: for Springs & Struts code override open func sizeThatFits(_ size: CGSize) -> CGSize { var contentSize = super.sizeThatFits(size) contentSize.height += insets.top + insets.bottom contentSize.width += insets.left + insets.right return contentSize } public func action(_ closure: @escaping Action) { Log("action did set") if actionOnTouch == nil { let gesture = UITapGestureRecognizer( target: self, action: #selector(Label.actionOnTouchUpInside)) gesture.numberOfTapsRequired = 1 gesture.numberOfTouchesRequired = 1 self.addGestureRecognizer(gesture) self.isUserInteractionEnabled = true } self.actionOnTouch = closure } @objc internal func actionOnTouchUpInside() { actionOnTouch?(self) } }
32.28
65
0.635068
acdeae36c69327110c1ae37d2707649aa94f1f8a
15,061
// // Quote.swift // StripeKit // // Created by Andrew Edwards on 7/25/21. // import Foundation /// A Quote is a way to model prices that you'd like to provide to a customer. Once accepted, it will automatically create an invoice, subscription or subscription schedule. public struct StripeQuote: StripeModel { /// Unique identifier for the object. public var id: String /// String representing the object’s type. Objects of the same type share the same value. public var object: String /// This field is not included by default. To include it in the response, expand the `line_items` field. public var lineItems: StripeQuoteLineItemList? /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. public var metadata: [String: String]? /// Total before any discounts or taxes are applied. public var amountSubtotal: Int? /// Total after discounts and taxes are applied. public var amountTotal: Int? /// The amount of the application fee (if any) that will be requested to be applied to the payment and transferred to the application owner’s Stripe account. Only applicable if there are no line items with recurring prices on the quote. public var applicationFeeAmount: Int? /// A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account. Only applicable if there are line items with recurring prices on the quote. public var applicationFeePercent: String? /// Settings for automatic tax lookup for this quote and resulting invoices and subscriptions. public var automaticTax: StripeQuoteAutomaticTax? /// Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay invoices at the end of the subscription cycle or on finalization using the default payment method attached to the subscription or customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions. Defaults to `charge_automatically`. public var collectionMethod: String? /// The definitive totals and line items for the quote, computed based on your inputted line items as well as other configuration such as trials. Used for rendering the quote to your customer. public var computed: StripeQuoteComputed? /// Time at which the object was created. Measured in seconds since the Unix epoch. public var created: Date /// Three-letter ISO currency code, in lowercase. Must be a supported currency. public var currency: StripeCurrency? /// The tax rates applied to this quote. public var defaultTaxRates: [String]? /// A description that will be displayed on the quote PDF. public var description: String? /// The discounts applied to this quote. public var discounts: [String]? /// The date on which the quote will be canceled if in `open` or `draft` status. Measured in seconds since the Unix epoch. public var expiresAt: Date? /// A footer that will be displayed on the quote PDF. public var footer: String? /// Details of the quote that was cloned. See the cloning documentation for more details. public var fromQuote: StripeQuoteFromQuote? /// A header that will be displayed on the quote PDF. public var header: String? @Expandable<StripeInvoice> public var invoice: String? /// All invoices will be billed using the specified settings. public var invoiceSettings: StripeQuoteInvoiceSettings? /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. public var livemode: Bool /// A unique number that identifies this particular quote. This number is assigned once the quote is finalized. public var number: String? /// The account on behalf of which to charge. See the Connect documentation for details. @Expandable<StripeConnectAccount> public var onBehalfOf: String? /// The status of the quote. public var status: StripeQuoteStatus? /// The timestamps of which the quote transitioned to a new status. public var statusTransitions: StripeQuoteStatusTransition? /// The subscription that was created or updated from this quote. @Expandable<StripeSubscription> public var subscription: String? /// When creating a subscription or subscription schedule, the specified configuration data will be used. There must be at least one line item with a recurring price for a subscription or subscription schedule to be created. public var subscriptionData: StripeQuoteSubscriptionData? /// The subscription schedule that was created or updated from this quote. @Expandable<StripeSubscriptionSchedule> public var subscriptionSchedule: String? /// Tax and discount details for the computed total amount. public var totalDetails: StripeQuoteTotalDetails? /// The account (if any) the payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the invoices. public var transferData: StripeQuoteTransferData? } public struct StripeQuoteAutomaticTax: StripeModel { /// Automatically calculate taxes public var enabled: Bool /// The status of the most recent automated tax calculation for this quote. public var status: StripeQuoteAutomaticTaxStatus? } public enum StripeQuoteAutomaticTaxStatus: String, StripeModel { /// The location details supplied on the customer aren’t valid or don’t provide enough location information to accurately determine tax rates for the customer. case requiresLocationInputs = "requires_location_inputs" /// Stripe successfully calculated tax automatically on this quote. case complete /// The Stripe Tax service failed, please try again later. case failed } public enum StripeQuoteCollectionMethod: String, StripeModel { case chargeAutomatically = "charge_automatically" case sendInvoice = "send_invoice" } public struct StripeQuoteComputed: StripeModel { /// The definitive totals and line items the customer will be charged on a recurring basis. Takes into account the line items with recurring prices and discounts with `duration=forever` coupons only. Defaults to null if no inputted line items with recurring prices. public var recurring: StripeQuoteComputedRecurring? /// The definitive upfront totals and line items the customer will be charged on the first invoice. public var upfront: StripeQuoteComputedUpfront? } public struct StripeQuoteComputedRecurring: StripeModel { /// Total before any discounts or taxes are applied. public var amountSubtotal: Int? /// Total after discounts and taxes are applied. public var amountTotal: Int? /// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`. public var interval: StripePlanInterval? /// The number of intervals (specified in the `interval` attribute) between subscription billings. For example, `interval=month` and `interval_count=3` bills every 3 months. public var intervalCount: Int? /// Tax and discount details for the computed total amount. public var totalDetails: StripeQuoteComputedRecurringTotalDetails? } public struct StripeQuoteComputedRecurringTotalDetails: StripeModel { /// This is the sum of all the line item discounts. public var amountDiscount: Int? /// This is the sum of all the line item shipping amounts. public var amountShipping: Int? /// This is the sum of all the line item tax amounts. public var amountTax: Int? /// Breakdown of individual tax and discount amounts that add up to the totals. /// /// This field is not included by default. To include it in the response, expand the `breakdown` field. public var breakdown: StripeQuoteComputedRecurringTotalDetailsBreakdown? } public struct StripeQuoteComputedRecurringTotalDetailsBreakdown: StripeModel { /// The aggregated line item discounts. public var discounts: [StripeQuoteComputedRecurringTotalDetailsBreakdownDiscount]? /// The aggregated line item tax amounts by rate. public var taxes: [StripeQuoteComputedRecurringTotalDetailsBreakdownTax]? } public struct StripeQuoteComputedRecurringTotalDetailsBreakdownDiscount: StripeModel { /// The amount discounted. public var amount: Int? /// The discount applied. public var discount: StripeDiscount? } public struct StripeQuoteComputedRecurringTotalDetailsBreakdownTax: StripeModel { /// Amount of tax applied for this rate. public var amount: Int? /// The tax rate applied. public var rate: StripeTaxRate? } public struct StripeQuoteComputedUpfront: StripeModel { /// Total before any discounts or taxes are applied. public var amountSubtotal: Int? /// Total after discounts and taxes are applied. public var amountTotal: Int? /// The line items that will appear on the next invoice after this quote is accepted. This does not include pending invoice items that exist on the customer but may still be included in the next invoice. /// /// This field is not included by default. To include it in the response, expand the `line_items` field. public var lineItems: StripeQuoteLineItemList? /// Tax and discount details for the computed total amount. public var totalDetails: StripeQuoteComputedUpfrontTotalDetails? } public struct StripeQuoteComputedUpfrontTotalDetails: StripeModel { /// This is the sum of all the line item discounts. public var amountDiscount: Int? /// This is the sum of all the line item shipping amounts. public var amountShipping: Int? /// This is the sum of all the line item tax amounts. public var amountTax: Int? /// Breakdown of individual tax and discount amounts that add up to the totals. /// /// This field is not included by default. To include it in the response, expand the `breakdown` field. public var breakdown: StripeQuoteComputedUpfrontTotalDetailsBreakdown? } public struct StripeQuoteComputedUpfrontTotalDetailsBreakdown: StripeModel { /// The aggregated line item discounts. public var discounts: [StripeQuoteComputedUpfrontTotalDetailsBreakdownDiscount]? /// The aggregated line item tax amounts by rate. public var taxes: [StripeQuoteComputedUpfrontTotalDetailsBreakdownTax]? } public struct StripeQuoteComputedUpfrontTotalDetailsBreakdownDiscount: StripeModel { /// The amount discounted. public var amount: Int? /// The discount applied. public var discount: StripeDiscount? } public struct StripeQuoteComputedUpfrontTotalDetailsBreakdownTax: StripeModel { /// Amount of tax applied for this rate. public var amount: Int? /// The tax rate applied. public var rate: StripeTaxRate? } public struct StripeQuoteFromQuote: StripeModel { /// Whether this quote is a revision of a different quote. public var isRevision: Bool? /// The quote that was cloned. @Expandable<StripeQuote> public var quote: String? } public struct StripeQuoteInvoiceSettings: StripeModel { /// Number of days within which a customer must pay invoices generated by this quote. This value will be null for quotes where `collection_method=charge_automatically`. public var daysUntilDue: Int? } public enum StripeQuoteStatus: String, StripeModel { /// The quote can be edited while in this status and has not been sent to the customer. case draft /// The quote has been finalized and is awaiting action from the customer. case open /// The customer has accepted the quote and invoice, subscription or subscription schedule has been created. case accepted /// The quote has been canceled and is no longer valid. case canceled } public struct StripeQuoteStatusTransition: StripeModel { /// The time that the quote was accepted. Measured in seconds since Unix epoch. public var acceptedAt: Date? /// The time that the quote was canceled. Measured in seconds since Unix epoch. public var canceledAt: Date? /// The time that the quote was finalized. Measured in seconds since Unix epoch. public var finalizedAt: Date? } public struct StripeQuoteSubscriptionData: StripeModel { /// When creating a new subscription, the date of which the subscription schedule will start after the quote is accepted. This date is ignored if it is in the past when the quote is accepted. Measured in seconds since the Unix epoch. public var effectiveDate: Date? /// Integer representing the number of trial period days before the customer is charged for the first time. public var trialPeriodDays: Int? } public struct StripeQuoteTotalDetails: StripeModel { /// This is the sum of all the line item discounts. public var amountDiscount: Int? /// This is the sum of all the line item shipping amounts. public var amountShipping: Int? /// This is the sum of all the line item tax amounts. public var amountTax: Int? /// Breakdown of individual tax and discount amounts that add up to the totals. /// /// This field is not included by default. To include it in the response, expand the `breakdown` field. public var breakdown: StripeQuoteTotalDetailsBreakdown? } public struct StripeQuoteTotalDetailsBreakdown: StripeModel { /// The aggregated line item discounts. public var discounts: [StripeQuoteTotalDetailsBreakdownDiscount]? /// The aggregated line item tax amounts by rate. public var taxes: [StripeQuoteTotalDetailsBreakdownTax]? } public struct StripeQuoteTotalDetailsBreakdownDiscount: StripeModel { /// The amount discounted. public var amount: Int? /// The discount applied. public var discount: StripeDiscount? } public struct StripeQuoteTotalDetailsBreakdownTax: StripeModel { /// Amount of tax applied for this rate. public var amount: Int? /// The tax rate applied. public var rate: StripeTaxRate? } public struct StripeQuoteTransferData: StripeModel { /// The amount in cents that will be transferred to the destination account when the invoice is paid. By default, the entire amount is transferred to the destination. public var amount: Int? /// A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice subtotal that will be transferred to the destination account. By default, the entire amount will be transferred to the destination. public var amountPercent: String? /// The account where funds from the payment will be transferred to upon payment success. @Expandable<StripeConnectAccount> public var destination: String? } public struct StripeQuoteList: StripeModel { public var object: String public var hasMore: Bool? public var url: String? public var data: [StripeQuoteLineItem]? }
52.477352
384
0.754996
d652901ac902b252bea9cc785973c423b01a03f8
1,453
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// import XCTest import AsyncAlgorithms final class TestSetAlgebra: XCTestCase { func test_Set() async { let source = [1, 2, 3] let expected = Set(source) let actual = await Set(source.async) XCTAssertEqual(expected, actual) } func test_Set_duplicate() async { let source = [1, 2, 3, 3] let expected = Set(source) let actual = await Set(source.async) XCTAssertEqual(expected, actual) } func test_IndexSet() async { let source = [1, 2, 3] let expected = IndexSet(source) let actual = await IndexSet(source.async) XCTAssertEqual(expected, actual) } func test_throwing() async { let source = Array([1, 2, 3, 4, 5, 6]) let input = source.async.map { (value: Int) async throws -> Int in if value == 4 { throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil) } return value } do { _ = try await Set(input) XCTFail() } catch { XCTAssertEqual((error as NSError).code, -1) } } }
28.490196
90
0.580179
feea5faa8d08714729c41978bd4a0acecad5fef0
37,864
/* * SwiftLocation * Easy and Efficent Location Tracker for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation import MapKit import CoreLocation /// Singleton instance for location tracker public let Location = LocationTracker.shared /// Location tracker class public final class LocationTracker: NSObject, CLLocationManagerDelegate { public typealias RequestPoolDidChange = ((Any) -> (Void)) public typealias LocationTrackerSettingsDidChange = ((TrackerSettings) -> (Void)) public typealias LocationDidChange = ((CLLocation) -> (Void)) /// This is a reference to LocationManager's singleton where the main queue for Requests. static let shared : LocationTracker = { // CLLocationManager must be created on main thread otherwise // it will generate an error at init time. if Thread.isMainThread { return LocationTracker() } else { return DispatchQueue.main.sync { return LocationTracker() } } }() /// Initialize func private override init() { self.locationManager = CLLocationManager() super.init() self.locationManager.delegate = self // Listen for any change (add or remove) into all queues let onAddHandler: ((Any) -> (Void)) = { self.onAddNewRequest?($0) } let onRemoveHandler: ((Any) -> (Void)) = { self.onRemoveRequest?($0) } for var pool in self.pools { pool.onAdd = onAddHandler pool.onRemove = onRemoveHandler } } public override var description: String { let countRunning: Int = self.pools.reduce(0, { $0 + $1.countRunning }) let countPaused: Int = self.pools.reduce(0, { $0 + $1.countPaused }) let countAll: Int = self.pools.reduce(0, { $0 + $1.count }) var status = "Requests: \(countRunning)/\(countAll) (\(countPaused) paused)" if let settings = self.locationSettings { status += "\nSettings:\(settings)" } else { status += "\nSettings: services off" } return status } /// Callback called when a new request is added public var onAddNewRequest: RequestPoolDidChange? = nil /// Callback called when a request was removed public var onRemoveRequest: RequestPoolDidChange? = nil /// Called when location manager settings did change public var onChangeTrackerSettings: LocationTrackerSettingsDidChange? = nil /// On Receive new location public var onReceiveNewLocation: LocationDidChange? = nil /// Internal location manager reference internal var locationManager: CLLocationManager /// Queued requests regarding location services private var locationRequests: RequestsQueue<LocationRequest> = RequestsQueue() /// Queued requests regarding reverse geocoding services private var geocoderRequests: RequestsQueue<GeocoderRequest> = RequestsQueue() /// Queued requests regarding heading services private var headingRequests: RequestsQueue<HeadingRequest> = RequestsQueue() /// Queued requests regarding region monitor services private var regionRequests: RequestsQueue<RegionRequest> = RequestsQueue() /// Queued requests regarding visits private var visitRequests: RequestsQueue<VisitsRequest> = RequestsQueue() /// This represent the status of the authorizations before a change private var lastStatus: CLAuthorizationStatus = CLAuthorizationStatus.notDetermined /// `true` if location is deferred private(set) var isDeferred: Bool = false /// This represent the last locations received (best accurated location and last received location) public private(set) var lastLocation = LastLocation() /// Active CoreLocation settings based upon running requests private var _locationSettings: TrackerSettings? private(set) var locationSettings: TrackerSettings? { set { guard let settings = newValue else { locationManager.stopAllLocationServices() _locationSettings = newValue return } if _locationSettings == newValue { return // ignore equal settings, avoid multiple sets } _locationSettings = newValue // Set attributes for CLLocationManager instance locationManager.activityType = settings.activity // activity type (used to better preserve battery based upon activity) locationManager.desiredAccuracy = settings.accuracy.level // accuracy (used to preserve battery based upon update frequency) locationManager.distanceFilter = settings.distanceFilter self.onChangeTrackerSettings?(settings) switch settings.frequency { case .significant: guard CLLocationManager.significantLocationChangeMonitoringAvailable() else { locationManager.stopAllLocationServices() return } // If best frequency is significant location update (and hardware supports it) then start only significant location update locationManager.stopUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = true locationManager.startMonitoringSignificantLocationChanges() case .deferredUntil(_,_,_): locationManager.stopMonitoringSignificantLocationChanges() locationManager.allowsBackgroundLocationUpdates = true locationManager.startUpdatingLocation() default: locationManager.stopMonitoringSignificantLocationChanges() locationManager.allowsBackgroundLocationUpdates = false locationManager.startUpdatingLocation() locationManager.disallowDeferredLocationUpdates() } } get { return _locationSettings } } /// Asks whether the heading calibration alert should be displayed. /// This method is called in an effort to calibrate the onboard hardware used to determine heading values. /// Typically at the following times: /// - The first time heading updates are ever requested /// - When Core Location observes a significant change in magnitude or inclination of the observed magnetic field /// /// If true from this method, Core Location displays the heading calibration alert on top of the current window. /// The calibration alert prompts the user to move the device in a particular pattern so that Core Location can /// distinguish between the Earth’s magnetic field and any local magnetic fields. /// The alert remains visible until calibration is complete or until you explicitly dismiss it by calling the /// dismissHeadingCalibrationDisplay() method. public var displayHeadingCalibration: Bool = true /// When `true` this property is a good way to improve battery life. /// This function also scan for any running Request's `activityType` and see if location data is unlikely to change. /// If yes (for example when user stops for food while using a navigation app) the location manager might pause updates /// for a period of time. /// By default is set to `false`. public var autoPauseUpdates: Bool = false { didSet { locationManager.pausesLocationUpdatesAutomatically = autoPauseUpdates } } /// The device orientation to use when computing heading values. /// When computing heading values, the location manager assumes that the top of the device in portrait mode represents /// due north (0 degrees) by default. For apps that run in other orientations, this may not always be the most convenient /// orientation. /// /// This property allows you to specify which device orientation you want the location manager to use as the reference /// point for due north. /// /// Although you can set the value of this property to unknown, faceUp, or faceDown, doing so has no effect on the /// orientation reference point. The original reference point is retained instead. /// Changing the value in this property affects only those heading values reported after the change is made. public var headingOrientation: CLDeviceOrientation { set { locationManager.headingOrientation = headingOrientation } get { return locationManager.headingOrientation } } /// You can use this method to dismiss it after an appropriate amount of time to ensure that your app’s user interface /// is not unduly disrupted. public func dismissHeadingCalibrationDisplay() { locationManager.dismissHeadingCalibrationDisplay() } // MARK: - Get location /// Create and enque a new location tracking request /// /// - Parameters: /// - accuracy: accuracy of the location request (it may affect device's energy consumption) /// - frequency: frequency of the location retrive process (it may affect device's energy consumption) /// - timeout: optional timeout. If no location were found before timeout a `LocationError.timeout` error is reported. /// - success: success handler to call when a new location were found for this request /// - error: error handler to call when an error did occour while searching for request /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - Returns: request @discardableResult public func getLocation(accuracy: Accuracy, frequency: Frequency, timeout: TimeInterval? = nil, cancelOnError: Bool = false, success: @escaping LocObserver.onSuccess, error: @escaping LocObserver.onError) -> LocationRequest { let req = LocationRequest(accuracy: accuracy, frequency: frequency, success, error) req.timeout = timeout req.cancelOnError = cancelOnError req.resume() return req } /// Create and enqueue a new reverse geocoding request for an input address string /// /// - Parameters: /// - address: address string to reverse /// - region: A geographical region to use as a hint when looking up the specified address. /// Specifying a region lets you prioritize the returned set of results to locations that are close to some /// specific geographical area, which is typically the user’s current location. /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getLocation(forAddress address: String, inRegion region: CLRegion? = nil, timeout: TimeInterval? = nil, cancelOnError: Bool = false, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(address: address, region: region, success, failure) req.timeout = timeout req.cancelOnError = cancelOnError req.resume() return req } /// Create and enqueue a new reverse geocoding request for an instance of `CLLocation` object. /// /// - Parameters: /// - location: location to reverse /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getPlacemark(forLocation location: CLLocation, timeout: TimeInterval? = nil, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(location: location, success, failure) req.timeout = timeout req.resume() return req } /// Create and enqueue a new reverse geocoding request for an Address Book `Dictionary` object. /// /// - Parameters: /// - dict: address book dictionary /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getLocation(forABDictionary dict: [AnyHashable: Any], timeout: TimeInterval? = nil, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(abDictionary: dict, success, failure) req.timeout = timeout req.resume() return req } // MARK: - Get heading /// Allows you to receive heading update with a minimum filter degree /// /// - Parameters: /// - filter: The minimum angular change (measured in degrees) required to generate new heading events. /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - success: succss handler /// - failure: failure handler /// - Returns: request @discardableResult public func getContinousHeading(filter: CLLocationDegrees, cancelOnError: Bool = false, success: @escaping HeadingObserver.onSuccess, failure: @escaping HeadingObserver.onError) throws -> HeadingRequest { let request = try HeadingRequest(filter: filter, success: success, failure: failure) request.resume() request.cancelOnError = cancelOnError return request } // MARK: - Monitor geographic location /// Monitor a geographic region identified by a center coordinate and a radius. /// Region monitoring /// /// - Parameters: /// - center: coordinate center /// - radius: radius in meters /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - enter: callback for region enter event /// - exit: callback for region exit event /// - error: callback for errors /// - Returns: request /// - Throws: throw `LocationError.serviceNotAvailable` if hardware does not support region monitoring @discardableResult public func monitor(regionAt center: CLLocationCoordinate2D, radius: CLLocationDistance, cancelOnError: Bool = false, enter: RegionObserver.onEvent?, exit: RegionObserver.onEvent?, error: @escaping RegionObserver.onFailure) throws -> RegionRequest { let request = try RegionRequest(center: center, radius: radius, onEnter: enter, onExit: exit, error: error) request.resume() request.cancelOnError = cancelOnError return request } /// Monitor a specified region /// /// - Parameters: /// - region: region to monitor /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - enter: callback for region enter event /// - exit: callback for region exit event /// - error: callback for errors /// - error: callback for errors /// - Throws: throw `LocationError.serviceNotAvailable` if hardware does not support region monitoring @discardableResult public func monitor(region: CLCircularRegion, cancelOnError: Bool = false, enter: RegionObserver.onEvent?, exit: RegionObserver.onEvent?, error: @escaping RegionObserver.onFailure) throws -> RegionRequest { let request = try RegionRequest(region: region, onEnter: enter, onExit: exit, error: error) request.cancelOnError = cancelOnError request.resume() return request } /// Calling this method begins the delivery of visit-related events to your app. /// Enabling visit events for one location manager enables visit events for all other location manager objects in your app. /// When a new visit event arrives callback is called and request still alive until removed. /// This service require always authorization. /// /// - Parameters: /// - event: callback called when a new visit arrive /// - error: callback called when an error occours /// - Returns: request /// - Throws: throw an exception if app does not support alway authorization @discardableResult public func monitorVisit(event: @escaping VisitObserver.onVisit, error: @escaping VisitObserver.onFailure) throws -> VisitsRequest { let request = try VisitsRequest(event: event, error: error) request.resume() return request } //MARK: - Register/Unregister location requests /// Register a new request and enqueue it /// /// - Parameter request: request to enqueue /// - Returns: `true` if added correctly to the queue, `false` otherwise. public func start<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { // Location Requests if let request = request as? LocationRequest { request._state = .running if locationRequests.add(request) { hasChanges = true } } // Geocoder Requests if let request = request as? GeocoderRequest { request._state = .running if geocoderRequests.add(request) { hasChanges = true } } // Heading requests if let request = request as? HeadingRequest { request._state = .running if headingRequests.add(request) { hasChanges = true } } // Region Monitoring requests if let request = request as? RegionRequest { request._state = .running if regionRequests.add(request) { hasChanges = true } } } if hasChanges { requests.forEach { $0.onResume() } self.updateServicesStatus() } } /// Unregister and stops a queued request /// /// - Parameter request: request to remove /// - Returns: `true` if request was removed successfully, `false` if it's not part of the queue public func cancel<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { if self.isQueued(request) == false { continue } // Location Requests if let request = request as? LocationRequest { request._state = .idle locationRequests.remove(request) hasChanges = true } // Geocoder requests if let request = request as? GeocoderRequest { request._state = .idle geocoderRequests.remove(request) hasChanges = true } // Heading requests if let request = request as? HeadingRequest { request._state = .idle headingRequests.remove(request) hasChanges = true } // Region Monitoring requests if let request = request as? RegionRequest { request._state = .idle locationManager.stopMonitoring(for: request.region) regionRequests.remove(request) hasChanges = true } } if hasChanges == true { self.updateServicesStatus() requests.forEach { $0.onCancel() } } } /// Pause any passed queued reques /// /// - Parameter requests: requests to pause public func pause<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { if self.isQueued(request) == false { continue } if self.isQueued(request) && request.state.isRunning { // Location requests if let request = request as? LocationRequest { request._state = .paused hasChanges = true } // Geocoder requests if let request = request as? GeocoderRequest { request._state = .paused hasChanges = true } // Heading requests if let request = request as? HeadingRequest { request._state = .paused hasChanges = true } // Region Monitoring requests if let request = request as? RegionRequest { locationManager.stopMonitoring(for: request.region) request._state = .paused hasChanges = true } } } if hasChanges == true { self.updateServicesStatus() requests.forEach { $0.onPause() } } } /// Return `true` if target `request` is part of a queue. /// /// - Parameter request: target request /// - Returns: `true` if request is in a queue, `false` otherwise internal func isQueued<T: Request>(_ request: T?) -> Bool { guard let request = request else { return false } // Location Request if let request = request as? LocationRequest { return locationRequests.isQueued(request) } // Geocoder Request if let request = request as? GeocoderRequest { return geocoderRequests.isQueued(request) } // Heading Request if let request = request as? HeadingRequest { return headingRequests.isQueued(request) } // Region Request if let request = request as? RegionRequest { return regionRequests.isQueued(request) } return false } //MARK: CLLocationManager Visits Delegate public func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) { self.visitRequests.dispatch(value: visit) } //MARK: CLLocationManager Region Monitoring Delegate public func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.onStartMonitoring?() } public func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(error: error) } public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(event: .entered) } public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(event: .exited) } public func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(state: state) } //MARK: - Internal Heading Manager Func public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { self.headingRequests.dispatch(value: newHeading) } public func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool { return self.displayHeadingCalibration } //MARK: Internal Location Manager Func /// Set the request's `state` for any queued requests which is in one the following states /// /// - Parameters: /// - newState: new state to set /// - states: request's allowed state to be changed private func loc_setRequestState(_ newState: RequestState, forRequestsIn states: Set<RequestState>) { locationRequests.forEach { if states.contains($0.state) { $0._state = newState } } } //MARK: - Deferred Location Helper Funcs private var isDeferredAvailable: Bool { // Seems `deferredLocationUpdatesAvailable()` function does not work properly in iOS 10 // It's not clear if it's a bug or not. // Som elinks about the topic: // https://github.com/zakishaheen/deferred-location-implementation // http://stackoverflow.com/questions/39498899/deferredlocationupdatesavailable-returns-no-in-ios-10 // https://github.com/lionheart/openradar-mirror/issues/15939 // // Moreover activating deferred locations causes didFinishDeferredUpdatesWithError to be called with kCLErrorDeferredFailed if #available(iOS 10, *) { return true } else { return CLLocationManager.deferredLocationUpdatesAvailable() } } /// Evaluate deferred location best settings /// /// - Returns: settings to apply private func deferredLocationSettings() -> (meters: Double, timeout: TimeInterval, accuracy: Accuracy)? { var meters: Double? = nil var timeout: TimeInterval? = nil var accuracyIsNavigation: Bool = false self.locationRequests.forEach { if case let .deferredUntil(rMt,rTime,rAcc) = $0.frequency { if meters == nil || (rMt < meters!) { meters = rMt } if timeout == nil || (rTime < timeout!) { timeout = rTime } if rAcc == true { accuracyIsNavigation = true } } } let accuracy = (accuracyIsNavigation ? Accuracy.navigation : Accuracy.room) return (meters == nil ? nil : (meters!,timeout!, accuracy)) } /// Turn on and off deferred location updated if needed private func turnOnOrOffDeferredLocationUpdates() { // Turn on/off deferred location updates if let defSettings = deferredLocationSettings() { if self.isDeferred == false { locationManager.desiredAccuracy = defSettings.accuracy.level locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = true locationManager.allowDeferredLocationUpdates(untilTraveled: defSettings.meters, timeout: defSettings.timeout) self.isDeferred = true } } else { if self.isDeferred { locationManager.disallowDeferredLocationUpdates() self.isDeferred = false } } } //MARK: - Location Tracking Helper Funcs /// Evaluate best settings based upon running location requests /// /// - Returns: best settings private func locationTrackingBestSettings() -> TrackerSettings? { guard locationRequests.countRunning > 0 else { return nil // no settings, location manager can be disabled } var accuracy: Accuracy = .any var frequency: Frequency = .significant var type: CLActivityType = .other var distanceFilter: CLLocationDistance? = kCLDistanceFilterNone for request in locationRequests { guard request.state.isRunning else { continue // request is not running, can be ignored } if request.accuracy.orderValue > accuracy.orderValue { accuracy = request.accuracy } if request.frequency < frequency { frequency = request.frequency } if request.activity.rawValue > type.rawValue { type = request.activity } if request.minimumDistance == nil { // If mimumDistance is nil it's equal to `kCLDistanceFilterNone` and it will // reports all movements regardless measured distance distanceFilter = nil } else { // Otherwise if distanceFilter is higher than `kCLDistanceFilterNone` and our value is less than // the current value, we want to store it. Lower value is the setting. if distanceFilter != nil && request.minimumDistance! < distanceFilter! { distanceFilter = request.minimumDistance! } } } if distanceFilter == nil { // translate it to the right value. `kCLDistanceFilterNone` report all movements // regardless the horizontal distance measured. distanceFilter = kCLDistanceFilterNone } // Deferred location updates // Because deferred updates use the GPS to track location changes, // the location manager allows deferred updates only when GPS hardware // is available on the device and when the desired accuracy is set to kCLLocationAccuracyBest // or kCLLocationAccuracyBestForNavigation. // - A) If the GPS hardware is not available, the location manager reports a deferredFailed error. // - B) If the accuracy is not set to one of the supported values, the location manager reports a deferredAccuracyTooLow error. // - C) In addition, the distanceFilter property of the location manager must be set to kCLDistanceFilterNone. // If it is set to any other value, the location manager reports a deferredDistanceFiltered error. if isDeferredAvailable, let deferredSettings = self.deferredLocationSettings() { // has any deferred location request accuracy = deferredSettings.accuracy // B) distanceFilter = kCLDistanceFilterNone // C) let isNavigationAccuracy = (deferredSettings.accuracy.level == kCLLocationAccuracyBestForNavigation) frequency = .deferredUntil(distance: deferredSettings.meters, timeout: deferredSettings.timeout, navigation: isNavigationAccuracy) } return TrackerSettings(accuracy: accuracy, frequency: frequency, activity: type, distanceFilter: distanceFilter!) } //MARK: - CLLocationManager Location Tracking Delegate @objc open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { locationRequests.forEach { $0.dispatchAuthChange(self.lastStatus, status) } self.lastStatus = status switch status { case .denied, .restricted: let error = LocationError.authDidChange(status) self.pools.forEach { $0.dispatch(error: error) } self.updateServicesStatus() case .authorizedAlways, .authorizedWhenInUse: self.pools.forEach { $0.resumeWaitingAuth() } self.updateServicesStatus() default: break } } @objc public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } self.onReceiveNewLocation?(location) // Note: // We need to start the deferred location delivery (by calling allowDeferredLocationUpdates) after // the first location is arrived. So if this is the first location we have received and we have // running deferred location request we can start it. if self.lastLocation.last != nil { turnOnOrOffDeferredLocationUpdates() } // Store last location self.lastLocation.set(location: location) // Dispatch to any request (which is not of type deferred) locationRequests.iterate({ return ($0.frequency.isDeferredFrequency == false) }, { $0.dispatch(location: location) }) } //MARK: CLLocationManager Deferred Error Delegate public func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) { // iterate over deferred locations locationRequests.iterate({ return $0.frequency.isDeferredFrequency }, { $0.dispatch(error: error ?? LocationError.unknown) }) } //MARK: CLLocationManager Error Delegate @objc open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationRequests.iterate({ return $0.frequency.isDeferredFrequency }, { $0.dispatch(error: error) }) } //MARK: - Update Services Status /// Update services (turn on/off hardware) based upon running requests private func updateServicesStatus() { let pools = self.pools func updateAllServices() { self.updateLocationServices() self.updateHeadingServices() self.updateRegionMonitoringServices() self.updateVisitsServices() } do { // Check if we need to ask for authorization based upon currently running requests guard try self.requireAuthorizationIfNeeded() == false else { return } // Otherwise we can continue updateAllServices() } catch { // Something went wrong, stop all... self.locationSettings = nil // Dispatch error pools.forEach { $0.dispatch(error: error) } } } private var pools: [RequestsQueueProtocol] { let pools: [RequestsQueueProtocol] = [locationRequests, regionRequests, visitRequests,geocoderRequests,headingRequests] return pools } /// Require authorizations if needed /// /// - Returns: `true` if authorization is needed, `false` otherwise /// - Throws: throw if some required settings are missing private func requireAuthorizationIfNeeded() throws -> Bool { func pauseAllRunningRequest() { // Mark running requests as pending pools.forEach { $0.set(.waitingUserAuth, forRequestsIn: [.running,.idle]) } } // This is the authorization keys set in Info.plist let plistAuth = CLLocationManager.appAuthorization // Get the max authorization between all running request let requiredAuth = self.pools.map({ $0.requiredAuthorization }).reduce(.none, { $0 < $1 ? $0 : $1 }) // This is the current authorization of CLLocationManager let currentAuth = LocAuth.status if requiredAuth == .none { // No authorization are needed return false } switch currentAuth { case .denied,.disabled, .restricted: // Authorization was explicity disabled throw LocationError.authorizationDenided default: if requiredAuth == .always && (currentAuth == .inUseAuthorized || currentAuth == .undetermined) { // We need always authorization but we have in-use authorization if plistAuth != .always && plistAuth != .both { // we have not set the correct plist key to support this auth throw LocationError.missingAuthInInfoPlist } // Okay we can require it pauseAllRunningRequest() locationManager.requestAlwaysAuthorization() return true } if requiredAuth == .inuse && currentAuth == .undetermined { // We have not set not always or in-use auth plist so we can continue if plistAuth != .inuse && plistAuth != .both { throw LocationError.missingAuthInInfoPlist } // require in use authorization pauseAllRunningRequest() locationManager.requestWhenInUseAuthorization() return true } } // We have enough rights to continue without requiring auth return false } // MARK: - Services Update /// Update visiting services internal func updateVisitsServices() { guard visitRequests.countRunning > 0 else { // There is not any running request, we can stop monitoring all regions locationManager.stopMonitoringVisits() return } locationManager.startMonitoringVisits() } /// Update location services based upon running Requests internal func updateLocationServices() { let hasBackgroundRequests = locationRequests.hasBackgroundRequests() guard locationRequests.countRunning > 0 else { // There is not any running request, we can stop location service to preserve battery. self.locationSettings = nil return } // Evaluate best accuracy,frequency and activity type based upon all queued requests guard let bestSettings = self.locationTrackingBestSettings() else { // No need to setup CLLocationManager, stop it. self.locationSettings = nil return } print("Settings \(bestSettings)") // Request authorizations if needed if bestSettings.accuracy.requestUserAuth == true { // Check if device supports location services. // If not dispatch the error to any running request and stop. guard CLLocationManager.locationServicesEnabled() else { locationRequests.forEach { $0.dispatch(error: LocationError.serviceNotAvailable) } return } } // If there is a request which needs background capabilities and we have not set it // dispatch proper error. if hasBackgroundRequests && CLLocationManager.isBackgroundUpdateEnabled == false { locationRequests.forEach { $0.dispatch(error: LocationError.backgroundModeNotSet) } return } // Everything is okay we can setup CLLocationManager based upon the most accuracted/most frequent // Request queued and running. let isAppInBackground = (UIApplication.shared.applicationState == .background && CLLocationManager.isBackgroundUpdateEnabled) self.locationManager.allowsBackgroundLocationUpdates = isAppInBackground if isAppInBackground { self.autoPauseUpdates = false } // Resume any paused request (a paused request is in `.waitingUserAuth`,`.paused` or `.failed`) locationRequests.iterate([.waitingUserAuth]) { $0.resume() } // Setup with best settings self.locationSettings = bestSettings } internal func updateRegionMonitoringServices() { // Region monitoring is not available for this hardware guard CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) else { regionRequests.dispatch(error: LocationError.serviceNotAvailable) return } // Region monitoring require always authorizaiton, if not generate error let auth = CLLocationManager.appAuthorization if auth != .always && auth != .both { regionRequests.dispatch(error: LocationError.requireAlwaysAuth) return } guard regionRequests.countRunning > 0 else { // There is not any running request, we can stop monitoring all regions locationManager.stopMonitoringAllRegions() return } // Monitor queued regions regionRequests.forEach { if $0.state.isRunning { locationManager.startMonitoring(for: $0.region) } } } /// Update heading services internal func updateHeadingServices() { // Heading service is not available on current hardware guard CLLocationManager.headingAvailable() else { self.headingRequests.dispatch(error: LocationError.serviceNotAvailable) return } guard headingRequests.countRunning > 0 else { // There is not any running request, we can stop location service to preserve battery. locationManager.stopUpdatingHeading() return } // Find max accuracy in reporting heading and set it var bestHeading: CLLocationDegrees = Double.infinity for request in headingRequests { guard let filter = request.filter else { bestHeading = kCLHeadingFilterNone break } bestHeading = min(bestHeading,filter) } locationManager.headingFilter = bestHeading // Start locationManager.startUpdatingHeading() } }
37.864
258
0.73455
7a5957fc5b1e41780aac4d46787829d57fecebb1
534
// // Copyright © 2019 An Tran. All rights reserved. // import SwiftUI struct GeometryReaderExampleView: View { var body: some View { ExampleView( demoContentView: GeometryReaderExampleDemoView(), remoteSourcePath: "Animation/Geometry/GeometryReader/GeometryReaderExampleDemoView.swift" ) .navigationBarTitle("GeometryReader") } } struct GeometryReaderExampleView_Previews: PreviewProvider { static var previews: some View { GeometryReaderExampleView() } }
23.217391
101
0.696629
792633451fb7f906078ec63f60a56a03b0e534af
2,484
/// Copyright (c) 2020 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 SwiftUI struct WelcomeMessageView: View { var body: some View { Label { VStack(alignment: .leading) { Text("Welcome to") .font(.headline) .bold() Text("Kuchi") .font(.largeTitle) .bold() } .foregroundColor(.red) .lineLimit(2) .multilineTextAlignment(.leading) .padding(.horizontal) } icon: { LogoImage() } .labelStyle(HorizontallyAlignedLabelStyle()) } } struct WelcomeMessageView_Previews: PreviewProvider { static var previews: some View { WelcomeMessageView() } }
40.064516
83
0.717794
5b9f0b225929bfb2ba1835420eaa63e2b91b7bf9
1,628
/* * Copyright (C) 2014-2019 halo https://github.com/halo/macosvpn * * 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. */ public struct Log { public static func debug(_ message: String) { guard Arguments.options.debugRequested else { return } print(Color.Wrap(foreground: .blue).wrap("\(message)")) } public static func info(_ message: String) { print("\(message)") } public static func warn(_ message: String) { print(Color.Wrap(foreground: .yellow).wrap("\(message)")) } public static func error(_ message: String) { print(Color.Wrap(foreground: .red).wrap("\(message)")) } }
45.222222
133
0.738329
39235da6d49aebab433b3d05b3e95505a1cd17bd
851
// // MainAssembly.swift // Exemple // // Created by Bart on 26.10.2019 // Copyright © 2019 iDevs.io. All rights reserved. // import UIKit typealias MainModule = Module<MainModuleInput, MainModuleOutput> class MainAssembly: Assembly { func build(coordinator: CoordinatorType) -> MainModule { // View let view = MainViewController.controllerFromStoryboard(.main) // Interactor let interactor = MainInteractor() // Router let router = MainRouter(coordinator: coordinator) // Presenter let presenter = MainPresenter(interactor: interactor, router: router) // Dependency Setup presenter.view = view view.output = presenter return Module(view: view, input: presenter, output: presenter) } }
24.314286
77
0.620447
72d3322c15f004709aa0bc19c7f9917d8748a637
2,364
import Foundation import PathKit public class PackageManager { public var path: Path public var name: String public var beakFile: BeakFile public var sourcesPath: Path { return path + "Sources" } public var packagePath: Path { return path + "Package.swift" } public var mainFilePath: Path { return sourcesPath + "\(name)/main.swift" } public init(path: Path, name: String, beakFile: BeakFile) { self.path = path self.name = name self.beakFile = beakFile } public func write(functionCall: String?) throws { try write() var swiftFile = beakFile.contents if let functionCall = functionCall { swiftFile += "\n\n" + functionCall } try mainFilePath.writeIfUnchanged(swiftFile) } public func write(filePath: Path) throws { try write() try? mainFilePath.delete() try mainFilePath.writeIfUnchanged(beakFile.contents) } func write() throws { try path.mkpath() try mainFilePath.parent().mkpath() let package = PackageManager.createPackage(name: name, beakFile: beakFile) try packagePath.writeIfUnchanged(package) } public static func createPackage(name: String, beakFile: BeakFile) -> String { let dependenciesString = beakFile.dependencies.map { ".package(url: \($0.package.quoted), \($0.requirement))," }.joined(separator: "\n ") let librariesString = beakFile.libraries.map { "\($0.quoted)," }.joined(separator: "\n ") return """ // swift-tools-version:5.0 import PackageDescription let package = Package( name: \(name.quoted), platforms: [ .macOS(.v10_13), ], dependencies: [ \(dependenciesString) ], targets: [ .target( name: \(name.quoted), dependencies: [ \(librariesString) ] ) ] ) """ } } extension Path { func writeIfUnchanged(_ string: String) throws { if let existingContent: String = try? read() { if existingContent == string { return } } try write(string) } }
28.142857
152
0.551607
4857526536dfa8f5e69fcc43be00e94986c3d0d0
737
// // DataViewController.swift // XppIRCiOS // // Created by Michiel Hegemans on 08/01/2017. // Copyright © 2017 Bromancer. All rights reserved. // import UIKit class DataViewController: UIViewController { @IBOutlet weak var dataLabel: UILabel! var dataObject: String = "" 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. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.dataLabel!.text = dataObject } }
21.057143
80
0.671642
bb58f43d5dc768488080fb12bfaf04565a6f9aec
939
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import CallKit import Foundation @available(iOS 10.0, *) extension CXProviderConfiguration { @nonobjc public final var supportedHandleTypes: Set<CXHandle.HandleType> { get { return Set(__supportedHandleTypes.map { CXHandle.HandleType(rawValue: $0.intValue)! }) } set { __supportedHandleTypes = Set(newValue.lazy.map { $0.rawValue as NSNumber }) } } }
30.290323
80
0.582535
905b5e76513371be9b74238413f4122749657088
782
// // WfmIntradayPlanningGroupListing.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation /** A list of IntradayPlanningGroup objects */ public class WfmIntradayPlanningGroupListing: Codable { public enum NoDataReason: String, Codable { case noPublishedSchedule = "NoPublishedSchedule" case noSourceForecast = "NoSourceForecast" } public var entities: [ForecastPlanningGroupResponse]? /** The reason there was no data for the request */ public var noDataReason: NoDataReason? public init(entities: [ForecastPlanningGroupResponse]?, noDataReason: NoDataReason?) { self.entities = entities self.noDataReason = noDataReason } }
23
90
0.69821
08ecc25defd005c0fda1b7bf92267aee3fa54413
579
// // QueryFilterMethod.swift // FluentExt // // Created by Gustavo Perdomo on 07/28/18. // Copyright © 2018 Vapor Community. All rights reserved. // internal enum QueryFilterMethod: String { case equal = "eq" case notEqual = "neq" case `in` = "in" case notIn = "nin" case greaterThan = "gt" case greaterThanOrEqual = "gte" case lessThan = "lt" case lessThanOrEqual = "lte" case startsWith = "sw" case notStartsWith = "nsw" case endsWith = "ew" case notEndsWith = "new" case contains = "ct" case notContains = "nct" }
23.16
58
0.630397
870857fb20a56ed10e365b464b50360fd433faf3
2,616
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // 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 CoreData class InstanceManager { let session: Session init(session: Session) { self.session = session } func getInstance(url: String?) -> InstanceMO? { guard let url = url else { return nil } let query = NSFetchRequest<InstanceMO>(entityName: "Instance") query.predicate = NSPredicate(format: "url = %@", url) let results = session.fetch(request: query) return results.first } func processConfigDTO(url: String, config: GnusocialConfigDTO) -> InstanceMO? { if let existing = getInstance(url: url) { return existing } guard let fileQuota = config.attachments?.fileQuota, let name = config.site?.name, let serverOwnUrl = config.site?.server, let timezone = config.site?.timezone, let uploadsAllowed = config.attachments?.uploads else { return nil } let textLimit = Int64(config.site?.textLimit ?? "") ?? 1000 let bioLimit = Int64(config.profile?.bioLimit ?? "") ?? textLimit let contentLimit = Int64(config.notice?.contentLimit ?? "") ?? textLimit let descLimit = Int64(config.group?.descLimit ?? "") ?? textLimit let fileQuota64 = Int64(fileQuota) // Otherwise make a new one let new = NSEntityDescription.insertNewObject(forEntityName: "Instance", into: session.moc) as! InstanceMO new.bioLimit = bioLimit new.contentLimit = contentLimit new.descLimit = descLimit new.fileQuota = fileQuota64 new.textLimit = textLimit new.name = name new.serverOwnUrl = serverOwnUrl new.timezone = timezone new.url = url new.uploadsAllowed = uploadsAllowed if let logo = config.site?.logo { new.logo = logo } session.persist() return new } }
34.88
114
0.629587
769a092597befa72ec5478fcc7cd1e0b3e282ed0
1,040
// 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: "PodJimPlayKit", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "PodJimPlayKit", targets: ["PodJimPlayKit"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "PodJimPlayKit", dependencies: []), .testTarget( name: "PodJimPlayKitTests", dependencies: ["PodJimPlayKit"]), ] )
35.862069
117
0.627885
ed6225ad1c4531f14dd7e4915d27d504b0df387d
1,148
// // MoveStack.swift // Solitaire // // Created by Juan on 11/06/2020. // Copyright © 2020 Pixfans. All rights reserved. // import SpriteKit class Move: Pile { static let KZPos : CGFloat = 100 static let KOffset = CGSize(width: 0, height: -30) var origin: InteractivePile var destination: InteractivePile? init(source: InteractivePile, cards: [Card], position: CGPoint) { self.origin = source super.init(offset: Move.KOffset, position: position, texture: SKTexture.init()) self.cards = cards zPosition = Move.KZPos } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func cancel() { origin.add(cards: cards) origin.updateCards(animated: true) } func moveCards(destination: InteractivePile) { self.destination = destination destination.add(cards: cards) destination.updateCards(animated: true) } func revert() { self.destination?.remove(cards: cards) self.origin.add(cards: cards) } }
22.96
87
0.609756
29614265d6ada1958dcaea8bad6a432113cbd811
1,598
// // SWAppLoginManager.swift // Switcher // // Created by X140Yu on 6/9/16. // Copyright © 2016 X140Yu. All rights reserved. // import Foundation import AppKit class SWAppLoginManager { static func loginWith(_ type: SWLoginType, appleID: String, password: String) { var resourceName: String = "" switch type { case .appStore: resourceName = "AppStore" case .iTunes: resourceName = "iTunes" case .none: assertionFailure("should not be none") } guard let path = Bundle.main.path(forResource: resourceName, ofType: "txt") else { return } guard let content = try? NSString(contentsOfFile: path, encoding: 0) as String else { return } guard let appleScript = NSAppleScript(source: processScript(content, appleID: appleID, password: password)) else { return } var errorInfo: NSDictionary? = nil appleScript.executeAndReturnError(&errorInfo) if errorInfo != nil { ErrorHanding.showErrorDialog() } } static func processScript(_ content: String, appleID: String, password: String) -> String { let result = content.replacingOccurrences(of: "$APP_ID", with: appleID) return result.replacingOccurrences(of: "$PASSWORD", with: password) } } struct ErrorHanding { static func showErrorDialog() { let alert = NSAlert() alert.messageText = "Sorry, some errors occured. :(" alert.informativeText = "Please try again." alert.addButton(withTitle: "Ok") alert.runModal() } }
31.96
131
0.639549
ed0cf8ee0f682792dbf4ae7de8ee08d889dbc7f3
627
#if canImport(Darwin) import Foundation extension Bundle { /** Locates the first bundle with a '.xctest' file extension. */ internal static var currentTestBundle: Bundle? { return allBundles.first { $0.bundlePath.hasSuffix(".xctest") } } /** Return the module name of the bundle. Uses the bundle filename and transform it to match Xcode's transformation. Module name has to be a valid "C99 extended identifier". */ internal var moduleName: String { let fileName = bundleURL.fileName as NSString return fileName.c99ExtendedIdentifier } } #endif
24.115385
79
0.671451
1d3fa4fada01d1a2bdc87849a64403832c00bd6f
2,945
// // AppDelegate.swift // MERLinSample // // Created by Giuseppe Lanza on 02/09/18. // Copyright © 2018 HBCDigital. All rights reserved. // import MERLin import RxSwift import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, EventsProducer { let moduleName: String = "app_launch" let moduleSection: String = "App launch" let moduleType: String = "App launch" let disposeBag = DisposeBag() var events: Observable<AppDelegateEvent> { return _events } private let _events = PublishSubject<AppDelegateEvent>() var window: UIWindow? var moduleManager: BaseModuleManager = BaseModuleManager() var router: SimpleRouter! lazy var eventsListeners: [AnyEventsListener] = { [ ConsoleLogEventsListener(), AppDelegateEventsListener(withRouter: router), RoutingEventsListener(withRouter: router) ] }() func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { router = SimpleRouter(withFactory: moduleManager) moduleManager.addEventsListeners(eventsListeners) eventsListeners.forEach { $0.listenEvents(from: self) } return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow() window?.rootViewController = router.rootViewController(forLaunchOptions: launchOptions) window?.makeKeyAndVisible() _events.onNext(.didFinishLaunching) return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { guard app.canOpenURL(url) == true else { return false } _events.onNext(.openURL(url: url)) return true } func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool { _events.onNext(.willContinueUserActivity(type: userActivityType)) return true } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { _events.onNext(.continueUserActivity(userActivity)) return true } func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error) { _events.onNext(.failedToContinueUserActivity(type: userActivityType)) } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { _events.onNext(.didUseShortcut(shortcutItem)) } }
35.481928
167
0.689983
fc6bbd58d60567328683de0614151f60888a22c7
2,639
/// The Trie class has the following attributes: /// -root (the root of the trie) /// -wordList (the words that currently exist in the trie) /// -wordCount (the number of words in the trie) public final class Trie { typealias Node = TrieNode<Character> public fileprivate(set) var words: Set<String> = [] public var isEmpty: Bool { return count == 0 } public var count: Int { return words.count } fileprivate let root: Node public init() { root = TrieNode<Character>() } } // MARK: - Basic Methods public extension Trie { func insert(word: String) { guard !word.isEmpty, !contains(word: word) else { return } var currentNode = root var characters = Array(word.lowercased().characters) var currentIndex = 0 while currentIndex < characters.count { let character = characters[currentIndex] if let child = currentNode.children[character] { currentNode = child } else { currentNode.add(child: character) currentNode = currentNode.children[character]! } currentIndex += 1 if currentIndex == characters.count { currentNode.isTerminating = true } } words.insert(word) } func contains(word: String) -> Bool { guard !word.isEmpty else { return false } var currentNode = root var characters = Array(word.lowercased().characters) var currentIndex = 0 while currentIndex < characters.count, let child = currentNode.children[characters[currentIndex]] { currentNode = child currentIndex += 1 } if currentIndex == characters.count && currentNode.isTerminating { return true } else { return false } } func remove(word: String) { guard !word.isEmpty, words.contains(word) else { return } words.remove(word) var currentNode = root var characters = Array(word.lowercased().characters) var currentIndex = 0 while currentIndex < characters.count { let character = characters[currentIndex] guard let child = currentNode.children[character] else { return } currentNode = child currentIndex += 1 } if currentNode.children.count > 0 { currentNode.isTerminating = false } else { var character = currentNode.value while currentNode.children.count == 0, let parent = currentNode.parent { currentNode = parent currentNode.children[character!] = nil character = currentNode.value if currentNode.isTerminating { break } } } } }
25.375
103
0.627889
0a6c8dadf5c678d21c2b81d230b7da5e10c1dec8
2,369
// // Library // // Created by Otto Suess on 04.07.18. // Copyright © 2018 Zap. All rights reserved. // import Foundation import Lightning struct FilterSettings: Equatable, Codable { var channelEvents: Bool var transactionEvents: Bool var createInvoiceEvents: Bool var expiredInvoiceEvents: Bool var lightningPaymentEvents: Bool } extension FilterSettings { static var fileName = "filterSettings" init() { channelEvents = true transactionEvents = true createInvoiceEvents = true expiredInvoiceEvents = false lightningPaymentEvents = true } public func save() { Storage.store(self, to: FilterSettings.fileName) } public static func load() -> FilterSettings { return Storage.restore(fileName) ?? FilterSettings() } } enum FilterSetting: Localizable { case channelEvents case transactionEvents case createInvoiceEvents case expiredInvoiceEvents case lightningPaymentEvents var localized: String { switch self { case .transactionEvents: return L10n.Scene.Filter.displayOnChainTransactions case .lightningPaymentEvents: return L10n.Scene.Filter.displayLightningPayments case .createInvoiceEvents: return L10n.Scene.Filter.displayLightningInvoices case .channelEvents: return L10n.Scene.Filter.displayChannelEvents case .expiredInvoiceEvents: return L10n.Scene.Filter.displayExpiredInvoices } } private var keyPath: WritableKeyPath<FilterSettings, Bool> { switch self { case .channelEvents: return \.channelEvents case .transactionEvents: return \.transactionEvents case .createInvoiceEvents: return \.createInvoiceEvents case .expiredInvoiceEvents: return \.expiredInvoiceEvents case .lightningPaymentEvents: return \.lightningPaymentEvents } } func isActive(in filterSettings: FilterSettings) -> Bool { return filterSettings[keyPath: keyPath] } func setActive(_ isActive: Bool, in filterSettings: FilterSettings) -> FilterSettings { var filterSettings = filterSettings filterSettings[keyPath: keyPath] = isActive return filterSettings } }
27.546512
91
0.669903
3a89e1a3f7303d6e6d402364065751ce839a3ed3
2,137
// // AppDelegate.swift // AutoLayout // // Created by WangBen on 16/4/28. // Copyright © 2016年 WangBen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.468085
285
0.753861
8a16c194c64854681c6e7594dd9f46aa9004ae47
5,095
// // WelcomeViewController.swift // Truco Marcador // // Created by Joao Flores on 15/06/20. // Copyright © 2020 Gustavo Lima. All rights reserved. // import UIKit import StoreKit class WelcomeViewController: UIViewController { // MARK: - Variables var products: [SKProduct] = [] var timerLoad: Timer! static let priceFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.formatterBehavior = .behavior10_4 formatter.numberStyle = .currency return formatter }() // MARK: - IBOutlets // @IBOutlet weak var buyLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! // @IBOutlet weak var titlePurchase: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var loadingView: UIActivityIndicatorView! @IBOutlet weak var viewPro: UIView! @IBOutlet weak var viewTest: UIView! // MARK: - IBAction @IBAction func buyPressed(_ sender: Any) { RazeFaceProducts.store.buyProduct(self.products[0]) startLoading() timerLoad = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.loadingPlaying), userInfo: nil, repeats: false) confirmCheckmark() } @IBAction func restorePressed(_ sender: Any) { RazeFaceProducts.store.restorePurchases() startLoading() timerLoad = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.loadingPlaying), userInfo: nil, repeats: false) confirmCheckmark() } // MARK: - UI @objc func loadingPlaying() { stopLoading() } func confirmCheckmark() { DispatchQueue.main.async { if(RazeFaceProducts.store.isProductPurchased("NoAds.College") || (UserDefaults.standard.object(forKey: "NoAds.College") != nil)) { self.stopLoading() UserDefaults.standard.set(true, forKey:"NoAds.College") self.showController() } } } func showController() { let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) performSegue(withIdentifier: "ShowApp", sender: nil) } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() viewPro.layer.cornerRadius = 20 viewTest.layer.cornerRadius = 20 NotificationCenter.default.addObserver(self, selector: #selector(MasterViewController.handlePurchaseNotification(_:)), name: .IAPHelperPurchaseNotification, object: nil) confirmCheckmark() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) reload() confirmCheckmark() } override func viewWillAppear(_ animated: Bool) { super.viewDidAppear(animated) reload() confirmCheckmark() } override func viewWillDisappear(_ animated: Bool) { reload() confirmCheckmark() } @objc func handlePurchaseNotification(_ notification: Notification) { guard let productID = notification.object as? String, let _ = products.firstIndex(where: { product -> Bool in product.productIdentifier == productID }) else { return } confirmCheckmark() } // MARK: - UI func startLoading() { loadingView.alpha = 1 loadingView.startAnimating() } func stopLoading() { loadingView.alpha = 0 loadingView.stopAnimating() } // MARK: - Data Management @objc func reload() { products = [] RazeFaceProducts.store.requestProducts{ [weak self] success, products in guard let self = self else { return } if success { self.products = products! DispatchQueue.main.async { self.descriptionLabel.text = self.products[0].localizedDescription MasterViewController.self.priceFormatter.locale = self.products[0].priceLocale self.priceLabel.text = MasterViewController.self.priceFormatter.string(from: self.products[0].price)! } } else { if products?[0] != nil { self.descriptionLabel.text = self.products[0].localizedDescription MasterViewController.self.priceFormatter.locale = self.products[0].priceLocale self.priceLabel.text = MasterViewController.self.priceFormatter.string(from: self.products[0].price)! } } } confirmCheckmark() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
31.645963
145
0.579588
f79f51600eae145e5c4991877d0568c6d9fb7eb6
447
// // SwiftyReading.swift // Files // // Created by Manuel Sánchez on 9/12/19. // import Foundation struct SwiftyReading: Codable { let firstReading: Reading? let psalm: Reading? let secondReading: Reading? let gospel: Reading? let date: String enum CodingKeys: String, CodingKey { case firstReading = "first_reading" case secondReading = "second_reading" case psalm, gospel, date } }
19.434783
45
0.651007
8965cbf2f000ce0cc97de11f09cef7f8de4d3a07
3,593
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit class AKDistortionTests: AKTestCase { override func setUp() { super.setUp() duration = 1.0 } func testCubicTerm() { output = AKDistortion(input, cubicTerm: 0.65) AKTestMD5("9dca12baacae3c7190d358fd9682d483") } func testDecay() { output = AKDistortion(input, decay: 2) AKTestMD5("cb80e1702ec954880f78da716533df33") } func testDecimation() { output = AKDistortion(input, decimation: 0.61) AKTestMD5("19633943272798663095159a27c4d06a") } func testDecimationMix() { output = AKDistortion(input, decimationMix: 0.62) AKTestMD5("b176942f8f27bfc782b9989bbabc49c6") } func testDefault() { output = AKDistortion(input) AKTestMD5("809d9eb95a91e34dc2ebb957dd525394") } func testDelay() { output = AKDistortion(input, delay: 0.2) AKTestMD5("6de6a44ef0b8b3a072c0355b56c69e83") } func testDelayMix() { output = AKDistortion(input, delayMix: 0.6) AKTestMD5("1a499e4fe4b036950c85f48832cf0b75") } func testFinalMix() { output = AKDistortion(input, finalMix: 0.69) AKTestMD5("5040767304222a74ff0a5f61ee890ab3") } func testLinearTerm() { output = AKDistortion(input, linearTerm: 0.63) AKTestMD5("a60c35c5f4552b50a83889534852d490") } func testParameters() { output = AKDistortion(input, delay: 0.2, decay: 2, delayMix: 0.6, decimation: 0.61, rounding: 0.5, decimationMix: 0.62, linearTerm: 0.63, squaredTerm: 0.64, cubicTerm: 0.65, polynomialMix: 0.66, ringModFreq1: 200, ringModFreq2: 300, ringModBalance: 0.67, ringModMix: 0.68, softClipGain: 0, finalMix: 0.69) AKTestMD5("b20419cbe57b8ff46b7082ccec6fb9f5") } func testPolynomialMix() { output = AKDistortion(input, polynomialMix: 0.66) AKTestMD5("844168c2749002acf535a0599952005a") } func testRingModBalance() { output = AKDistortion(input, ringModBalance: 0.67, ringModMix: 0.68) AKTestMD5("9cad389fcaae58d25874838325888c7b") } func testRingModFreq1() { output = AKDistortion(input, ringModFreq1: 200, ringModMix: 0.68) AKTestMD5("219ad6174a9c5fe683220276f139496c") } func testRingModFreq2() { output = AKDistortion(input, ringModFreq2: 300, ringModMix: 0.68) AKTestMD5("2974848b83e6d6c453443b89b8232b56") } func testRingModMix() { output = AKDistortion(input, ringModMix: 0.68) AKTestMD5("0a083989773cc93c6f2d8940df181acd") } func testRounding() { output = AKDistortion(input, rounding: 0.5) AKTestMD5("0960d44f15db32056aa6e8146025d20a") } func testSquaredTerm() { output = AKDistortion(input, squaredTerm: 0.64) AKTestMD5("1bf56e3620ec5790483c16fded69c06f") } func testSoftClipGain() { output = AKDistortion(input, softClipGain: 0) AKTestMD5("eeaa785a6d4087a7abb9f0145f9a7540") } }
30.193277
100
0.578068
29171e2a96da272ece3427efb9df0dec3fb8fe05
58
// // File.swift // FiretvExample // import Foundation
8.285714
17
0.655172
22447747d82e60521bcb8415c449fc413b0f6a5d
3,814
/******************************************************************************* * Copyright 2019 alladin-IT GmbH * * 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 CodableJSON /// This module defines a data model for a single reporting result, which is a part of a Large-Scale Measurement Platform (LMAP). class LmapResultDto: Codable { /// The name of the Schedule that produced the result. var schedule: String? /// The name of the Action in the Schedule that produced the result. var action: String? /// The name of the Task that produced the result. var task: String? /// This container is a placeholder for runtime parameters defined in Task-specific data models augmenting the base LMAP report data model. var parameters: String? //Any? /// The list of options there were in use when the measurement was performed. /// This list must include both the Task-specific options as well as the Action-specific options. var options: [LmapOptionDto]? /// A tag contains additional information that is passed with the result record to the Collector. /// This is the joined set of tags defined for the Task object, the Schedule object, and the Action object. /// A tag can be used to carry the Measurement Cycle ID. var tags: [String]? /// The date and time of the event that triggered the Schedule of the Action that produced the reported result values. /// The date and time does not include any added randomization. var event: Date? /// The date and time when the Task producing this result started. var start: Date? /// The date and time when the Task producing this result finished. var end: Date? /// The optional cycle number is the time closest to the time reported in the event leaf /// that is a multiple of the cycle-interval of the event that triggered the execution of the Schedule. /// The value is only present if the event that triggered the execution of the Schedule has a defined cycle-interval. var cycleNumber: String? /// The status code returned by the execution of this Action. /// /// A status code returned by the execution of a Task. Note /// that the actual range is implementation dependent, but it /// should be portable to use values in the range 0..127 for /// regular exit codes. By convention, 0 indicates successful /// termination. Negative values may be used to indicate /// abnormal termination due to a signal; the absolute value /// may identify the signal number in this case. var status: Int? /// The names of Tasks overlapping with the execution of the Task that has produced this result. var conflict: [LmapConflictDto]? /// A list of results. Replaces the table list from LMAP var results: [SubMeasurementResult]? /// enum CodingKeys: String, CodingKey { case schedule case action case task case parameters case options = "option" case tags = "tag" case event case start case end case cycleNumber = "cycle-number" case status case conflict case results } }
41.010753
143
0.670425
e5bee5ac01b2ecd063d7987c491fe6e7347e7b16
12,056
// // CourseOutline.swift // edX // // Created by Akiva Leffert on 4/29/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import edXCore public typealias CourseBlockID = String public struct CourseOutline { enum Fields : String, RawStringExtractable { case Root = "root" case Blocks = "blocks" case BlockCounts = "block_counts" case BlockType = "type" case Descendants = "descendants" case DisplayName = "display_name" case DueDate = "due" case Format = "format" case Graded = "graded" case LMSWebURL = "lms_web_url" case StudentViewMultiDevice = "student_view_multi_device" case StudentViewURL = "student_view_url" case StudentViewData = "student_view_data" case Summary = "summary" case MinifiedBlockID = "block_id" case AuthorizationDenialReason = "authorization_denial_reason" case AuthorizationDenialMessage = "authorization_denial_message" case isCompleted = "completion" case ContainsGatedContent = "contains_gated_content" case ShowGatedSections = "show_gated_sections" case SpecialExamInfo = "special_exam_info" } public let root : CourseBlockID public let blocks : [CourseBlockID:CourseBlock] private let parents : [CourseBlockID:CourseBlockID] public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) { self.root = root self.blocks = blocks var parents : [CourseBlockID:CourseBlockID] = [:] for (blockID, block) in blocks { for child in block.children { parents[child] = blockID } } self.parents = parents } public init?(json : JSON) { if let root = json[Fields.Root].string, let blocks = json[Fields.Blocks].dictionaryObject { var validBlocks : [CourseBlockID:CourseBlock] = [:] for (blockID, blockBody) in blocks { let body = JSON(blockBody) let webURL = NSURL(string: body[Fields.LMSWebURL].stringValue) var children = body[Fields.Descendants].arrayObject as? [String] ?? [] let name = body[Fields.DisplayName].string let dueDate = body[Fields.DueDate].string let blockURL = body[Fields.StudentViewURL].string.flatMap { NSURL(string:$0) } let format = body[Fields.Format].string let typeName = body[Fields.BlockType].string ?? "" let multiDevice = body[Fields.StudentViewMultiDevice].bool ?? false let blockCounts : [String:Int] = (body[Fields.BlockCounts].object as? NSDictionary)?.mapValues { $0 as? Int ?? 0 } ?? [:] let graded = body[Fields.Graded].bool ?? false let minifiedBlockID = body[Fields.MinifiedBlockID].string let authorizationDenialReason = body[Fields.AuthorizationDenialReason].string let authorizationDenialMessage = body[Fields.AuthorizationDenialMessage].string let isCompleted = body[Fields.isCompleted].boolValue let specialExamInfo = body[Fields.SpecialExamInfo].dictionaryObject // quick fix for LEARNER-8708, to hide special exam components // TODO: may or may not change after final decision from product if specialExamInfo != nil { children = [] } var type : CourseBlockType if let category = CourseBlock.Category(rawValue: typeName) { switch category { case .Course: type = .Course case .Chapter: type = .Chapter case .Section: type = .Section case .Unit: type = .Unit case .HTML: type = .HTML case .Problem: type = .Problem case .OpenAssesment: type = .OpenAssesment case .DragAndDrop: type = .DragAndDrop case .WordCloud: type = .WordCloud case .Video : let bodyData = (body[Fields.StudentViewData].object as? NSDictionary).map { [Fields.Summary.rawValue : $0 ] } let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, unitURL: blockURL?.absoluteString, name : name ?? Strings.untitled) type = .Video(summary) case .Discussion: // Inline discussion is in progress feature. Will remove this code when it's ready to ship type = .Unknown(typeName) if OEXConfig.shared().discussionsEnabled { let bodyData = body[Fields.StudentViewData].object as? NSDictionary let discussionModel = DiscussionModel(dictionary: bodyData ?? [:]) type = .Discussion(discussionModel) } case .LTIConsumer: type = .LTIConsumer } } else { type = .Unknown(typeName) } validBlocks[blockID] = CourseBlock( type: type, children: children, blockID: blockID, minifiedBlockID: minifiedBlockID, name: name, dueDate: dueDate, blockCounts : blockCounts, blockURL : blockURL, webURL: webURL, format : format, multiDevice : multiDevice, graded : graded, authorizationDenialReason: authorizationDenialReason, authorizationDenialMessage: authorizationDenialMessage, typeName: typeName, isCompleted: isCompleted, specialExamInfo: specialExamInfo ) } self = CourseOutline(root: root, blocks: validBlocks) } else { return nil } } func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? { return self.parents[blockID] } } public enum CourseBlockType: Equatable { case Unknown(String) case Course case Chapter // child of course case Section // child of chapter case Unit // child of section case Video(OEXVideoSummary) case Problem case OpenAssesment case DragAndDrop case WordCloud case HTML case LTIConsumer case Discussion(DiscussionModel) public var asVideo : OEXVideoSummary? { switch self { case let .Video(summary): return summary default: return nil } } } public class CourseBlock { /// Simple list of known block categories strings public enum Category : String { case Chapter = "chapter" case Course = "course" case HTML = "html" case Problem = "problem" case OpenAssesment = "openassessment" case DragAndDrop = "drag-and-drop-v2" case WordCloud = "word_cloud" case Section = "sequential" case Unit = "vertical" case Video = "video" case Discussion = "discussion" case LTIConsumer = "lti_consumer" } public enum AuthorizationDenialReason : String { case featureBasedEnrollment = "Feature-based Enrollments" case none = "none" } public let type : CourseBlockType public let blockID : CourseBlockID /// This is the alpha numeric identifier at the end of the blockID above. public let minifiedBlockID: String? /// Children in the navigation hierarchy. /// Note that this may be different than the block's list of children, server side /// Since we flatten out the hierarchy for display public let children : [CourseBlockID] /// Title of block. Keep this private so people don't use it as the displayName by accident private let name : String? public let dueDate : String? /// Actual title of the block. Not meant to be user facing - see displayName public var internalName : String? { return name } /// User visible name of the block. public var displayName : String { guard let name = name, !name.isEmpty else { return Strings.untitled } return name } /// TODO: Match final API name /// The type of graded component public let format : String? /// Mapping between block types and number of blocks of that type in this block's /// descendants (recursively) for example ["video" : 3] public let blockCounts : [String:Int] /// Just the block content itself as a web page. /// Suitable for embedding in a web view. public let blockURL : NSURL? /// If this is web content, can we actually display it. public let multiDevice : Bool /// A full web page for the block. /// Suitable for opening in a web browser. public let webURL : NSURL? /// Whether or not the block is graded. /// TODO: Match final API name public let graded : Bool? /// Authorization Denial Reason if the block content is gated public let authorizationDenialReason: AuthorizationDenialReason /// Authorization Denial Message if the block content is gated public let authorizationDenialMessage: String? public let specialExamInfo: [String : Any]? /// completion works as a property observer, /// when value of `isCompleted` is changed, subscription method on `completion` is called. public private(set) var completion: Observable<Bool> = Observable(false) /// Status of block completion public var isCompleted: Bool { didSet { completion.value = isCompleted } } /// Property to represent gated content public var isGated: Bool { return authorizationDenialReason == .featureBasedEnrollment } /// Text type of the block public var typeName: String? public init(type : CourseBlockType, children : [CourseBlockID], blockID : CourseBlockID, minifiedBlockID: String?, name : String?, dueDate : String? = nil, blockCounts : [String:Int] = [:], blockURL : NSURL? = nil, webURL : NSURL? = nil, format : String? = nil, multiDevice : Bool, graded : Bool = false, authorizationDenialReason: String? = nil, authorizationDenialMessage: String? = nil, typeName: String? = nil, isCompleted: Bool = false, specialExamInfo: [String : Any]? = nil) { self.type = type self.children = children self.name = name self.dueDate = dueDate self.blockCounts = blockCounts self.blockID = blockID self.minifiedBlockID = minifiedBlockID self.blockURL = blockURL self.webURL = webURL self.graded = graded self.format = format self.multiDevice = multiDevice self.authorizationDenialReason = AuthorizationDenialReason(rawValue: authorizationDenialReason ?? AuthorizationDenialReason.none.rawValue) ?? AuthorizationDenialReason.none self.authorizationDenialMessage = authorizationDenialMessage self.typeName = typeName self.isCompleted = isCompleted self.specialExamInfo = specialExamInfo } }
37.209877
180
0.575647
46eaba629562f4ba9f232d6819e7141746378147
578
// // AppDelegate.swift // School // // Created by mis on 17.02.21. // // Copyright (c) [2021] [Michael Schmidt, [email protected]] // You can use it under the MIT License (You find it in file LICENSE) // import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
19.266667
73
0.690311
90b20ecb00a74f1e47993108f1888f66336b193a
318
func foo(_ a : inout [Int]) -> [Int] { a[0] = 3 a[1] = 4 a[3] = 4 return a } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -extract-function -source-filename %s -pos=2:1 -end-pos=5:11 >> %t.result/L2-5.swift // RUN: diff -u %S/Outputs/extract_sugar/L2-5.swift.expected %t.result/L2-5.swift
28.909091
102
0.606918
e867f5ffdc1a12f0303820647047a594d41405c3
1,740
/************************************************************************//** * PROJECT: SwiftDOM * FILENAME: EntityRefNodeImpl.swift * IDE: AppCode * AUTHOR: Galen Rhodes * DATE: 11/3/20 * * Copyright © 2020 Galen Rhodes. All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *//************************************************************************/ import Foundation public class EntityRefNodeImpl: NamedNodeImpl, EntityRefNode { //@f:0 @inlinable public var entityName : String { nodeName } @inlinable public override var isReadOnly : Bool { true } @inlinable public override var nodeType : NodeTypes { .EntityReferenceNode } //@f:1 public init(_ owningDocument: DocumentNode, entityName: String) { super.init(owningDocument, nodeName: entityName) } public init(_ owningDocument: DocumentNode, namespaceURI: String, qualifiedEntityName name: String) { super.init(owningDocument, namespaceURI: namespaceURI, qualifiedName: name) } }
48.333333
183
0.662069
f9efb27aa99a42d1cd954e7ea2e13ac1a5ac3ca5
19,669
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. /// You can use the enum of option item with value to control some behaviors of Kingfisher. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] extension Array where Element == KingfisherOptionsInfoItem { static let empty: KingfisherOptionsInfo = [] } /// Represents the available option items could be used in `KingfisherOptionsInfo`. public enum KingfisherOptionsInfoItem { /// Kingfisher will use the associated `ImageCache` object when handling related operations, /// including trying to retrieve the cached images and store the downloaded image to it. case targetCache(ImageCache) /// The `ImageCache` for storing and retrieving original images. If `originalCache` is /// contained in the options, it will be preferred for storing and retrieving original images. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. /// /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is /// applied in the option, the original image will be stored to this `originalCache`. At the /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, /// Kingfisher will try to search the original image to check whether it is already there. If found, /// it will be used and applied with the given processor. It is an optimization for not downloading /// the same image for multiple times. case originalCache(ImageCache) /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. case downloader(ImageDownloader) /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `.forceRefresh` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. case downloadPriority(Float) /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory /// cache, then it will ignore the disk cache but download the image again from network. This is useful when /// you want to display a changeable image behind the same url at the same app session, while avoiding download /// it for multiple times. case fromMemoryCacheOrRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `.transition` option for more. case forceTransition /// If set, Kingfisher will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. case waitForCache /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is /// not in cache, the image retrieving will fail with an error. case onlyFromCache /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen /// rendering to extract pixel information in background. This can speed up display, but will cost more time to /// prepare the image for using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks. @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") case callbackDispatchQueue(DispatchQueue?) /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. /// /// - Note: /// This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue. case callbackQueue(CallbackQueue) /// The associated value will be used as the scale factor when converting retrieved data to an image. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. /// /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, /// which uses more memory but only decode image frames once. case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the image download request. You can modify the request for some /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. /// The original request will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirect. You can modify the request for /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url /// mapping. /// The original redirection request will be sent without any modification by default. case redirectHandler(ImageDownloadRedirectHandler) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. /// If not set, the `DefaultImageProcessor.default` will be used. case processor(ImageProcessor) /// Supplies a `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// If not set, the `DefaultCacheSerializer.default` will be used. case cacheSerializer(CacheSerializer) /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being /// fetched from a cache, the modifier will run after the `CacheSerializer`. /// /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from an animated image file as a single image. /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. /// /// This option will be ignored if the target image is not animated image data. case onlyLoadFirstFrame /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original /// images if necessary. /// /// The original image will be only cached to disk storage. case cacheOriginalImage /// If set and a downloading error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. case onFailureImage(Image?) /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage /// aggressively. By default this is not contained in the options, that means if the requested image is already /// in disk cache, Kingfisher will not try to load it to memory. case alsoPrefetchToMemory /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already /// has an image set. /// /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. case loadDiskFileSynchronously /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case memoryCacheExpiration(StorageExpiration) /// The expiration extending setting for memory cache. The item expiration time will be incremented by this value after access. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. case memoryCacheAccessExtendingExpiration(ExpirationExtending) /// The expiration setting for memory cache. By default, the underlying `DiskStorage.Backend` uses the /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case diskCacheExpiration(StorageExpiration) /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of /// blocking the UI, especially if the processor needs a lot of time to run). case processingQueue(CallbackQueue) /// Enable progressive image loading, Kingfisher will use the `ImageProgressive` of case progressiveJPEG(ImageProgressive) } // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. // So we can prevent the iterating over the options array again and again. /// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member /// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be /// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. public struct KingfisherParsedOptionsInfo { public var targetCache: ImageCache? = nil public var originalCache: ImageCache? = nil public var downloader: ImageDownloader? = nil public var transition: ImageTransition = .none public var downloadPriority: Float = URLSessionTask.defaultPriority public var forceRefresh = false public var fromMemoryCacheOrRefresh = false public var forceTransition = false public var cacheMemoryOnly = false public var waitForCache = false public var onlyFromCache = false public var backgroundDecode = false public var preloadAllAnimationData = false public var callbackQueue: CallbackQueue = .mainCurrentOrAsync public var scaleFactor: CGFloat = 1.0 public var requestModifier: ImageDownloadRequestModifier? = nil public var redirectHandler: ImageDownloadRedirectHandler? = nil public var processor: ImageProcessor = DefaultImageProcessor.default public var imageModifier: ImageModifier? = nil public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default public var keepCurrentImageWhileLoading = false public var onlyLoadFirstFrame = false public var cacheOriginalImage = false public var onFailureImage: Optional<Image?> = .none public var alsoPrefetchToMemory = false public var loadDiskFileSynchronously = false public var memoryCacheExpiration: StorageExpiration? = nil public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime public var diskCacheExpiration: StorageExpiration? = nil public var processingQueue: CallbackQueue? = nil public var progressiveJPEG: ImageProgressive? = nil var onDataReceived: [DataReceivingSideEffect]? = nil public init(_ info: KingfisherOptionsInfo?) { guard let info = info else { return } for option in info { switch option { case .targetCache(let value): targetCache = value case .originalCache(let value): originalCache = value case .downloader(let value): downloader = value case .transition(let value): transition = value case .downloadPriority(let value): downloadPriority = value case .forceRefresh: forceRefresh = true case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true case .forceTransition: forceTransition = true case .cacheMemoryOnly: cacheMemoryOnly = true case .waitForCache: waitForCache = true case .onlyFromCache: onlyFromCache = true case .backgroundDecode: backgroundDecode = true case .preloadAllAnimationData: preloadAllAnimationData = true case .callbackQueue(let value): callbackQueue = value case .scaleFactor(let value): scaleFactor = value case .requestModifier(let value): requestModifier = value case .redirectHandler(let value): redirectHandler = value case .processor(let value): processor = value case .imageModifier(let value): imageModifier = value case .cacheSerializer(let value): cacheSerializer = value case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true case .onlyLoadFirstFrame: onlyLoadFirstFrame = true case .cacheOriginalImage: cacheOriginalImage = true case .onFailureImage(let value): onFailureImage = .some(value) case .alsoPrefetchToMemory: alsoPrefetchToMemory = true case .loadDiskFileSynchronously: loadDiskFileSynchronously = true case .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration case .processingQueue(let queue): processingQueue = queue case .progressiveJPEG(let value): progressiveJPEG = value } } if originalCache == nil { originalCache = targetCache } } } extension KingfisherParsedOptionsInfo { var imageCreatingOptions: ImageCreatingOptions { return ImageCreatingOptions( scale: scaleFactor, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyLoadFirstFrame) } } protocol DataReceivingSideEffect: AnyObject { var onShouldApply: () -> Bool { get set } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) } class ImageLoadingProgressSideEffect: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } let block: DownloadProgressBlock init(_ block: @escaping DownloadProgressBlock) { self.block = block } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { guard onShouldApply() else { return } guard let expectedContentLength = task.task.response?.expectedContentLength, expectedContentLength != -1 else { return } let dataLength = Int64(task.mutableData.count) DispatchQueue.main.async { self.block(dataLength, expectedContentLength) } } }
56.037037
139
0.72749
de8475be303b14c062541a4c3595c4c5d37a775d
1,024
// // Helper.swift // NSResultKitExample // // Created by Robert Armenski on 27.10.20. // import Foundation import NSResultKit enum RandomError: Error { case oddNumberFailure(Int) } extension RandomError: LocalizedError { var errorDescription: String? { switch self { case .oddNumberFailure(let number): return "Number \(number) is odd" @unknown default: return "Unknown" } } } @objc(Helper) public class Helper: NSObject { @objc public static func process(_ result: NSResult) { switch result.base { case .success(let value): print("Sucess: \(value)") case .failure(let error): print("Failure: \(error)") } } static var random: Result<Int, RandomError> { let val = Int.random(in: 0...100) return val.isMultiple(of: 2) ? .success(val) : .failure(.oddNumberFailure(val)) } @objc public static func randomResult() -> NSResult { .init(random) } }
22.26087
87
0.597656
8aa355c4a1ac84c90c00a948adab4b8aea001130
2,227
// // SerialDisposable.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ public final class SerialDisposable : DisposeBase, Cancelable { private var _lock = SpinLock() // state private var _current = nil as Disposable? private var _isDisposed = false /** - returns: Was resource disposed. */ public var isDisposed: Bool { return _isDisposed } /** Initializes a new instance of the `SerialDisposable`. */ override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return _lock.calculateLocked { return self.disposable } } set (newDisposable) { let disposable: Disposable? = _lock.calculateLocked { if _isDisposed { return newDisposable } else { let toDispose = _current _current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /** Disposes the underlying disposable as well as all future replacements. */ public func dispose() { _dispose()?.dispose() } private func _dispose() -> Disposable? { _lock.lock(); defer { _lock.unlock() } if _isDisposed { return nil } else { _isDisposed = true let current = _current _current = nil return current } } }
25.895349
192
0.566682
e50d7054a20d38eb448e6d997229261eb6c00e54
3,441
/* Copyright 2017 Avery Pierce 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 /// Represents a login flow public enum MXLoginFlowType { case password case recaptcha case OAuth2 case emailIdentity case token case dummy case emailCode case other(String) public var identifier: String { switch self { case .password: return kMXLoginFlowTypePassword case .recaptcha: return kMXLoginFlowTypeRecaptcha case .OAuth2: return kMXLoginFlowTypeOAuth2 case .emailIdentity: return kMXLoginFlowTypeEmailIdentity case .token: return kMXLoginFlowTypeToken case .dummy: return kMXLoginFlowTypeDummy case .emailCode: return kMXLoginFlowTypeEmailCode case .other(let value): return value } } public init(identifier: String) { let flowTypess: [MXLoginFlowType] = [.password, .recaptcha, .OAuth2, .emailIdentity, .token, .dummy, .emailCode] self = flowTypess.first(where: { $0.identifier == identifier }) ?? .other(identifier) } } /// Represents a mode for forwarding push notifications. public enum MXPusherKind { case http, none, custom(String) public var objectValue: NSObject { switch self { case .http: return "http" as NSString case .none: return NSNull() case .custom(let value): return value as NSString } } } /** Push rules kind. Push rules are separated into different kinds of rules. These categories have a priority order: verride rules have the highest priority. Some category may define implicit conditions. */ public enum MXPushRuleKind { case override, content, room, sender, underride public var identifier: __MXPushRuleKind { switch self { case .override: return __MXPushRuleKindOverride case .content: return __MXPushRuleKindContent case .room: return __MXPushRuleKindRoom case .sender: return __MXPushRuleKindSender case .underride: return __MXPushRuleKindUnderride } } public init?(identifier: __MXPushRuleKind?) { let pushRules: [MXPushRuleKind] = [.override, .content, .room, .sender, .underride] guard let pushRule = pushRules.first(where: { $0.identifier == identifier }) else { return nil } self = pushRule } } /** Scope for a specific push rule. Push rules can be applied globally, or to a spefific device given a `profileTag` */ public enum MXPushRuleScope { case global, device(profileTag: String) public var identifier: String { switch self { case .global: return "global" case .device(let profileTag): return "device/\(profileTag)" } } public init(identifier: String) { let scopes: [MXPushRuleScope] = [.global] self = scopes.first(where: { $0.identifier == identifier }) ?? .device(profileTag: identifier) } }
29.921739
120
0.684975
215fc59cc48f04b5e5751e03fb114b2d7d4e4291
1,532
/* * Copyright 2018 Tua Rua Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import FreSwift import FirebaseMLCommon import FirebaseMLModelInterpreter public extension ModelInputs { convenience init?(_ freObject: FREObject?) { guard let rv = freObject, let freInputs = rv["input"] else { return nil } self.init() let asByteArray = FreByteArraySwift(freByteArray: freInputs) if let byteData = asByteArray.value { do { try self.addInput(byteData) } catch let e as NSError { asByteArray.releaseBytes() FreSwiftLogger.shared.error(message: e.localizedDescription, type: .invalidArgument, line: #line, column: #column, file: #file) return nil } catch { asByteArray.releaseBytes() return nil } } asByteArray.releaseBytes() } }
34.044444
108
0.624674
f41d83506bf330e3e10498dd03450d9547df7794
1,100
// 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. // ALGAPI+Device.swift import Foundation import MagpieCore extension ALGAPI { @discardableResult func getAnnouncements( _ draft: AnnouncementFetchDraft, onCompleted handler: @escaping (Response.ModelResult<AnnouncementList>) -> Void ) -> EndpointOperatable { return EndpointBuilder(api: self) .base(.mobile) .path(.announcements, args: draft.deviceId) .method(.get) .completionHandler(handler) .execute() } }
32.352941
87
0.696364
f51ac4156533b0e0d4b0dfb3cad7d6827eb4d7d4
2,165
// // AppDelegate.swift // HRGCD // // Created by obgniyum on 01/22/2018. // Copyright (c) 2018 obgniyum. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.06383
285
0.753811
1dac1a4e5768fefac3985d1e51abdb1fe27319ad
690
// // AnswerGame.swift // arithmetical // // Created by Pedro Sandoval on 8/26/16. // Copyright © 2016 Sandoval Software. All rights reserved. // import Foundation import UIKit class AnswerGame: Game { var questionGenerator: ( () -> (String) )! /* Instantiate a AnswerGame object looks like the following: * Ex. */ init(name: String, summary: String, instructions: String, image: UIImage, selectionImage: UIImage, questionGenerator: @escaping () -> (String)) { super.init(name: name, summary: summary, instructions: instructions, image: image, selectionImage: selectionImage) self.questionGenerator = questionGenerator } }
27.6
149
0.673913
89822a3fc60104523f1826af3b58f7993fec2bcf
435
// // Bundle+BookReader.swift // // Created by Alex on 01/10/2018. // import Foundation internal class DummyBookReaderClass {} extension Bundle { static var bookReader: Bundle { get { let bundle = Bundle(for: DummyBookReaderClass.self) let bookReaderBundlePath = bundle.path(forResource: "BookReader", ofType: "bundle") return Bundle(path: bookReaderBundlePath!)! } } }
21.75
95
0.643678
294a4104257bbece5f79b9be313f02fb37c5a91e
896
import UIKit /// Represents an a proportional relationship between width and height. public struct AspectRatio { /// A 1:1 aspect ratio. public static let square = AspectRatio(ratio: 1) /// The width:height ratio value. public var ratio: CGFloat /// Initializes with a width & height ratio. /// /// - Parameter width: The relative width of the ratio. /// - Parameter height: The relative height of the ratio. public init(width: CGFloat, height: CGFloat) { self.init(ratio: width / height) } /// Initializes with a specific ratio. /// /// - Parameter ratio: The width:height ratio. public init(ratio: CGFloat) { self.ratio = ratio } func height(forWidth width: CGFloat) -> CGFloat { return width / ratio } func width(forHeight height: CGFloat) -> CGFloat { return height * ratio } }
26.352941
71
0.633929
2f031358b735468bb2c23d0ee26e7f03c4cd246a
1,729
// // Filter.swift // RxSwift // // Created by Krunoslav Zaher on 2/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class FilterSink<O : ObserverType>: Sink<O>, ObserverType { typealias Predicate = (Element) throws -> Bool typealias Element = O.E private let _predicate: Predicate init(predicate: @escaping Predicate, observer: O, cancel: Cancelable) { _predicate = predicate super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let satisfies = try _predicate(value) if satisfies { forwardOn(.next(value)) } } catch let e { forwardOn(.error(e)) dispose() } case .completed, .error: forwardOn(event) dispose() } } } class Filter<Element> : Producer<Element> { typealias Predicate = (Element) throws -> Bool private let _source: Observable<Element> private let _predicate: Predicate init(source: Observable<Element>, predicate: @escaping Predicate) { _source = source _predicate = predicate } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = FilterSink(predicate: _predicate, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
29.305085
144
0.569693
6288fc89587940d4de3ee9f50db837f14b934818
166
import CoreGraphics import Foundation internal protocol TimingParameters { var duration: TimeInterval { get } func value(at time: TimeInterval) -> CGFloat }
20.75
48
0.759036
c1d992bd0015818b71838289a5b5160361b6ff75
3,888
// // ProfileHeaderView.swift // LabShare-Front // // Created by Alexander Frazis on 20/9/20. // Copyright © 2020 CITS3200. All rights reserved. // import SwiftUI import Combine struct ProfileHeaderView: View { @EnvironmentObject var userAuthVM: UserAuthenticationViewModel @ObservedObject var profileVM: ProfileViewModel var body: some View { VStack(alignment: .leading) { CircleImageUpdatable(imageName: self.$profileVM.profile.owner.imageName) .padding(.leading, 30) .padding(.trailing, 30) HStack { Spacer() Text("\(self.profileVM.profile.owner.firstName) \(self.profileVM.profile.owner.lastName)") .font(.title) .fontWeight(.semibold) .padding() Spacer() } VStack (alignment: .leading, spacing: 7) { Text("About") .font(.title) .fontWeight(.medium) Text("Email: \(self.profileVM.profile.owner.email)") .fixedSize(horizontal: false, vertical: true) // Text("Born: \(self.profileVM.profile.dob)") // if profileVM.dobExists { // Text("Born: " + self.profileVM.dobString) // .fixedSize(horizontal: false, vertical: true) // } if profileVM.occupationExists { Text("Occupation: \(self.profileVM.profile.occupation)") .fixedSize(horizontal: false, vertical: true) } if profileVM.employerExists { Text("Employer: \(self.profileVM.profile.employer)") .fixedSize(horizontal: false, vertical: true) } if profileVM.bioExists { Text("Bio: \(self.profileVM.profile.bio)") .fixedSize(horizontal: false, vertical: true) } } }.padding() .navigationBarItems(trailing: Group { if (profileVM.profile.owner.id == userAuthVM.userAuth.id || userAuthVM.userAuth.isStaff) { NavigationLink ( destination: ProfileSettingsView(profileVM: self.profileVM), label: { Image(systemName: "line.horizontal.3").font(Font.largeTitle) } ) } }) .onAppear(perform: self.profileVM.getProfileClosure(userAuthVM: userAuthVM)) } } struct ProfileHeaderView_Previews: PreviewProvider { static var previews: some View { Group { ProfileHeaderView(profileVM: ProfileViewModel(userId: 72)) .environmentObject(UserAuthenticationViewModel(id: 72, token: "d4e3814547b0b328f3baae5ea78a3b1417464386", isLoggedIn: true, isStaff: true, isActive: true)) ProfileHeaderView(profileVM: ProfileViewModel(userId: 70)) .environmentObject(UserAuthenticationViewModel(id: 70, token: "356a0facdfb32b8720ada293893c4dae6267d406", isLoggedIn: true, isStaff: true, isActive: true)) // ProfileHeaderView(profileVM: ProfileViewModel(profile: ProfileModel(id: 37, bio: "I like programming and to study and to dance and to sing and to play baseball and to play soccer and to play jazz", dob: Date(), occupation: "Student", employer: "University of Western Australia", owner: UserModel(id: 37, email: "[email protected]", firstName: "Alexander", lastName: "Frazis")))) // .environmentObject(UserAuthenticationViewModel(id: 37, token: "14f2518e6ffc20cf52642b7c7d51b63b88fe127f", isLoggedIn: true)) } } }
42.725275
400
0.5643
875c3f1b07450fac5f465a6c49ce3619212912df
2,101
// // APIEndpoints.swift // WhatToWatch // // Created by Denis Novitsky on 23.04.2021. // import Foundation struct APIEndpoints { static func fetchTrends(type: MediaType, timeWindow: TimeWindow, page: Int) -> Endpoint<MediaPageDTO> { let mediaString = APIEndpoints.mediaString(from: type) let timeWindowString = APIEndpoints.timeWindowString(from: timeWindow) return .init(path: "3/trending/\(mediaString)/\(timeWindowString)", method: .get, queryParameters: ["page": page]) } static func fetchMediaList(type: MediaType, query: String, page: Int) -> Endpoint<MediaPageDTO> { let mediaString = APIEndpoints.mediaString(from: type) return .init(path: "3/search/\(mediaString)", method: .get, queryParameters: ["query": query, "page": page]) } static func fetchMedia(type: MediaType, id: Int) -> Endpoint<MediaDTO> { let mediaString = APIEndpoints.mediaString(from: type) return .init(path: "3/\(mediaString)/\(id)", method: .get, queryParameters: ["append_to_response": "credits,combined_credits"]) } static func fetchMediaImage(path: String, width: Int) -> Endpoint<Data> { // TODO: Load from server // From API documentation let sizes = [45, 92, 154, 185, 300, 342, 500, 780, 1280] let closestWidth = sizes.min { abs($0 - width) < abs($1 - width) }! return .init(path: "t/p/w\(closestWidth)\(path)", method: .get, responseDecoder: RawDataResponseDecoder()) } // MARK: - Mapping private static func timeWindowString(from timeWindow: TimeWindow) -> String { switch timeWindow { case .day: return "day" case .week: return "week" } } private static func mediaString(from type: MediaType) -> String { switch type { case .movie: return "movie" case .tv: return "tv" case .person: return "person" } } }
31.833333
107
0.588767
0ee208d1e5b61c44063effe376905bd3f35ed360
675
// // CrashCell.swift // MTC-Rat // // Created by Кирилл Володин on 29.09.17. // Copyright © 2017 Кирилл Володин. All rights reserved. // import UIKit class CrashCell: UITableViewCell { @IBOutlet weak var statusImage: UIImageView! @IBOutlet weak var codeLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var shortDescription: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.774194
65
0.66963
bbbd4ed92814310e7e8e8b478632db54581000c2
14,775
// Generated using Sourcery 0.18.0 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // Generated with SwiftyMocky 4.0.0 import SwiftyMocky import XCTest import HealthKit import CoreData import Presentr import CSV import SwiftDate import UserNotifications import Instructions @testable import Introspective @testable import AttributeRestrictions @testable import Attributes @testable import BooleanAlgebra @testable import Common @testable import DataExport @testable import DataImport @testable import DependencyInjection @testable import Notifications @testable import Persistence @testable import Queries @testable import SampleGroupers @testable import SampleGroupInformation @testable import Samples @testable import Settings @testable import UIExtensions // MARK: - AttributeRestrictionFactory open class AttributeRestrictionFactoryMock: AttributeRestrictionFactory, Mock { public init(sequencing sequencingPolicy: SequencingPolicy = .lastWrittenResolvedFirst, stubbing stubbingPolicy: StubbingPolicy = .wrap, file: StaticString = #file, line: UInt = #line) { SwiftyMockyTestObserver.setup() self.sequencingPolicy = sequencingPolicy self.stubbingPolicy = stubbingPolicy self.file = file self.line = line } var matcher: Matcher = Matcher.default var stubbingPolicy: StubbingPolicy = .wrap var sequencingPolicy: SequencingPolicy = .lastWrittenResolvedFirst private var invocations: [MethodType] = [] private var methodReturnValues: [Given] = [] private var methodPerformValues: [Perform] = [] private var file: StaticString? private var line: UInt? public typealias PropertyStub = Given public typealias MethodStub = Given public typealias SubscriptStub = Given /// Convenience method - call setupMock() to extend debug information when failure occurs public func setupMock(file: StaticString = #file, line: UInt = #line) { self.file = file self.line = line } /// Clear mock internals. You can specify what to reset (invocations aka verify, givens or performs) or leave it empty to clear all mock internals public func resetMock(_ scopes: MockScope...) { let scopes: [MockScope] = scopes.isEmpty ? [.invocation, .given, .perform] : scopes if scopes.contains(.invocation) { invocations = [] } if scopes.contains(.given) { methodReturnValues = [] } if scopes.contains(.perform) { methodPerformValues = [] } } private static func isCapturing<T>(_ param: Parameter<T>) -> Bool { switch param { // can't use `case .capturing(_, _):` here because it causes an EXC_BAD_ACCESS error case .value(_): return false case .matching(_): return false case ._: return false default: return true } } open func typesFor(_ attribute: Attribute) -> [AttributeRestriction.Type] { addInvocation(.m_typesFor__attribute(Parameter<Attribute>.value(`attribute`))) let perform = methodPerformValue(.m_typesFor__attribute(Parameter<Attribute>.value(`attribute`))) as? (Attribute) -> Void perform?(`attribute`) var __value: [AttributeRestriction.Type] do { __value = try methodReturnValue(.m_typesFor__attribute(Parameter<Attribute>.value(`attribute`))).casted() } catch { onFatalFailure("Stub return value not specified for typesFor(_ attribute: Attribute). Use given") Failure("Stub return value not specified for typesFor(_ attribute: Attribute). Use given") } return __value } open func initialize(type: AttributeRestriction.Type, forAttribute attribute: Attribute) -> AttributeRestriction { addInvocation(.m_initialize__type_typeforAttribute_attribute(Parameter<AttributeRestriction.Type>.value(`type`), Parameter<Attribute>.value(`attribute`))) let perform = methodPerformValue(.m_initialize__type_typeforAttribute_attribute(Parameter<AttributeRestriction.Type>.value(`type`), Parameter<Attribute>.value(`attribute`))) as? (AttributeRestriction.Type, Attribute) -> Void perform?(`type`, `attribute`) var __value: AttributeRestriction do { __value = try methodReturnValue(.m_initialize__type_typeforAttribute_attribute(Parameter<AttributeRestriction.Type>.value(`type`), Parameter<Attribute>.value(`attribute`))).casted() } catch { onFatalFailure("Stub return value not specified for initialize(type: AttributeRestriction.Type, forAttribute attribute: Attribute). Use given") Failure("Stub return value not specified for initialize(type: AttributeRestriction.Type, forAttribute attribute: Attribute). Use given") } return __value } fileprivate enum MethodType { case m_typesFor__attribute(Parameter<Attribute>) case m_initialize__type_typeforAttribute_attribute(Parameter<AttributeRestriction.Type>, Parameter<Attribute>) static func compareParameters(lhs: MethodType, rhs: MethodType, matcher: Matcher) -> Matcher.ComparisonResult { switch (lhs, rhs) { case (.m_typesFor__attribute(let lhsAttribute), .m_typesFor__attribute(let rhsAttribute)): var noncapturingComparisons: [Bool] = [] var comparison: Bool var results: [Matcher.ParameterComparisonResult] = [] if !isCapturing(lhsAttribute) && !isCapturing(rhsAttribute) { comparison = Parameter.compare(lhs: lhsAttribute, rhs: rhsAttribute, with: matcher) noncapturingComparisons.append(comparison) results.append(Matcher.ParameterComparisonResult(comparison, lhsAttribute, rhsAttribute, "_ attribute")) } if isCapturing(lhsAttribute) || isCapturing(rhsAttribute) { comparison = Parameter.compare(lhs: lhsAttribute, rhs: rhsAttribute, with: matcher, nonCapturingParamsMatch: noncapturingComparisons.allSatisfy({$0})) results.append(Matcher.ParameterComparisonResult(comparison, lhsAttribute, rhsAttribute, "_ attribute")) } return Matcher.ComparisonResult(results) case (.m_initialize__type_typeforAttribute_attribute(let lhsType, let lhsAttribute), .m_initialize__type_typeforAttribute_attribute(let rhsType, let rhsAttribute)): var noncapturingComparisons: [Bool] = [] var comparison: Bool var results: [Matcher.ParameterComparisonResult] = [] if !isCapturing(lhsType) && !isCapturing(rhsType) { comparison = Parameter.compare(lhs: lhsType, rhs: rhsType, with: matcher) noncapturingComparisons.append(comparison) results.append(Matcher.ParameterComparisonResult(comparison, lhsType, rhsType, "type")) } if !isCapturing(lhsAttribute) && !isCapturing(rhsAttribute) { comparison = Parameter.compare(lhs: lhsAttribute, rhs: rhsAttribute, with: matcher) noncapturingComparisons.append(comparison) results.append(Matcher.ParameterComparisonResult(comparison, lhsAttribute, rhsAttribute, "forAttribute attribute")) } if isCapturing(lhsType) || isCapturing(rhsType) { comparison = Parameter.compare(lhs: lhsType, rhs: rhsType, with: matcher, nonCapturingParamsMatch: noncapturingComparisons.allSatisfy({$0})) results.append(Matcher.ParameterComparisonResult(comparison, lhsType, rhsType, "type")) } if isCapturing(lhsAttribute) || isCapturing(rhsAttribute) { comparison = Parameter.compare(lhs: lhsAttribute, rhs: rhsAttribute, with: matcher, nonCapturingParamsMatch: noncapturingComparisons.allSatisfy({$0})) results.append(Matcher.ParameterComparisonResult(comparison, lhsAttribute, rhsAttribute, "forAttribute attribute")) } return Matcher.ComparisonResult(results) default: return .none } } func intValue() -> Int { switch self { case let .m_typesFor__attribute(p0): return p0.intValue case let .m_initialize__type_typeforAttribute_attribute(p0, p1): return p0.intValue + p1.intValue } } func assertionName() -> String { switch self { case .m_typesFor__attribute: return ".typesFor(_:)" case .m_initialize__type_typeforAttribute_attribute: return ".initialize(type:forAttribute:)" } } } open class Given: StubbedMethod { fileprivate var method: MethodType private init(method: MethodType, products: [StubProduct]) { self.method = method super.init(products) } public static func typesFor(_ attribute: Parameter<Attribute>, willReturn: [AttributeRestriction.Type]...) -> MethodStub { return Given(method: .m_typesFor__attribute(`attribute`), products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func initialize(type: Parameter<AttributeRestriction.Type>, forAttribute attribute: Parameter<Attribute>, willReturn: AttributeRestriction...) -> MethodStub { return Given(method: .m_initialize__type_typeforAttribute_attribute(`type`, `attribute`), products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func typesFor(_ attribute: Parameter<Attribute>, willProduce: (Stubber<[AttributeRestriction.Type]>) -> Void) -> MethodStub { let willReturn: [[AttributeRestriction.Type]] = [] let given: Given = { return Given(method: .m_typesFor__attribute(`attribute`), products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: ([AttributeRestriction.Type]).self) willProduce(stubber) return given } public static func initialize(type: Parameter<AttributeRestriction.Type>, forAttribute attribute: Parameter<Attribute>, willProduce: (Stubber<AttributeRestriction>) -> Void) -> MethodStub { let willReturn: [AttributeRestriction] = [] let given: Given = { return Given(method: .m_initialize__type_typeforAttribute_attribute(`type`, `attribute`), products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: (AttributeRestriction).self) willProduce(stubber) return given } } public struct Verify { fileprivate var method: MethodType public static func typesFor(_ attribute: Parameter<Attribute>) -> Verify { return Verify(method: .m_typesFor__attribute(`attribute`))} public static func initialize(type: Parameter<AttributeRestriction.Type>, forAttribute attribute: Parameter<Attribute>) -> Verify { return Verify(method: .m_initialize__type_typeforAttribute_attribute(`type`, `attribute`))} } public struct Perform { fileprivate var method: MethodType var performs: Any public static func typesFor(_ attribute: Parameter<Attribute>, perform: @escaping (Attribute) -> Void) -> Perform { return Perform(method: .m_typesFor__attribute(`attribute`), performs: perform) } public static func initialize(type: Parameter<AttributeRestriction.Type>, forAttribute attribute: Parameter<Attribute>, perform: @escaping (AttributeRestriction.Type, Attribute) -> Void) -> Perform { return Perform(method: .m_initialize__type_typeforAttribute_attribute(`type`, `attribute`), performs: perform) } } public func given(_ method: Given) { methodReturnValues.append(method) } public func perform(_ method: Perform) { methodPerformValues.append(method) methodPerformValues.sort { $0.method.intValue() < $1.method.intValue() } } public func verify(_ method: Verify, count: Count = Count.moreOrEqual(to: 1), file: StaticString = #file, line: UInt = #line) { let fullMatches = matchingCalls(method, file: file, line: line) let success = count.matches(fullMatches) let assertionName = method.method.assertionName() let feedback: String = { guard !success else { return "" } return Utils.closestCallsMessage( for: self.invocations.map { invocation in matcher.set(file: file, line: line) defer { matcher.clearFileAndLine() } return MethodType.compareParameters(lhs: invocation, rhs: method.method, matcher: matcher) }, name: assertionName ) }() MockyAssert(success, "Expected: \(count) invocations of `\(assertionName)`, but was: \(fullMatches).\(feedback)", file: file, line: line) } private func addInvocation(_ call: MethodType) { invocations.append(call) } private func methodReturnValue(_ method: MethodType) throws -> StubProduct { matcher.set(file: self.file, line: self.line) defer { matcher.clearFileAndLine() } let candidates = sequencingPolicy.sorted(methodReturnValues, by: { $0.method.intValue() > $1.method.intValue() }) let matched = candidates.first(where: { $0.isValid && MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher).isFullMatch }) guard let product = matched?.getProduct(policy: self.stubbingPolicy) else { throw MockError.notStubed } return product } private func methodPerformValue(_ method: MethodType) -> Any? { matcher.set(file: self.file, line: self.line) defer { matcher.clearFileAndLine() } let matched = methodPerformValues.reversed().first { MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher).isFullMatch } return matched?.performs } private func matchingCalls(_ method: MethodType, file: StaticString?, line: UInt?) -> [MethodType] { matcher.set(file: file ?? self.file, line: line ?? self.line) defer { matcher.clearFileAndLine() } return invocations.filter { MethodType.compareParameters(lhs: $0, rhs: method, matcher: matcher).isFullMatch } } private func matchingCalls(_ method: Verify, file: StaticString?, line: UInt?) -> Int { return matchingCalls(method.method, file: file, line: line).count } private func givenGetterValue<T>(_ method: MethodType, _ message: String) -> T { do { return try methodReturnValue(method).casted() } catch { onFatalFailure(message) Failure(message) } } private func optionalGivenGetterValue<T>(_ method: MethodType, _ message: String) -> T? { do { return try methodReturnValue(method).casted() } catch { return nil } } private func onFatalFailure(_ message: String) { guard let file = self.file, let line = self.line else { return } // Let if fail if cannot handle gratefully SwiftyMockyTestObserver.handleFatalError(message: message, file: file, line: line) } }
46.904762
231
0.700305
4889e3cae32eaf860207987c315b77edf4c72482
945
#if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif public class ImageDownloadRequest: NetworkRequest { #if canImport(UIKit) public typealias Output = UIImage #elseif canImport(AppKit) public typealias Output = NSImage #endif public let url: URL? public let urlSession: URLSession public let finishingQueue: DispatchQueue public let requestMethod: NetworkRequestMethod public let authentication: NetworkRequestAuthentication? public init( url: URL?, urlSession: URLSession = .shared, finishingQueue: DispatchQueue = .main, requestMethod: NetworkRequestMethod = .get, authentication: NetworkRequestAuthentication? = nil) { self.url = url self.urlSession = urlSession self.finishingQueue = finishingQueue self.requestMethod = requestMethod self.authentication = authentication } }
26.25
60
0.701587
1e1265f64dd8ec72c4b02872243b4b8549f58743
443
// Copyright 2017-2020 Fitbit, Inc // SPDX-License-Identifier: Apache-2.0 // // UILabel+Rx.swift // BluetoothConnection // // Created by Marcel Jackwerth on 11/20/17. // #if os(iOS) import Foundation import RxCocoa import RxSwift import UIKit extension Reactive where Base: UILabel { var textColor: Binder<UIColor?> { return Binder(self.base) { label, color in label.textColor = color } } } #endif
17.038462
50
0.663657
f8e5cb19c44a14d27ff59a873feca86564a7d8ef
17,695
// // ChatViewController.swift // TrackingAdvisor // // Created by Benjamin BARON on 5/22/18. // Copyright © 2018 Benjamin BARON. All rights reserved. // import Foundation import UIKit import Alamofire struct Message : Codable { let text: String let timestamp: Date let sender: Bool } class ChatViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private var collectionView: UICollectionView! private let cellId = "cellId" var friend: String? { didSet { navigationItem.title = friend } } let messageInputContainerView: UIView = { let view = UIView() view.backgroundColor = UIColor.white view.translatesAutoresizingMaskIntoConstraints = false return view }() let inputTextField: UITextField = { let textField = UITextField() textField.placeholder = "Enter message..." textField.translatesAutoresizingMaskIntoConstraints = false return textField }() lazy var sendButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Send", for: .normal) let titleColor = UIColor(red: 0, green: 137/255, blue: 249/255, alpha: 1) button.setTitleColor(titleColor, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(handleSend), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() private func scrollToLastMessage() { // scroll to the last message if messages.count > 0 { let lastItem = self.messages.count - 1 let indexPath = IndexPath(item: lastItem, section: 0) self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true) } } func createMessage(with text: String, minutesAgo: Double, sender: Bool = false) -> Message { let message = Message(text: text, timestamp: Date().addingTimeInterval(-minutesAgo * 60), sender: sender) return message } @objc func handleSend() { if let text = inputTextField.text { let message = createMessage(with: text, minutesAgo: 0, sender: true) messages.append(message) send(message: message) { [unowned self] in self.scrollToLastMessage() } } inputTextField.text = nil } var messages: [Message] = [] { didSet { collectionView?.reloadData() scrollToLastMessage() }} var bottomConstraint: NSLayoutConstraint? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = true getAllMessages() { [unowned self] res in self.messages = res self.scrollToLastMessage() self.collectionView.contentInset = UIEdgeInsets(top: 64.0, left: 0.0, bottom: 0.0, right: 0.0) self.collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 64.0, left: 0.0, bottom: 0.0, right: 0.0) } } @objc func back(sender: UIBarButtonItem) { self.navigationController!.popToRootViewController(animated: true) } override func viewDidLoad() { super.viewDidLoad() // change the behaviour of the back button self.navigationItem.hidesBackButton = true let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(back(sender:))) self.navigationItem.leftBarButtonItem = newBackButton view.backgroundColor = .white let frame = UIScreen.main.bounds collectionView = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.dataSource = self collectionView.delegate = self collectionView.showsHorizontalScrollIndicator = false collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 250, height: 100) flowLayout.minimumInteritemSpacing = 3 flowLayout.minimumLineSpacing = 3 flowLayout.scrollDirection = .vertical collectionView.collectionViewLayout = flowLayout collectionView.register(ChatLogMessageCell.self, forCellWithReuseIdentifier: cellId) view.addSubview(collectionView) view.addVisualConstraint("H:|[collection]|", views: ["collection": collectionView]) view.addSubview(messageInputContainerView) view.addVisualConstraint("H:|[v0]|", views: ["v0": messageInputContainerView]) view.addVisualConstraint("V:|[collection]-[v0(48)]", views: ["collection": collectionView, "v0": messageInputContainerView]) bottomConstraint = NSLayoutConstraint(item: messageInputContainerView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) if AppDelegate.isIPhoneX() { bottomConstraint?.constant = -15 } view.addConstraint(bottomConstraint!) view.layoutIfNeeded() setupInputComponents() NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func handleKeyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0 UIView.animate(withDuration: 0, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.view.layoutIfNeeded() }, completion: { [unowned self] (completed) in if isKeyboardShowing && self.messages.count > 0 { let lastItem = self.messages.count - 1 let indexPath = IndexPath(item: lastItem, section: 0) self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true) } }) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { inputTextField.endEditing(true) } private func setupInputComponents() { let topBorderView = UIView() topBorderView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) topBorderView.translatesAutoresizingMaskIntoConstraints = false messageInputContainerView.addSubview(inputTextField) messageInputContainerView.addSubview(sendButton) messageInputContainerView.addSubview(topBorderView) messageInputContainerView.addVisualConstraint("H:|-8-[v0][v1(60)]|", views: ["v0": inputTextField, "v1": sendButton]) messageInputContainerView.addVisualConstraint("V:|[v0]|", views: ["v0": inputTextField]) messageInputContainerView.addVisualConstraint("V:|[v0]|", views: ["v0": sendButton]) messageInputContainerView.addVisualConstraint("H:|[v0]|", views: ["v0": topBorderView]) messageInputContainerView.addVisualConstraint("V:|[v0(0.5)]", views: ["v0": topBorderView]) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatLogMessageCell var nextMessage: Message? = nil if messages.count > indexPath.item+1 { nextMessage = messages[indexPath.item+1] } let message = messages[indexPath.item] cell.messageTextView.text = message.text cell.profileImageView.image = UIImage(named: "user-circle") let constraintRect = CGSize(width: 250, height: 1000) let estimatedFrame = message.text.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : UIFont.systemFont(ofSize: 18)], context: nil) if !message.sender { cell.messageTextView.frame = CGRect(x: 48 + 8, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 20) cell.textBubbleView.frame = CGRect(x: 48 - 10, y: -4, width: estimatedFrame.width + 16 + 8 + 16, height: estimatedFrame.height + 20 + 6) cell.profileImageView.isHidden = false if let msg = nextMessage, !msg.sender { cell.bubbleImageView.image = ChatLogMessageCell.grayTailBubbleImage } else { cell.bubbleImageView.image = ChatLogMessageCell.grayBubbleImage } cell.bubbleImageView.tintColor = UIColor(white: 0.95, alpha: 1) cell.messageTextView.textColor = UIColor.black } else { //outgoing sending message cell.messageTextView.frame = CGRect(x: view.frame.width - estimatedFrame.width - 40, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 20) cell.textBubbleView.frame = CGRect(x: view.frame.width - estimatedFrame.width - 50, y: -4, width: estimatedFrame.width + 34, height: estimatedFrame.height + 26) cell.profileImageView.isHidden = true if let msg = nextMessage, msg.sender { cell.bubbleImageView.image = ChatLogMessageCell.blueTailBubbleImage } else { cell.bubbleImageView.image = ChatLogMessageCell.blueBubbleImage } cell.bubbleImageView.tintColor = UIColor(red: 0, green: 137/255, blue: 249/255, alpha: 1) cell.messageTextView.textColor = UIColor.white } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let message = messages[indexPath.item] let constraintRect = CGSize(width: 250, height: 1000) let estimatedFrame = message.text.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : UIFont.systemFont(ofSize: 18)], context: nil) var nextMessage: Message? = nil if messages.count > indexPath.item+1 { nextMessage = messages[indexPath.item+1] } var offset: CGFloat = 20.0 if nextMessage != nil && nextMessage!.sender != message.sender { offset = 35.0 } return CGSize(width: view.frame.width, height: estimatedFrame.height + offset) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0) } // MARK: - Communicate with the server private func getAllMessages(callback: (([Message])->Void)? = nil) { DispatchQueue.global(qos: .background).async { let userid = Settings.getUserId() ?? "" let parameters: Parameters = [ "userid": userid ] Alamofire.request(Constants.urls.getAllMessagesURL, method: .get, parameters: parameters).responseJSON { response in LogService.shared.log(LogService.types.serverResponse, args: [LogService.args.responseMethod: "get", LogService.args.responseUrl: Constants.urls.getAllMessagesURL, LogService.args.responseCode: String(response.response?.statusCode ?? 0)]) if response.result.isSuccess { guard let data = response.data else { return } do { let decoder = JSONDecoder() let res = try decoder.decode([Message].self, from: data) callback?(res) } catch { print("Error serializing the json", error) } } else { print("Error in response \(response.result)") } } } } private func send(message: Message, callback: (()->Void)? = nil) { DispatchQueue.global(qos: .background).async { let userid = Settings.getUserId() ?? "" let parameters: Parameters = [ "userid": userid, "message": message.text, "timestamp": message.timestamp.localTime ] Alamofire.request(Constants.urls.sendMessageURL, method: .get, parameters: parameters).responseJSON { response in LogService.shared.log(LogService.types.serverResponse, args: [LogService.args.responseMethod: "get", LogService.args.responseUrl: Constants.urls.sendMessageURL, LogService.args.responseCode: String(response.response?.statusCode ?? 0)]) if response.result.isSuccess { guard let data = response.data else { return } do { let decoder = JSONDecoder() _ = try decoder.decode([String:String].self, from: data) callback?() } catch { print("Error serializing the json", error) } } else { print("Error in response \(response.result)") } } } } } fileprivate class ChatLogMessageCell: BaseCell { let messageTextView: UITextView = { let textView = UITextView() textView.font = UIFont.systemFont(ofSize: 18) textView.text = "Sample message" textView.backgroundColor = UIColor.clear return textView }() let textBubbleView: UIView = { let view = UIView() view.layer.cornerRadius = 15 view.layer.masksToBounds = true return view }() let profileImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 15 imageView.layer.masksToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() static let grayBubbleImage = UIImage(named: "bubble_gray")!.resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26)).withRenderingMode(.alwaysTemplate) static let blueBubbleImage = UIImage(named: "bubble_blue")!.resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26)).withRenderingMode(.alwaysTemplate) static let blueTailBubbleImage = UIImage(named: "bubble_sender")!.resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26)).withRenderingMode(.alwaysTemplate) static let grayTailBubbleImage = UIImage(named: "bubble_receiver")!.resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26)).withRenderingMode(.alwaysTemplate) let bubbleImageView: UIImageView = { let imageView = UIImageView() imageView.image = ChatLogMessageCell.grayBubbleImage imageView.tintColor = UIColor(white: 0.90, alpha: 1) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() override func setupViews() { super.setupViews() addSubview(textBubbleView) addSubview(messageTextView) addSubview(profileImageView) addVisualConstraint("H:|-8-[v0(30)]", views: ["v0": profileImageView]) addVisualConstraint("V:[v0(30)]|", views: ["v0": profileImageView]) textBubbleView.addSubview(bubbleImageView) textBubbleView.addVisualConstraint("H:|[v0]|", views: ["v0": bubbleImageView]) textBubbleView.addVisualConstraint("V:|[v0]|", views: ["v0": bubbleImageView]) translatesAutoresizingMaskIntoConstraints = false } } fileprivate class BaseCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { } }
42.434053
192
0.620458
16114fada0dd3bbb0fcf496d74602cca7b095f72
1,016
import Foundation public struct CurrentOrderSummaryReport: Codable { public struct CurrentOrderSummary: Codable { public let betId: String public let marketId: String public let selectionId: Int public let handicap: Double public let priceSize: PriceSize public let bspLiability: Double public let side: Side public let status: OrderStatus public let persistenceType: PersistenceType public let orderType: OrderType public let placedDate: Date public let matchedDate: Date? public let averagePriceMatched: Double? public let sizeMatched: Double? public let sizeRemaining: Double? public let sizeLapsed: Double? public let sizeCancelled: Double? public let sizeVoided: Double? public let customerOrderRef: String? public let customerStrategyRef: String? } public let moreAvailable: Bool public let currentOrders: [CurrentOrderSummary] } public struct PriceSize: Codable { public let price: Double public let size: Double }
29.882353
50
0.75
1ad9f5afe4c9cf5051473920c8cb21a4b5c2e046
2,557
// // AppDelegate.swift // XBackgroundManager // // Created by dte2mdj on 03/31/2020. // Copyright (c) 2020 dte2mdj. All rights reserved. // import UIKit import XBackgroundManager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? #if swift(>=5.0) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { XBackgroundManager.shared.enabled = true return true } #else func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. XBackgroundManager.shared.enabled = true return true } #endif func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
42.616667
285
0.737583
1cba077f4b6b2e5aa71d4e3cd637963ea0be66eb
1,424
// // LoggerUITests.swift // LoggerUITests // // Created by Anton Kononenko on 9/18/21. // import XCTest class LoggerUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.116279
182
0.655197
f5951f0509ff884dbc076713d81249134ac4250f
3,622
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif /** Superclass for those `Attribute` objects that imply dimension constraints like width and height */ open class DimensionAttribute: Attribute { /// Whether the `NSLayoutConstraint` generated by the /// `Attribute` is owned by the the `createItem` open override var ownedByItem: Bool { return true } } /** The width of the object’s alignment rectangle */ public class Width: DimensionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .width } } /** The height of the object’s alignment rectangle */ public class Height: DimensionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .height } } /** The size of the object’s rectangle */ public class Size: CompoundAttribute { /** Initializer which creates a `CompountAttribute` instance formed by `Width` and `Height` attributes with `constant = 0.0`, `multiplier = 1.0` and `relatedBy = .Equal` - returns: the `CompoundAttribute` instance created */ public override init() { super.init() self.attributes = [ Width(), Height() ] } /** Initializer which creates a `CompountAttribute` instance formed by `Width` and `Height` attributes with `constant = value`, `multiplier = 1.0` and `relatedBy = .Equal` - parameter value: `constant` of the constraint - returns: the `CompoundAttribute` instance created */ public override init(_ value: CGFloat) { super.init() self.attributes = [ Width(value), Height(value) ] } /** Initializer which creates a `CompountAttribute` instance formed by `Width` and `Height` attributes with the `constant`, `multiplier` and `relatedBy` defined by the `Constant` supplied - parameter constant: `Constant` struct aggregating `constant`, `multiplier` and `relatedBy` properties - returns: the `CompoundAttribute` instance created */ public override init(_ constant: Constant) { super.init() self.attributes = [ Width(constant), Height(constant) ] } /** Initializer which creates a `CompountAttribute` instance formed by `Width` and `Height` attributes with `constant = size.width` and `constant = size.height` respectively, `multiplier = 1.0` and `relatedBy = .Equal` - parameter size: `CGSize` that sets the constants for the `Width` and `Height` *subattributes* - returns: the `CompoundAttribute` instance created */ public init(_ size: CGSize) { super.init() self.attributes = [ Width(CGFloat(size.width)), Height(CGFloat(size.height)) ] } }
29.447154
80
0.632247
642248479dbcd914bd0e2359e5da2bcc0df58700
251
// // RoomGroupVo.swift // DYTV // // Created by 寂惺 on 2018/7/10. // Copyright © 2018年 haha. All rights reserved. // import Foundation struct RoomGroupVo { var roomList : [RoomVo]? var headerIcon : String? var headerName : String? }
15.6875
48
0.649402
296791d91d31c0d20081614a54d49270eea3bc09
103
import Common public let logger = LightLogger.self public let analytics = Analytics<AnalyticsEvent>()
20.6
50
0.805825
91868b3af9a012ac4f1407b782b18826a9dbb0e9
1,012
// // AppDelegate.swift // PrinceOfVersionsSample // // Created by Jasmin Abou Aldan on 13/09/2019. // Copyright © 2019 infinum. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Uncomment version that you want to build: createAndShowViewController(with: "SwiftAppSample") // createAndShowViewController(with: "ObjCAppSample") return true } } private extension AppDelegate { func createAndShowViewController(with identifier: String) { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier) window?.rootViewController = viewController window?.makeKeyAndVisible() } }
28.914286
145
0.729249
e4dc96ec70431d6a71b536c113ca3d4eebd54d0c
2,350
// // MussicListViewModel.swift // iTunesPlayer // // Created by Ferdinando Furci on 20/03/2020. // Copyright © 2020 Ferdinando Furci. All rights reserved. // import Foundation // MARK: - SortingOptions enum SortingOptions: Int { case length = 0 case genre = 1 case price = 2 } // MARK: - MusicListViewModelProtocol protocol MusicListViewModelProtocol { var dataset: [Song] { get } init(with dataSource: MusicListDatasourceProtocol) func getMusicData(with parameters: String) func sortDataset(sortingOption: SortingOptions) } // MARK: - MusicListViewModelDelegate protocol MusicListViewModelDelegate: class { func MusicListViewModel(didUpdate songs: [Song]) func MusicListViewModel(shouldShowActivityIndicator: Bool) func MusicListViewModel(willShow error: Error?) } // MARK: - MusicListViewModel final class MusicListViewModel: MusicListViewModelProtocol { // MARK: Private properties private (set)var dataset: [Song] = [] private let datasource: MusicListDatasourceProtocol weak var delegate: MusicListViewModelDelegate? // MARK: Initialization init(with dataSource: MusicListDatasourceProtocol) { self.datasource = dataSource } // MARK: Protocol functions func getMusicData(with parameters: String) { guard !parameters.isEmpty else { return } self.delegate?.MusicListViewModel(shouldShowActivityIndicator: true) datasource.fetch(with: parameters) { [weak self] (result: Result<Songlist, Error>) in guard let self = self else { return } self.delegate?.MusicListViewModel(shouldShowActivityIndicator: false) switch result { case .success(let songs): self.delegate?.MusicListViewModel(willShow: nil) self.dataset = songs.results self.delegate?.MusicListViewModel(didUpdate: songs.results) case .failure(let error): self.delegate?.MusicListViewModel(willShow: error) } } } func sortDataset(sortingOption: SortingOptions) { switch sortingOption { case .length: dataset.sort { $0.duration.localizedStandardCompare($1.duration) == .orderedAscending } delegate?.MusicListViewModel(didUpdate: dataset) case .genre: dataset.sort { $0.genre < $1.genre } delegate?.MusicListViewModel(didUpdate: dataset) case .price: dataset.sort { $0.trackPrice ?? 0 < $1.trackPrice ?? 0 } delegate?.MusicListViewModel(didUpdate: dataset) } } }
28.313253
90
0.746809
4a46ceffda2d1d55e265ca8e92920d4b55a9ff1a
1,657
// // IMDownloadImagesTest.swift // iMoviesTests // // Created by Ricardo Casanova on 04/09/2018. // Copyright © 2018 Careem. All rights reserved. // import XCTest @testable import iMovies class IMDownloadImagesTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testDownloadImageWithUrl(_ url: URL?) { let getImageExpectation: XCTestExpectation = self.expectation(description: "image") let imageView = UIImageView() imageView.frame = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0) guard let url = url else { XCTFail("impossible to get the url") return } imageView.hnk_setImage(from: url, placeholder: nil, success: { (image) in XCTAssertNotNil(image) getImageExpectation.fulfill() }) { (error) in XCTFail("something went wrong getting the image from the url") } self.waitForExpectations(timeout: 20.0, handler: nil) } func testDownloadTMDBSmallImage() { let url = IMMovieImageManager.getSmalImageUrlWith("/pTpxQB1N0waaSc3OSn0e9oc8kx9.jpg") testDownloadImageWithUrl(url) } func testDownloadTMDBMediumImage() { let url = IMMovieImageManager.getMediumImageUrlWith("/pTpxQB1N0waaSc3OSn0e9oc8kx9.jpg") testDownloadImageWithUrl(url) } func testDownloadTMDBLargeImage() { let url = IMMovieImageManager.getLargeImageUrlWith("/pTpxQB1N0waaSc3OSn0e9oc8kx9.jpg") testDownloadImageWithUrl(url) } }
29.070175
95
0.639107
e476c1c426852a623fea9ec29333ecd88a21abc1
2,821
// // ReviewViewController.swift // WeScan // // Created by Boris Emorine on 2/25/18. // Copyright © 2018 WeTransfer. All rights reserved. // import UIKit /// The `ReviewViewController` offers an interface to review the image after it has been cropped and deskwed according to the passed in quadrilateral. final class ReviewViewController: UIViewController { lazy private var imageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.isOpaque = true imageView.image = results.scannedImage imageView.backgroundColor = .black imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() lazy private var doneButton: UIBarButtonItem = { let title = NSLocalizedString("wescan.review.button.done", tableName: nil, bundle: Bundle(for: ReviewViewController.self), value: "Done", comment: "A generic done button") let button = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(finishScan)) button.tintColor = navigationController?.navigationBar.tintColor return button }() private let results: ImageScannerResults // MARK: - Life Cycle init(results: ImageScannerResults) { self.results = results super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() title = NSLocalizedString("wescan.review.title", tableName: nil, bundle: Bundle(for: ReviewViewController.self), value: "Review", comment: "The review title of the ReviewController") navigationItem.rightBarButtonItem = doneButton } // MARK: Setups private func setupViews() { view.addSubview(imageView) } private func setupConstraints() { let imageViewConstraints = [ imageView.topAnchor.constraint(equalTo: view.topAnchor), imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), view.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), view.leadingAnchor.constraint(equalTo: imageView.leadingAnchor) ] NSLayoutConstraint.activate(imageViewConstraints) } // MARK: - Actions @objc private func finishScan() { if let imageScannerController = navigationController as? ImageScannerController { imageScannerController.imageScannerDelegate?.imageScannerController(imageScannerController, didFinishScanningWithResults: results) } } }
34.402439
190
0.675292
334ec66f2ce6c8974c79fbbf2e6c25b4b7def84a
1,094
// // AppDelegate.swift // CleanArchitectureWithCoordinatorPatternDemo // // Created by Umbrella tech on 06.11.2017. // Copyright © 2017 Umbrella. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var rootController: UINavigationController { window?.rootViewController = UINavigationController() return window?.rootViewController as! UINavigationController } fileprivate lazy var coordinator: Coordinatable = self.makeCoordinator() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. coordinator.start() return true } } // MARK:- Private methods private extension AppDelegate { func makeCoordinator() -> Coordinatable { return AppCoordinator(router: Router(rootController: rootController), factory: CoordinatorFactory()) } }
28.789474
144
0.711152
ccb264958f99033feb0133f38d8eca8b154afeaa
270
// OSLog+Extensions.swift // Copyright (c) 2022 Joe Blau import Foundation import os.log extension OSLog { private static var subsystem = Bundle.main.bundleIdentifier! static let hexSmartContract = OSLog(subsystem: subsystem, category: "hex_smart_contract") }
24.545455
93
0.766667
693faf0875ceb7ef675b56548d925b3d48d2f7c5
37,457
// // ArticlesTable.swift // NetNewsWire // // Created by Brent Simmons on 5/9/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import Foundation import RSCore import RSDatabase import RSDatabaseObjC import RSParser import Articles final class ArticlesTable: DatabaseTable { let name: String private let accountID: String private let queue: DatabaseQueue private let statusesTable: StatusesTable private let authorsLookupTable: DatabaseLookupTable private let retentionStyle: ArticlesDatabase.RetentionStyle private var articlesCache = [String: Article]() private lazy var searchTable: SearchTable = { return SearchTable(queue: queue, articlesTable: self) }() // TODO: update articleCutoffDate as time passes and based on user preferences. let articleCutoffDate = Date().bySubtracting(days: 90) private typealias ArticlesFetchMethod = (FMDatabase) -> Set<Article> init(name: String, accountID: String, queue: DatabaseQueue, retentionStyle: ArticlesDatabase.RetentionStyle) { self.name = name self.accountID = accountID self.queue = queue self.statusesTable = StatusesTable(queue: queue) self.retentionStyle = retentionStyle let authorsTable = AuthorsTable(name: DatabaseTableName.authors) self.authorsLookupTable = DatabaseLookupTable(name: DatabaseTableName.authorsLookup, objectIDKey: DatabaseKey.articleID, relatedObjectIDKey: DatabaseKey.authorID, relatedTable: authorsTable, relationshipName: RelationshipName.authors) } // MARK: - Fetching Articles for Feed func fetchArticles(_ webFeedID: String) throws -> Set<Article> { return try fetchArticles{ self.fetchArticlesForFeedID(webFeedID, $0) } } func fetchArticlesAsync(_ webFeedID: String, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchArticlesForFeedID(webFeedID, $0) }, completion) } func fetchArticles(_ webFeedIDs: Set<String>) throws -> Set<Article> { return try fetchArticles{ self.fetchArticles(webFeedIDs, $0) } } func fetchArticlesAsync(_ webFeedIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchArticles(webFeedIDs, $0) }, completion) } // MARK: - Fetching Articles by articleID func fetchArticles(articleIDs: Set<String>) throws -> Set<Article> { return try fetchArticles{ self.fetchArticles(articleIDs: articleIDs, $0) } } func fetchArticlesAsync(articleIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { return fetchArticlesAsync({ self.fetchArticles(articleIDs: articleIDs, $0) }, completion) } // MARK: - Fetching Unread Articles func fetchUnreadArticles(_ webFeedIDs: Set<String>) throws -> Set<Article> { return try fetchArticles{ self.fetchUnreadArticles(webFeedIDs, $0) } } func fetchUnreadArticlesAsync(_ webFeedIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchUnreadArticles(webFeedIDs, $0) }, completion) } // MARK: - Fetching Today Articles func fetchArticlesSince(_ webFeedIDs: Set<String>, _ cutoffDate: Date) throws -> Set<Article> { return try fetchArticles{ self.fetchArticlesSince(webFeedIDs, cutoffDate, $0) } } func fetchArticlesSinceAsync(_ webFeedIDs: Set<String>, _ cutoffDate: Date, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchArticlesSince(webFeedIDs, cutoffDate, $0) }, completion) } // MARK: - Fetching Starred Articles func fetchStarredArticles(_ webFeedIDs: Set<String>) throws -> Set<Article> { return try fetchArticles{ self.fetchStarredArticles(webFeedIDs, $0) } } func fetchStarredArticlesAsync(_ webFeedIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchStarredArticles(webFeedIDs, $0) }, completion) } // MARK: - Fetching Search Articles func fetchArticlesMatching(_ searchString: String) throws -> Set<Article> { var articles: Set<Article> = Set<Article>() var error: DatabaseError? = nil queue.runInDatabaseSync { (databaseResult) in switch databaseResult { case .success(let database): articles = self.fetchArticlesMatching(searchString, database) case .failure(let databaseError): error = databaseError } } if let error = error { throw(error) } return articles } func fetchArticlesMatching(_ searchString: String, _ webFeedIDs: Set<String>) throws -> Set<Article> { var articles = try fetchArticlesMatching(searchString) articles = articles.filter{ webFeedIDs.contains($0.webFeedID) } return articles } func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set<String>) throws -> Set<Article> { var articles = try fetchArticlesMatching(searchString) articles = articles.filter{ articleIDs.contains($0.articleID) } return articles } func fetchArticlesMatchingAsync(_ searchString: String, _ webFeedIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchArticlesMatching(searchString, webFeedIDs, $0) }, completion) } func fetchArticlesMatchingWithArticleIDsAsync(_ searchString: String, _ articleIDs: Set<String>, _ completion: @escaping ArticleSetResultBlock) { fetchArticlesAsync({ self.fetchArticlesMatchingWithArticleIDs(searchString, articleIDs, $0) }, completion) } // MARK: - Fetching Articles for Indexer func fetchArticleSearchInfos(_ articleIDs: Set<String>, in database: FMDatabase) -> Set<ArticleSearchInfo>? { let parameters = articleIDs.map { $0 as AnyObject } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(articleIDs.count))! let sql = "select articleID, title, contentHTML, contentText, summary, searchRowID from articles where articleID in \(placeholders);"; if let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) { return resultSet.mapToSet { (row) -> ArticleSearchInfo? in let articleID = row.string(forColumn: DatabaseKey.articleID)! let title = row.string(forColumn: DatabaseKey.title) let contentHTML = row.string(forColumn: DatabaseKey.contentHTML) let contentText = row.string(forColumn: DatabaseKey.contentText) let summary = row.string(forColumn: DatabaseKey.summary) let searchRowIDObject = row.object(forColumnName: DatabaseKey.searchRowID) var searchRowID: Int? = nil if searchRowIDObject != nil && !(searchRowIDObject is NSNull) { searchRowID = Int(row.longLongInt(forColumn: DatabaseKey.searchRowID)) } return ArticleSearchInfo(articleID: articleID, title: title, contentHTML: contentHTML, contentText: contentText, summary: summary, searchRowID: searchRowID) } } return nil } // MARK: - Updating and Deleting func update(_ parsedItems: Set<ParsedItem>, _ webFeedID: String, _ deleteOlder: Bool, _ completion: @escaping UpdateArticlesCompletionBlock) { precondition(retentionStyle == .feedBased) if parsedItems.isEmpty { callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } // 1. Ensure statuses for all the incoming articles. // 2. Create incoming articles with parsedItems. // 3. [Deleted - this step is no longer needed] // 4. Fetch all articles for the feed. // 5. Create array of Articles not in database and save them. // 6. Create array of updated Articles and save what’s changed. // 7. Call back with new and updated Articles. // 8. Delete Articles in database no longer present in the feed. // 9. Update search index. self.queue.runInTransaction { (databaseResult) in func makeDatabaseCalls(_ database: FMDatabase) { let articleIDs = parsedItems.articleIDs() let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, false, database) //1 assert(statusesDictionary.count == articleIDs.count) let incomingArticles = Article.articlesWithParsedItems(parsedItems, webFeedID, self.accountID, statusesDictionary) //2 if incomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } let fetchedArticles = self.fetchArticlesForFeedID(webFeedID, database) //4 let fetchedArticlesDictionary = fetchedArticles.dictionary() let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) //5 let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) //6 // Articles to delete are 1) not starred and 2) older than 30 days and 3) no longer in feed. let articlesToDelete: Set<Article> if deleteOlder { let cutoffDate = Date().bySubtracting(days: 30) articlesToDelete = fetchedArticles.filter { (article) -> Bool in return !article.status.starred && article.status.dateArrived < cutoffDate && !articleIDs.contains(article.articleID) } } else { articlesToDelete = Set<Article>() } self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, articlesToDelete, completion) //7 self.addArticlesToCache(newArticles) self.addArticlesToCache(updatedArticles) // 8. Delete articles no longer in feed. let articleIDsToDelete = articlesToDelete.articleIDs() if !articleIDsToDelete.isEmpty { self.removeArticles(articleIDsToDelete, database) self.removeArticleIDsFromCache(articleIDsToDelete) } // 9. Update search index. if let newArticles = newArticles { self.searchTable.indexNewArticles(newArticles, database) } if let updatedArticles = updatedArticles { self.searchTable.indexUpdatedArticles(updatedArticles, database) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func update(_ webFeedIDsAndItems: [String: Set<ParsedItem>], _ read: Bool, _ completion: @escaping UpdateArticlesCompletionBlock) { precondition(retentionStyle == .syncSystem) if webFeedIDsAndItems.isEmpty { callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } // 1. Ensure statuses for all the incoming articles. // 2. Create incoming articles with parsedItems. // 3. Ignore incoming articles that are (!starred and read and really old) // 4. Fetch all articles for the feed. // 5. Create array of Articles not in database and save them. // 6. Create array of updated Articles and save what’s changed. // 7. Call back with new and updated Articles. // 8. Update search index. self.queue.runInTransaction { (databaseResult) in func makeDatabaseCalls(_ database: FMDatabase) { var articleIDs = Set<String>() for (_, parsedItems) in webFeedIDsAndItems { articleIDs.formUnion(parsedItems.articleIDs()) } let (statusesDictionary, _) = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, read, database) //1 assert(statusesDictionary.count == articleIDs.count) let allIncomingArticles = Article.articlesWithWebFeedIDsAndItems(webFeedIDsAndItems, self.accountID, statusesDictionary) //2 if allIncomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } let incomingArticles = self.filterIncomingArticles(allIncomingArticles) //3 if incomingArticles.isEmpty { self.callUpdateArticlesCompletionBlock(nil, nil, nil, completion) return } let incomingArticleIDs = incomingArticles.articleIDs() let fetchedArticles = self.fetchArticles(articleIDs: incomingArticleIDs, database) //4 let fetchedArticlesDictionary = fetchedArticles.dictionary() let newArticles = self.findAndSaveNewArticles(incomingArticles, fetchedArticlesDictionary, database) //5 let updatedArticles = self.findAndSaveUpdatedArticles(incomingArticles, fetchedArticlesDictionary, database) //6 self.callUpdateArticlesCompletionBlock(newArticles, updatedArticles, nil, completion) //7 self.addArticlesToCache(newArticles) self.addArticlesToCache(updatedArticles) // 8. Update search index. if let newArticles = newArticles { self.searchTable.indexNewArticles(newArticles, database) } if let updatedArticles = updatedArticles { self.searchTable.indexUpdatedArticles(updatedArticles, database) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } public func delete(articleIDs: Set<String>, completion: DatabaseCompletionBlock?) { self.queue.runInTransaction { (databaseResult) in func makeDatabaseCalls(_ database: FMDatabase) { self.removeArticles(articleIDs, database) DispatchQueue.main.async { completion?(nil) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion?(databaseError) } } } } // MARK: - Unread Counts func fetchUnreadCount(_ webFeedIDs: Set<String>, _ since: Date, _ completion: @escaping SingleUnreadCountCompletionBlock) { // Get unread count for today, for instance. if webFeedIDs.isEmpty { completion(.success(0)) return } queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let sql = "select count(*) from articles natural join statuses where feedID in \(placeholders) and (datePublished > ? or (datePublished is null and dateArrived > ?)) and read=0;" var parameters = [Any]() parameters += Array(webFeedIDs) as [Any] parameters += [since] as [Any] parameters += [since] as [Any] let unreadCount = self.numberWithSQLAndParameters(sql, parameters, in: database) DispatchQueue.main.async { completion(.success(unreadCount)) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func fetchStarredAndUnreadCount(_ webFeedIDs: Set<String>, _ completion: @escaping SingleUnreadCountCompletionBlock) { if webFeedIDs.isEmpty { completion(.success(0)) return } queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let sql = "select count(*) from articles natural join statuses where feedID in \(placeholders) and read=0 and starred=1;" let parameters = Array(webFeedIDs) as [Any] let unreadCount = self.numberWithSQLAndParameters(sql, parameters, in: database) DispatchQueue.main.async { completion(.success(unreadCount)) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } // MARK: - Statuses func fetchUnreadArticleIDsAsync(_ webFeedIDs: Set<String>, _ completion: @escaping ArticleIDsCompletionBlock) { fetchArticleIDsAsync(.read, false, webFeedIDs, completion) } func fetchStarredArticleIDsAsync(_ webFeedIDs: Set<String>, _ completion: @escaping ArticleIDsCompletionBlock) { fetchArticleIDsAsync(.starred, true, webFeedIDs, completion) } func fetchStarredArticleIDs() throws -> Set<String> { return try statusesTable.fetchStarredArticleIDs() } func fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate(_ completion: @escaping ArticleIDsCompletionBlock) { statusesTable.fetchArticleIDsForStatusesWithoutArticlesNewerThan(articleCutoffDate, completion) } func mark(_ articles: Set<Article>, _ statusKey: ArticleStatus.Key, _ flag: Bool, _ completion: @escaping ArticleStatusesResultBlock) { self.queue.runInTransaction { databaseResult in switch databaseResult { case .success(let database): let statuses = self.statusesTable.mark(articles.statuses(), statusKey, flag, database) DispatchQueue.main.async { completion(.success(statuses ?? Set<ArticleStatus>())) } case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func markAndFetchNew(_ articleIDs: Set<String>, _ statusKey: ArticleStatus.Key, _ flag: Bool, _ completion: @escaping ArticleIDsCompletionBlock) { queue.runInTransaction { databaseResult in switch databaseResult { case .success(let database): let newStatusIDs = self.statusesTable.markAndFetchNew(articleIDs, statusKey, flag, database) DispatchQueue.main.async { completion(.success(newStatusIDs)) } case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func createStatusesIfNeeded(_ articleIDs: Set<String>, _ completion: @escaping DatabaseCompletionBlock) { queue.runInTransaction { databaseResult in switch databaseResult { case .success(let database): let _ = self.statusesTable.ensureStatusesForArticleIDs(articleIDs, true, database) DispatchQueue.main.async { completion(nil) } case .failure(let databaseError): DispatchQueue.main.async { completion(databaseError) } } } } // MARK: - Indexing func indexUnindexedArticles() { queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { let sql = "select articleID from articles where searchRowID is null limit 500;" guard let resultSet = database.executeQuery(sql, withArgumentsIn: nil) else { return } let articleIDs = resultSet.mapToSet{ $0.string(forColumn: DatabaseKey.articleID) } if articleIDs.isEmpty { return } self.searchTable.ensureIndexedArticles(articleIDs, database) DispatchQueue.main.async { self.indexUnindexedArticles() } } if let database = databaseResult.database { makeDatabaseCalls(database) } } } // MARK: - Caches func emptyCaches() { queue.runInDatabase { _ in self.articlesCache = [String: Article]() } } // MARK: - Cleanup /// Delete articles that we won’t show in the UI any longer /// — their arrival date is before our 90-day recency window; /// they are read; they are not starred. /// /// Because deleting articles might block the database for too long, /// we do this in a careful way: delete articles older than a year, /// check to see how much time has passed, then decide whether or not to continue. /// Repeat for successively more-recent dates. /// /// Returns `true` if it deleted old articles all the way up to the 90 day cutoff date. func deleteOldArticles() { precondition(retentionStyle == .syncSystem) queue.runInTransaction { databaseResult in guard let database = databaseResult.database else { return } func deleteOldArticles(cutoffDate: Date) { let sql = "delete from articles where articleID in (select articleID from articles natural join statuses where dateArrived<? and read=1 and starred=0);" let parameters = [cutoffDate] as [Any] database.executeUpdate(sql, withArgumentsIn: parameters) } let startTime = Date() func tooMuchTimeHasPassed() -> Bool { let timeElapsed = Date().timeIntervalSince(startTime) return timeElapsed > 2.0 } let dayIntervals = [365, 300, 225, 150] for dayInterval in dayIntervals { deleteOldArticles(cutoffDate: startTime.bySubtracting(days: dayInterval)) if tooMuchTimeHasPassed() { return } } deleteOldArticles(cutoffDate: self.articleCutoffDate) } } /// Delete old statuses. func deleteOldStatuses() { queue.runInTransaction { databaseResult in guard let database = databaseResult.database else { return } let sql: String let cutoffDate: Date switch self.retentionStyle { case .syncSystem: sql = "delete from statuses where dateArrived<? and read=1 and starred=0 and articleID not in (select articleID from articles);" cutoffDate = Date().bySubtracting(days: 180) case .feedBased: sql = "delete from statuses where dateArrived<? and starred=0 and articleID not in (select articleID from articles);" cutoffDate = Date().bySubtracting(days: 30) } let parameters = [cutoffDate] as [Any] database.executeUpdate(sql, withArgumentsIn: parameters) } } /// Delete articles from feeds that are no longer in the current set of subscribed-to feeds. /// This deletes from the articles and articleStatuses tables, /// and, via a trigger, it also deletes from the search index. func deleteArticlesNotInSubscribedToFeedIDs(_ webFeedIDs: Set<String>) { if webFeedIDs.isEmpty { return } queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let sql = "select articleID from articles where feedID not in \(placeholders);" let parameters = Array(webFeedIDs) as [Any] guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { return } let articleIDs = resultSet.mapToSet{ $0.string(forColumn: DatabaseKey.articleID) } if articleIDs.isEmpty { return } self.removeArticles(articleIDs, database) self.statusesTable.removeStatuses(articleIDs, database) } if let database = databaseResult.database { makeDatabaseCalls(database) } } } /// Mark statuses beyond the 90-day window as read. /// /// This is not intended for wide use: this is part of implementing /// the April 2020 retention policy change for feed-based accounts. func markOlderStatusesAsRead() { queue.runInDatabase { databaseResult in guard let database = databaseResult.database else { return } let sql = "update statuses set read = 1 where dateArrived<?;" let parameters = [self.articleCutoffDate] as [Any] database.executeUpdate(sql, withArgumentsIn: parameters) } } } // MARK: - Private private extension ArticlesTable { // MARK: - Fetching private func fetchArticles(_ fetchMethod: @escaping ArticlesFetchMethod) throws -> Set<Article> { var articles = Set<Article>() var error: DatabaseError? = nil queue.runInDatabaseSync { databaseResult in switch databaseResult { case .success(let database): articles = fetchMethod(database) case .failure(let databaseError): error = databaseError } } if let error = error { throw(error) } return articles } private func fetchArticlesAsync(_ fetchMethod: @escaping ArticlesFetchMethod, _ completion: @escaping ArticleSetResultBlock) { queue.runInDatabase { databaseResult in switch databaseResult { case .success(let database): let articles = fetchMethod(database) DispatchQueue.main.async { completion(.success(articles)) } case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func articlesWithResultSet(_ resultSet: FMResultSet, _ database: FMDatabase) -> Set<Article> { var cachedArticles = Set<Article>() var fetchedArticles = Set<Article>() while resultSet.next() { guard let articleID = resultSet.string(forColumn: DatabaseKey.articleID) else { assertionFailure("Expected articleID.") continue } if let article = articlesCache[articleID] { cachedArticles.insert(article) continue } // The resultSet is a result of a JOIN query with the statuses table, // so we can get the statuses at the same time and avoid additional database lookups. guard let status = statusesTable.statusWithRow(resultSet, articleID: articleID) else { assertionFailure("Expected status.") continue } guard let article = Article(accountID: accountID, row: resultSet, status: status) else { continue } fetchedArticles.insert(article) } resultSet.close() if fetchedArticles.isEmpty { return cachedArticles } // Fetch authors for non-cached articles. (Articles from the cache already have authors.) let fetchedArticleIDs = fetchedArticles.articleIDs() let authorsMap = authorsLookupTable.fetchRelatedObjects(for: fetchedArticleIDs, in: database) let articlesWithFetchedAuthors = fetchedArticles.map { (article) -> Article in if let authors = authorsMap?.authors(for: article.articleID) { return article.byAdding(authors) } return article } // Add fetchedArticles to cache, now that they have attached authors. for article in articlesWithFetchedAuthors { articlesCache[article.articleID] = article } return cachedArticles.union(articlesWithFetchedAuthors) } func fetchArticlesWithWhereClause(_ database: FMDatabase, whereClause: String, parameters: [AnyObject]) -> Set<Article> { let sql = "select * from articles natural join statuses where \(whereClause);" return articlesWithSQL(sql, parameters, database) } func fetchArticlesMatching(_ searchString: String, _ database: FMDatabase) -> Set<Article> { let sql = "select rowid from search where search match ?;" let sqlSearchString = sqliteSearchString(with: searchString) let searchStringParameters = [sqlSearchString] guard let resultSet = database.executeQuery(sql, withArgumentsIn: searchStringParameters) else { return Set<Article>() } let searchRowIDs = resultSet.mapToSet { $0.longLongInt(forColumnIndex: 0) } if searchRowIDs.isEmpty { return Set<Article>() } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(searchRowIDs.count))! let whereClause = "searchRowID in \(placeholders)" let parameters: [AnyObject] = Array(searchRowIDs) as [AnyObject] return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func sqliteSearchString(with searchString: String) -> String { var s = "" searchString.enumerateSubstrings(in: searchString.startIndex..<searchString.endIndex, options: .byWords) { (word, range, enclosingRange, stop) in guard let word = word else { return } s += word if s != "AND" && s != "OR" { s += "*" } s += " " } return s } func articlesWithSQL(_ sql: String, _ parameters: [AnyObject], _ database: FMDatabase) -> Set<Article> { guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { return Set<Article>() } return articlesWithResultSet(resultSet, database) } func fetchArticleIDsAsync(_ statusKey: ArticleStatus.Key, _ value: Bool, _ webFeedIDs: Set<String>, _ completion: @escaping ArticleIDsCompletionBlock) { guard !webFeedIDs.isEmpty else { completion(.success(Set<String>())) return } queue.runInDatabase { databaseResult in func makeDatabaseCalls(_ database: FMDatabase) { let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! var sql = "select articleID from articles natural join statuses where feedID in \(placeholders) and \(statusKey.rawValue)=" sql += value ? "1" : "0" sql += ";" let parameters = Array(webFeedIDs) as [Any] guard let resultSet = database.executeQuery(sql, withArgumentsIn: parameters) else { DispatchQueue.main.async { completion(.success(Set<String>())) } return } let articleIDs = resultSet.mapToSet{ $0.string(forColumnIndex: 0) } DispatchQueue.main.async { completion(.success(articleIDs)) } } switch databaseResult { case .success(let database): makeDatabaseCalls(database) case .failure(let databaseError): DispatchQueue.main.async { completion(.failure(databaseError)) } } } } func fetchArticles(_ webFeedIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { // select * from articles natural join statuses where feedID in ('http://ranchero.com/xml/rss.xml') and read=0 if webFeedIDs.isEmpty { return Set<Article>() } let parameters = webFeedIDs.map { $0 as AnyObject } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let whereClause = "feedID in \(placeholders)" return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func fetchUnreadArticles(_ webFeedIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { // select * from articles natural join statuses where feedID in ('http://ranchero.com/xml/rss.xml') and read=0 if webFeedIDs.isEmpty { return Set<Article>() } let parameters = webFeedIDs.map { $0 as AnyObject } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let whereClause = "feedID in \(placeholders) and read=0" return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func fetchArticlesForFeedID(_ webFeedID: String, _ database: FMDatabase) -> Set<Article> { return fetchArticlesWithWhereClause(database, whereClause: "articles.feedID = ?", parameters: [webFeedID as AnyObject]) } func fetchArticles(articleIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { if articleIDs.isEmpty { return Set<Article>() } let parameters = articleIDs.map { $0 as AnyObject } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(articleIDs.count))! let whereClause = "articleID in \(placeholders)" return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func fetchArticlesSince(_ webFeedIDs: Set<String>, _ cutoffDate: Date, _ database: FMDatabase) -> Set<Article> { // select * from articles natural join statuses where feedID in ('http://ranchero.com/xml/rss.xml') and (datePublished > ? || (datePublished is null and dateArrived > ?) // // datePublished may be nil, so we fall back to dateArrived. if webFeedIDs.isEmpty { return Set<Article>() } let parameters = webFeedIDs.map { $0 as AnyObject } + [cutoffDate as AnyObject, cutoffDate as AnyObject] let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let whereClause = "feedID in \(placeholders) and (datePublished > ? or (datePublished is null and dateArrived > ?))" return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func fetchStarredArticles(_ webFeedIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { // select * from articles natural join statuses where feedID in ('http://ranchero.com/xml/rss.xml') and starred=1; if webFeedIDs.isEmpty { return Set<Article>() } let parameters = webFeedIDs.map { $0 as AnyObject } let placeholders = NSString.rs_SQLValueList(withPlaceholders: UInt(webFeedIDs.count))! let whereClause = "feedID in \(placeholders) and starred=1" return fetchArticlesWithWhereClause(database, whereClause: whereClause, parameters: parameters) } func fetchArticlesMatching(_ searchString: String, _ webFeedIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { let articles = fetchArticlesMatching(searchString, database) // TODO: include the feedIDs in the SQL rather than filtering here. return articles.filter{ webFeedIDs.contains($0.webFeedID) } } func fetchArticlesMatchingWithArticleIDs(_ searchString: String, _ articleIDs: Set<String>, _ database: FMDatabase) -> Set<Article> { let articles = fetchArticlesMatching(searchString, database) // TODO: include the articleIDs in the SQL rather than filtering here. return articles.filter{ articleIDs.contains($0.articleID) } } // MARK: - Saving Parsed Items func callUpdateArticlesCompletionBlock(_ newArticles: Set<Article>?, _ updatedArticles: Set<Article>?, _ deletedArticles: Set<Article>?, _ completion: @escaping UpdateArticlesCompletionBlock) { let articleChanges = ArticleChanges(newArticles: newArticles, updatedArticles: updatedArticles, deletedArticles: deletedArticles) DispatchQueue.main.async { completion(.success(articleChanges)) } } // MARK: - Saving New Articles func findNewArticles(_ incomingArticles: Set<Article>, _ fetchedArticlesDictionary: [String: Article]) -> Set<Article>? { let newArticles = Set(incomingArticles.filter { fetchedArticlesDictionary[$0.articleID] == nil }) return newArticles.isEmpty ? nil : newArticles } func findAndSaveNewArticles(_ incomingArticles: Set<Article>, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set<Article>? { //5 guard let newArticles = findNewArticles(incomingArticles, fetchedArticlesDictionary) else { return nil } self.saveNewArticles(newArticles, database) return newArticles } func saveNewArticles(_ articles: Set<Article>, _ database: FMDatabase) { saveRelatedObjectsForNewArticles(articles, database) if let databaseDictionaries = articles.databaseDictionaries() { insertRows(databaseDictionaries, insertType: .orReplace, in: database) } } func saveRelatedObjectsForNewArticles(_ articles: Set<Article>, _ database: FMDatabase) { let databaseObjects = articles.databaseObjects() authorsLookupTable.saveRelatedObjects(for: databaseObjects, in: database) } // MARK: - Updating Existing Articles func articlesWithRelatedObjectChanges<T>(_ comparisonKeyPath: KeyPath<Article, Set<T>?>, _ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article]) -> Set<Article> { return updatedArticles.filter{ (updatedArticle) -> Bool in if let fetchedArticle = fetchedArticles[updatedArticle.articleID] { return updatedArticle[keyPath: comparisonKeyPath] != fetchedArticle[keyPath: comparisonKeyPath] } assertionFailure("Expected to find matching fetched article."); return true } } func updateRelatedObjects<T>(_ comparisonKeyPath: KeyPath<Article, Set<T>?>, _ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ lookupTable: DatabaseLookupTable, _ database: FMDatabase) { let articlesWithChanges = articlesWithRelatedObjectChanges(comparisonKeyPath, updatedArticles, fetchedArticles) if !articlesWithChanges.isEmpty { lookupTable.saveRelatedObjects(for: articlesWithChanges.databaseObjects(), in: database) } } func saveUpdatedRelatedObjects(_ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ database: FMDatabase) { updateRelatedObjects(\Article.authors, updatedArticles, fetchedArticles, authorsLookupTable, database) } func findUpdatedArticles(_ incomingArticles: Set<Article>, _ fetchedArticlesDictionary: [String: Article]) -> Set<Article>? { let updatedArticles = incomingArticles.filter{ (incomingArticle) -> Bool in //6 if let existingArticle = fetchedArticlesDictionary[incomingArticle.articleID] { if existingArticle != incomingArticle { return true } } return false } return updatedArticles.isEmpty ? nil : updatedArticles } func findAndSaveUpdatedArticles(_ incomingArticles: Set<Article>, _ fetchedArticlesDictionary: [String: Article], _ database: FMDatabase) -> Set<Article>? { //6 guard let updatedArticles = findUpdatedArticles(incomingArticles, fetchedArticlesDictionary) else { return nil } saveUpdatedArticles(Set(updatedArticles), fetchedArticlesDictionary, database) return updatedArticles } func saveUpdatedArticles(_ updatedArticles: Set<Article>, _ fetchedArticles: [String: Article], _ database: FMDatabase) { saveUpdatedRelatedObjects(updatedArticles, fetchedArticles, database) for updatedArticle in updatedArticles { saveUpdatedArticle(updatedArticle, fetchedArticles, database) } } func saveUpdatedArticle(_ updatedArticle: Article, _ fetchedArticles: [String: Article], _ database: FMDatabase) { // Only update exactly what has changed in the Article (if anything). // Untested theory: this gets us better performance and less database fragmentation. guard let fetchedArticle = fetchedArticles[updatedArticle.articleID] else { assertionFailure("Expected to find matching fetched article."); saveNewArticles(Set([updatedArticle]), database) return } guard let changesDictionary = updatedArticle.changesFrom(fetchedArticle), changesDictionary.count > 0 else { // Not unexpected. There may be no changes. return } updateRowsWithDictionary(changesDictionary, whereKey: DatabaseKey.articleID, matches: updatedArticle.articleID, database: database) } func addArticlesToCache(_ articles: Set<Article>?) { guard let articles = articles else { return } for article in articles { articlesCache[article.articleID] = article } } func removeArticleIDsFromCache(_ articleIDs: Set<String>) { for articleID in articleIDs { articlesCache[articleID] = nil } } func articleIsIgnorable(_ article: Article) -> Bool { if article.status.starred || !article.status.read { return false } return article.status.dateArrived < articleCutoffDate } func filterIncomingArticles(_ articles: Set<Article>) -> Set<Article> { // Drop Articles that we can ignore. precondition(retentionStyle == .syncSystem) return Set(articles.filter{ !articleIsIgnorable($0) }) } func removeArticles(_ articleIDs: Set<String>, _ database: FMDatabase) { deleteRowsWhere(key: DatabaseKey.articleID, equalsAnyValue: Array(articleIDs), in: database) } } private extension Set where Element == ParsedItem { func articleIDs() -> Set<String> { return Set<String>(map { $0.articleID }) } }
36.43677
236
0.743653
89a4af9ed32d623a94a0c204913b7023f4e416fb
1,750
// // CharacterDetailsViewModel.swift // MarvelApp // // Created by Igor Zarubin on 30.03.2022. // import Foundation import Combine final class CharacterDetailsViewModel: ObservableObject { private let character: MarvelCharacter private let service: ComicService var name: String { self.character.name } var description: String? { self.character.description } var url: URL? { self.character.thumbnail?.url(for: .square(.amazing)) } @Published var comics = [ComicDisplayItem]() @Published var isComicsLoading = true @Published var isComicsLoadingFailed = false private var subscriptions = Set<AnyCancellable>() init(character: MarvelCharacter, service: ComicService) { self.character = character self.service = service } func loadComics() { guard self.comics.isEmpty else { return } self.isComicsLoading = true self.isComicsLoadingFailed = false self.service.comics(for: character.id, offset: 0, limit: 20) .receive(on: DispatchQueue.main) .sink { [weak self] completion in self?.isComicsLoading = false guard case .failure = completion else { return } self?.isComicsLoadingFailed = true } receiveValue: { [weak self] comics in self?.comics = comics.map { ComicDisplayItem( id: $0.id, title: $0.title, previewURL: $0.thumbnail?.url(for: .portrait(.medium)) ) } } .store(in: &self.subscriptions) } }
30.172414
78
0.566857
09dd0e2385b2ab0f7068dfada37e0d9f7f30efd8
228
// // UICollectionViewCell.swift // WaveLabs // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(UIKit) import UIKit extension UICollectionViewCell { } #endif
15.2
54
0.714912
1a913c101bd7f5b0cdfb5fcd7b73b5a5a841a63e
2,751
import Foundation import os.log class SourceDisplays: PublishTerminateHandler { let name: String? let callback: (Float) -> Void var source: SourceDisplay? override var matchClass: String { return "AppleBacklightDisplay" } init(name: String? = nil, _ callback: @escaping (Float) -> Void) throws { self.name = name self.callback = callback try super.init() } func sync() throws { try source?.sync() } override func published(_ service: io_service_t) throws { guard source == nil && (name == nil || name == getDisplayName(service)) else { IOObjectRelease(service) return } source = try SourceDisplay(service, callback) os_log("Source display found: %{public}s", source!.name) } override func terminated(_ service: io_service_t) throws { if source?.display == service { os_log("Source display gone: %{public}s", source!.name) source = nil } IOObjectRelease(service) } } class SourceDisplay: Display { let display: io_service_t let port: IONotificationPortRef var notification: io_object_t = 0 var brightness: Float = 0 let callback: (Float) -> Void init(_ service: io_service_t, _ callback: @escaping (Float) -> Void) throws { self.display = service self.callback = callback guard let port = IONotificationPortCreate(kIOMasterPortDefault) else { IOObjectRelease(service) throw BrightnessSyncError.ioNotificationPortCreate } IONotificationPortSetDispatchQueue(port, DispatchQueue.global(qos: .background)) self.port = port guard IOServiceAddInterestNotification(port, service, kIOGeneralInterest, sourceCallback, Unmanaged.passUnretained(self).toOpaque(), &notification) == KERN_SUCCESS else { IONotificationPortDestroy(port) IOObjectRelease(service) throw BrightnessSyncError.ioServiceAddInterestNotification } } deinit { IOObjectRelease(notification) IONotificationPortDestroy(port) IOObjectRelease(display) } lazy var name: String = getDisplayName(display) ?? "unknown" func sync() throws { var brightness: Float = 0 guard IODisplayGetFloatParameter(display, 0, kIODisplayBrightnessKey as CFString, &brightness) == KERN_SUCCESS else { throw BrightnessSyncError.getBrightnessFailed } guard brightness != self.brightness else { return } os_log("Source display [%{public}s] brightness: %.2f%%", type: .debug, name, brightness * 100) callback(brightness) self.brightness = brightness } } func sourceCallback(_ refcon: UnsafeMutableRawPointer!, _ service: io_service_t, _ messageType: UInt32, _ messageArgument: UnsafeMutableRawPointer?) { do { try Unmanaged<SourceDisplay>.fromOpaque(refcon).takeUnretainedValue().sync() } catch { os_log("Failed to handle source display notification: %s", String(describing: error)) } }
30.230769
172
0.745184
8fbbfc84e0c65949db70a650e877e2931c68c122
447
import XCTest @testable import numsw class MatrixTransformationTests: XCTestCase { func testReshape() { let a = Matrix<Int>.eye(4) XCTAssertEqual(a.reshaped(rows: 2, columns: 8), Matrix([[1, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1]])) } static var allTests: [(String, (MatrixTransformationTests) -> () throws -> Void)] { return [ ("testReshape", testReshape) ] } }
24.833333
117
0.552573
29301f2e0f398afe8224a0c455bd034424d5847f
1,694
// // This source file is part of the MongoKitten open source project // // Copyright (c) 2016 - 2017 OpenKitten and the MongoKitten project authors // Licensed under MIT // // See https://github.com/OpenKitten/MongoKitten/blob/mongokitten31/LICENSE.md for license information // See https://github.com/OpenKitten/MongoKitten/blob/mongokitten31/CONTRIBUTORS.md for the list of MongoKitten project authors // import Foundation extension Database { /// Grants roles to a user in this database /// /// For additional information: https://docs.mongodb.com/manual/reference/command/grantRolesToUser/#dbcmd.grantRolesToUser /// /// TODO: Easier roleList creation /// /// - parameter roleList: The roles to grants /// - parameter user: The user to grant the roles to /// /// - throws: When unable to send the request/receive the response, the authenticated user doesn't have sufficient permissions or an error occurred public func grant(roles roleList: Document, to user: String) throws { let command: Document = [ "grantRolesToUser": user, "roles": roleList ] log.verbose("Granting roles to user \"\(user)\"") log.debug(roleList) let document = try firstDocument(in: try execute(command: command)) guard Int(document["ok"]) == 1 else { log.error("grantRolesToUser for user \"\(user)\" was not successful because of the following error") log.error(document) log.error("grantRolesToUser failed with the following roles") log.error(roleList) throw MongoError.commandFailure(error: document) } } }
37.644444
151
0.668241
507a6d6ab020d1137061d21be95511ee857dd72d
9,276
/* *     Copyright 2016 IBM Corp. *     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 SimpleHttpClient /** The type of callback to send with PushNotifications requests. */ public typealias PushNotificationsCompletionHandler = (_ data: Data?,_ status: Int?,_ error: PushNotificationsError?) -> Void /** Used to send Push notifications via a IBM Cloud Push Notifications service. */ public class PushNotifications { /// The IBM Cloud region where the Push Notifications service is hosted. public struct Region { public static let US_SOUTH = "ng.bluemix.net" public static let UK = "eu-gb.bluemix.net" public static let SYDNEY = "au-syd.bluemix.net" public static let FRANKFURT = "eu-de.bluemix.net" public static let US_EAST = "us-east.bluemix.net" } internal var headers = [String: String]() private var httpResource = HttpResource(schema: "", host: "") private var httpBulkResource = HttpResource(schema: "", host: "") private var pushApiKey = "" private var pushAppRegion = "" // used to test in test zone and dev zone public static var overrideServerHost = ""; /** Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service. - parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted. - parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to. - parameter pushAppSecret: The appSecret credential required for Push Notifications service authorization. */ public init(pushRegion: String, pushAppGuid: String, pushAppSecret: String) { headers = ["appSecret": pushAppSecret, "Content-Type": "application/json"] if(PushNotifications.overrideServerHost.isEmpty){ let pushHost = "imfpush." + pushRegion httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") }else{ let url = URL(string: PushNotifications.overrideServerHost) httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } } /** Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service. - parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted. - parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to. - parameter pushApiKey: The ApiKey credential required for Push Notifications service authorization. */ public init(pushApiKey:String, pushAppGuid: String, pushRegion: String) { self.pushApiKey = pushApiKey self.pushAppRegion = pushRegion if(PushNotifications.overrideServerHost.isEmpty) { let pushHost = "imfpush." + pushRegion httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } else { let url = URL(string: PushNotifications.overrideServerHost) httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } } /** This method will get an iam auth token from the server and add it to the request header. Get Auth token before calling any send methods. - parameter completionHandler: Returns true if there is token with token string */ public func getAuthToken(completionHandler: @escaping (_ hasToken:Bool?, _ tokenValue: String) -> Void) { if (pushApiKey != "" && pushAppRegion != "") { var regionString = pushAppRegion; if (!PushNotifications.overrideServerHost.isEmpty) { let url = URL(string: PushNotifications.overrideServerHost) let domain = url?.host if let splitStringArray = domain?.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true) { regionString = String(splitStringArray[1]) } } let pushHost = "iam." + regionString let iamHttpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/identity/token") var data:Data? let dataString = "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=\(pushApiKey)" data = dataString.data(using: .ascii, allowLossyConversion: true) let iamHeaders = ["Content-Type":"application/x-www-form-urlencoded","Accept":"application/json"] HttpClient.post(resource: iamHttpResource, headers: iamHeaders, data: data) { (error, status, headers, data) in //completionHandler?(data,status,PushNotificationsError.from(httpError: error)) if(status == 200) { let dataJson = try! JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! [String:Any] let tokenString = dataJson["access_token"] as? String if !(tokenString?.isEmpty)! { self.headers = ["Authorization": "Bearer " + tokenString!, "Content-Type": "application/json"] } completionHandler(true, tokenString!) } else { print("Error While getting the token", error ?? "") completionHandler(false, "") } } } else { print("Error : Pass valid Apikey and app region") completionHandler(false, "") } } /** Send the Push notification. - parameter notificiation: The push notification to send. - paramter completionHandler: The callback to be executed when the send request completes. */ public func send(notification: Notification, completionHandler: PushNotificationsCompletionHandler?) { guard let requestBody = notification.jsonFormat else { completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } guard let data = try? JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) else{ completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } HttpClient.post(resource: httpResource, headers: headers, data: data) { (error, status, headers, data) in completionHandler?(data,status,PushNotificationsError.from(httpError: error)) } } /** Send Bulk Push notification. - parameter notificiation: Array of push notification payload to send. - paramter completionHandler: The callback to be executed when the send request completes. */ public func sendBulk(notification: [Notification], completionHandler: PushNotificationsCompletionHandler?) { var dataArray = [[String:Any]]() for notif in notification { guard let requestBody = notif.jsonFormat else { completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } dataArray.append(requestBody) } guard let data = try? JSONSerialization.data(withJSONObject: dataArray, options: .prettyPrinted) else{ completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } HttpClient.post(resource: httpBulkResource, headers: headers, data: data) { (error, status, headers, data) in completionHandler?(data,status,PushNotificationsError.from(httpError: error)) } } }
46.38
155
0.639176
38d390b8b73d3ad37cdf3573c1aad342e609ba70
2,868
import UIKit @objc(SDCAlertAction) public class AlertAction: NSObject { /// Creates an action with a plain title. /// /// parameter title: An optional title for the action /// parameter style: The action's style /// parameter image: The image of action /// parameter handler: An optional closure that's called when the user taps on this action @objc public convenience init(title: String?, style: AlertAction.Style, image: UIImage? = nil, handler: ((AlertAction) -> Void)? = nil) { self.init() self.title = title self.style = style self.handler = handler self.image = image } @objc /// Creates an action with a stylized title. /// /// - parameter attributedTitle: An optional stylized title /// - parameter style: The action's style /// - parameter image: The image of action /// - parameter handler: An optional closure that is called when the user taps on this action public convenience init(attributedTitle: NSAttributedString?, style: AlertAction.Style, image: UIImage? = nil, handler: ((AlertAction) -> Void)? = nil) { self.init() self.attributedTitle = attributedTitle self.style = style self.handler = handler self.image = image } /// A closure that gets executed when the user taps on this actions in the UI @objc public var handler: ((AlertAction) -> Void)? /// The plain title for the action. Uses `attributedTitle` directly. @objc private(set) public var title: String? { get { return self.attributedTitle?.string } set { self.attributedTitle = newValue.map(NSAttributedString.init) } } /// The stylized title for the action. @objc private(set) public var attributedTitle: NSAttributedString? /// The action's style. @objc internal(set) public var style: AlertAction.Style = .normal /// The image of action. Optional @objc private(set) public var image: UIImage? /// The action's button accessibility identifier @objc public var accessibilityIdentifier: String? /// Whether this action can be interacted with by the user. @objc public var isEnabled = true { didSet { self.actionView?.isEnabled = self.isEnabled } } var actionView: ActionCell? { didSet { self.actionView?.isEnabled = self.isEnabled } } } extension AlertAction { /// The action's style @objc(SDCAlertActionStyle) public enum Style: Int { /// The action will have default font and text color case normal /// The action will take a style that indicates it's the preferred option case preferred /// The action will convey that this action will do something destructive case destructive } }
32.965517
155
0.645049
16483432de05c9dd185761dfe3fcaf1144e3ee7e
2,302
// // RelistenLegacyAPI.swift // RelistenShared // // Created by Jacob Farkas on 8/12/18. // Copyright © 2018 Alec Gorge. All rights reserved. // import Foundation import Siesta import SwiftyJSON import Cache public class RelistenLegacyAPI { private let service = Service(baseURL:"http://iguana.app.alecgorge.com/api") public init() { #if DEBUG // Bare-bones logging of which network calls Siesta makes: SiestaLog.Category.enabled = [] // [.network] // For more info about how Siesta decides whether to make a network call, // and when it broadcasts state updates to the app: //LogCategory.enabled = LogCategory.common // For the gory details of what Siesta’s up to: //LogCategory.enabled = LogCategory.detailed #endif // Global configuration service.configure { $0.expirationTime = 60 * 60 * 24 * 365 * 10 as TimeInterval $0.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"]) $0.pipeline[.parsing].cacheUsing(RelistenLegacyJSONCache()) //$0.pipeline[.parsing].cacheUsing(RelistenJsonCache()) } // Resource-specific configuration service.configureTransformer("/artists/*") { return LegacyArtist(json: ($0.content as JSON)["data"]) } service.configureTransformer("/artists/*/shows/*") { return LegacyShowWithTracks(json: ($0.content as JSON)["data"]) } } public func artist(_ slug: String) -> Resource { return service .resource("/artists") .child(slug) } public func fullShow(byArtist slug: String, showID: Int) -> Resource { return artist(slug) .child("shows") .child(String(showID)) } } class RelistenLegacyJSONCache : RelistenCache { let backingCache: AnyStorageAware<Entity<Any>> let memoryCacheConfig = MemoryConfig( expiry: .never, countLimit: 1000, // 4MB totalCostLimit: 1024 * 1024 * 4 ) public init() { backingCache = AnyStorageAware(MemoryStorage(config: memoryCacheConfig)) } }
28.419753
86
0.591659
fb2fae52f831a17b17c58aab7fbe6fe274148cdb
2,641
// Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen #if os(OSX) import AppKit.NSFont typealias Font = NSFont #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit.UIFont typealias Font = UIFont #endif // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length struct FontConvertible { let name: String let family: String let path: String func font(size: CGFloat) -> Font! { return Font(font: self, size: size) } func register() { guard let url = url else { return } var errorRef: Unmanaged<CFError>? CTFontManagerRegisterFontsForURL(url as CFURL, .process, &errorRef) } fileprivate var url: URL? { let bundle = Bundle(for: BundleToken.self) return bundle.url(forResource: path, withExtension: nil) } } extension Font { convenience init!(font: FontConvertible, size: CGFloat) { #if os(iOS) || os(tvOS) || os(watchOS) if !UIFont.fontNames(forFamilyName: font.family).contains(font.name) { font.register() } #elseif os(OSX) if let url = font.url, CTFontManagerGetScopeForURL(url as CFURL) == .none { font.register() } #endif self.init(name: font.name, size: size) } } // swiftlint:disable identifier_name line_length type_body_length enum FontFamily { enum SFCompactDisplay { static let ultralight = FontConvertible(name: "SFCompactDisplay-Ultralight", family: "SF Compact Display", path: "SFCompactDisplay-Ultralight.otf") } enum SFCompactText { static let italic = FontConvertible(name: "SFCompactText-Italic", family: "SF Compact Text", path: "SFCompactText-RegularItalic.otf") static let semibold = FontConvertible(name: "SFCompactText-Semibold", family: "SF Compact Text", path: "SFCompactText-Semibold.otf") static let semiboldItalic = FontConvertible(name: "SFCompactText-SemiboldItalic", family: "SF Compact Text", path: "SFCompactText-SemiboldItalic.otf") } enum SFProDisplay { static let blackItalic = FontConvertible(name: "SFProDisplay-BlackItalic", family: "SF Pro Display", path: "SF-Pro-Display-BlackItalic.otf") static let heavyItalic = FontConvertible(name: "SFProDisplay-HeavyItalic", family: "SF Pro Display", path: "SF-Pro-Display-HeavyItalic.otf") static let light = FontConvertible(name: "SFProDisplay-Light", family: "SF Pro Display", path: "SF-Pro-Display-Light.otf") static let lightItalic = FontConvertible(name: "SFProDisplay-LightItalic", family: "SF Pro Display", path: "SF-Pro-Display-LightItalic.otf") } } // swiftlint:enable identifier_name line_length type_body_length private final class BundleToken {}
37.197183
154
0.725483
e65bdd5b4d31ba63df19805ee82250f833e0f9ba
708
// // ToDoCellModell.swift // iOS_Bootstrap_Example // // Created by Ahmad Mahmoud on 12/21/18. // Copyright © 2018 CocoaPods. All rights reserved. // struct ToDoCellModel: Decodable, Equatable { var id: Int? var name: String? var createdAt: String? var isDone: Bool? // var tasks: [TaskEntity]? func getToDoCellEntity() -> ToDoListEntity { let toDoEntity = ToDoListEntity() toDoEntity.id = self.id! toDoEntity.name = self.name! if let date = DateTimeHelpers.getDateFromDateString(dateString: self.createdAt!) { toDoEntity.createdAt = date } toDoEntity.isDone = self.isDone! return toDoEntity } }
25.285714
90
0.635593
dd9dc2cab646191e6ddbc341cf99b7b28b7605b5
278
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b = T> func < { struct S<S { { } } protocol c { func b<T where S<e> : String protocol e : b { { } func b
17.375
87
0.68705
d76a2af693d278ed8f558604eacb41babb648c83
2,184
// // AppDelegate.swift // SampleSlimyCollectionView // // Created by Hiroto on 2017/09/24. // Copyright © 2017年 hi-ro-to. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.468085
285
0.75641
23a0ddebe76254280699071b4b3d4d72d65bf6d4
13,704
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import UIKit import nRFMeshProvision class SetHeartbeatPublicationViewController: ProgressViewController { // MARK: - Outlets & Actions @IBOutlet weak var doneButton: UIBarButtonItem! @IBAction func cancelTapped(_ sender: UIBarButtonItem) { dismiss(animated: true) } @IBAction func doneTapped(_ sender: UIBarButtonItem) { setPublication() } @IBAction func countDidChange(_ sender: UISlider) { countSelected(sender.value) } @IBAction func periodDidChange(_ sender: UISlider) { periodSelected(sender.value) } @IBOutlet weak var destinationIcon: UIImageView! @IBOutlet weak var destinationLabel: UILabel! @IBOutlet weak var destinationSubtitleLabel: UILabel! @IBOutlet weak var keyIcon: UIImageView! @IBOutlet weak var keyLabel: UILabel! @IBOutlet weak var ttlLabel: UILabel! @IBOutlet weak var countSlider: UISlider! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var periodSlider: UISlider! @IBOutlet weak var periodLabel: UILabel! @IBOutlet weak var relaySwitch: UISwitch! @IBOutlet weak var proxySwitch: UISwitch! @IBOutlet weak var friendSwitch: UISwitch! @IBOutlet weak var lowPowerSwitch: UISwitch! // MARK: - Properties var node: Node! var delegate: PublicationDelegate? private var destination: Address? private var networkKey: NetworkKey? private var ttl: UInt8 = 5 { didSet { ttlLabel.text = "\(ttl)" } } private var countLog: UInt8 = 0 private var periodLog: UInt8 = 1 // The UI does not allow to set periodLog to 0. // MARK: - View Controller override func viewDidLoad() { super.viewDidLoad() MeshNetworkManager.instance.delegate = self if let publication = node.heartbeatPublication { destination = publication.address networkKey = node.networkKeys.first { $0.index == publication.networkKeyIndex } ttl = publication.ttl countLog = 0 // This is not stored in the database and is reset each time. periodLog = max(publication.periodLog, 1) relaySwitch.isOn = publication.features.contains(.relay) proxySwitch.isOn = publication.features.contains(.proxy) friendSwitch.isOn = publication.features.contains(.friend) lowPowerSwitch.isOn = publication.features.contains(.lowPower) // Period Slider only allows setting values greater than 0. // Disabling periodic Heartbeat messages is done by setting // countSlider to 0. periodSlider.value = Float(periodLog - 1) } else { networkKey = node.networkKeys.first } relaySwitch.isEnabled = node.features?.relay != .notSupported proxySwitch.isEnabled = node.features?.proxy != .notSupported friendSwitch.isEnabled = node.features?.friend != .notSupported lowPowerSwitch.isEnabled = node.features?.friend != .notSupported reloadKeyView() reloadDestinationView() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath == .ttl { presentTTLDialog() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case .some("setDestination"): let viewController = segue.destination as! SetHeartbeatPublicationDestinationsViewController viewController.target = node viewController.selectedNetworkKey = networkKey viewController.selectedDestination = destination viewController.delegate = self default: break } } } private extension SetHeartbeatPublicationViewController { /// Presents a dialog to edit the Initial TTL for Heartbeat messages. func presentTTLDialog() { presentTextAlert(title: "Initial TTL", message: "TTL = Time To Live\n\nTTL to be used when sending Heartbeat messages.\n" + "Max value is 127. Message with TTL 0 will not be relayed.", text: "5", placeHolder: "Default is 5", type: .ttlRequired, cancelHandler: nil) { value in self.ttl = UInt8(value)! } } func countSelected(_ value: Float) { countLog = value < 18 ? UInt8(value) : 0xFF countLabel.text = countLog.countString // Update Period slider. periodSlider.isEnabled = countLog > 0 switch countLog { case 0: periodLabel.text = "N/A" default: periodLabel.text = UInt8(periodSlider.value + 1).periodString break } } func periodSelected(_ value: Float) { periodLog = UInt8(value + 1) periodLabel.text = periodLog.periodString } func reloadKeyView() { if let networkKey = networkKey { keyIcon.tintColor = .nordicLake keyLabel.text = networkKey.name } else { keyIcon.tintColor = .lightGray keyLabel.text = "No Key Selected" } } func reloadDestinationView() { guard let address = destination else { destinationLabel.text = "No destination selected" if #available(iOS 13.0, *) { destinationLabel.textColor = .secondaryLabel destinationIcon.tintColor = .secondaryLabel } else { destinationLabel.textColor = .lightGray destinationIcon.tintColor = .lightGray } destinationSubtitleLabel.text = nil doneButton.isEnabled = false return } if #available(iOS 13.0, *) { destinationLabel.textColor = .label } else { destinationLabel.textColor = .darkText } let meshNetwork = MeshNetworkManager.instance.meshNetwork! if address.isUnicast { let node = meshNetwork.node(withAddress: address) destinationLabel.text = node?.name ?? "Unknown Device" destinationSubtitleLabel.text = nil destinationIcon.tintColor = .nordicLake destinationIcon.image = #imageLiteral(resourceName: "ic_flag_24pt") doneButton.isEnabled = true } else if address.isGroup { if let group = meshNetwork.group(withAddress: address) ?? Group.specialGroup(withAddress: address) { destinationLabel.text = group.name destinationSubtitleLabel.text = nil } else { destinationLabel.text = "Unknown group" destinationSubtitleLabel.text = address.asString() } destinationIcon.image = #imageLiteral(resourceName: "tab_groups_outline_black_24pt") destinationIcon.tintColor = .nordicLake doneButton.isEnabled = true } else { destinationLabel.text = "Invalid address" destinationSubtitleLabel.text = nil destinationIcon.tintColor = .nordicRed destinationIcon.image = #imageLiteral(resourceName: "ic_flag_24pt") doneButton.isEnabled = false } } func setPublication() { guard let destination = destination, let networkKey = networkKey, let node = self.node else { return } var features: NodeFeatures = [] if relaySwitch.isOn { features.insert(.relay) } if proxySwitch.isOn { features.insert(.proxy) } if friendSwitch.isOn { features.insert(.friend) } if lowPowerSwitch.isOn { features.insert(.lowPower) } let periodLog = countLog > 0 ? self.periodLog : 0 let countLog = self.countLog let ttl = self.ttl start("Setting Heartbeat Publication...") { [features] in let message: ConfigMessage = ConfigHeartbeatPublicationSet(startSending: countLog, heartbeatMessagesEvery: periodLog, secondsTo: destination, usingTtl: ttl, andNetworkKey: networkKey, andEnableHeartbeatMessagesTriggeredByChangeOf: features)! return try MeshNetworkManager.instance.send(message, to: node) } } } extension SetHeartbeatPublicationViewController: HeartbeatDestinationDelegate { func keySelected(_ key: NetworkKey) { networkKey = key reloadKeyView() } func destinationSelected(_ address: Address) { destination = address reloadDestinationView() } } extension SetHeartbeatPublicationViewController: MeshNetworkDelegate { func meshNetworkManager(_ manager: MeshNetworkManager, didReceiveMessage message: MeshMessage, sentFrom source: Address, to destination: Address) { // Has the Node been reset remotely. guard !(message is ConfigNodeReset) else { (UIApplication.shared.delegate as! AppDelegate).meshNetworkDidChange() done { let rootViewControllers = self.presentingViewController?.children self.dismiss(animated: true) { rootViewControllers?.forEach { if let navigationController = $0 as? UINavigationController { navigationController.popToRootViewController(animated: true) } } } } return } // Is the message targeting the current Node? guard node.unicastAddress == source else { return } // Handle the message based on its type. switch message { case let status as ConfigHeartbeatPublicationStatus: done { if status.status == .success { self.dismiss(animated: true) self.delegate?.publicationChanged() } else { self.presentAlert(title: "Error", message: status.message) } } default: break } } func meshNetworkManager(_ manager: MeshNetworkManager, failedToSendMessage message: MeshMessage, from localElement: Element, to destination: Address, error: Error) { done { self.presentAlert(title: "Error", message: error.localizedDescription) } } } private extension UInt8 { var countString: String { switch self { case 0: return "Disabled" case 0x11: return "65534" case 0xFF: return "Indefinitely" default: return "\(Int(pow(2.0, Double(self - 1))))" } } var periodString: String { assert(self > 0) let value = self < 0x11 ? Int(pow(2.0, Double(self - 1))) : 0xFFFF if value / 3600 > 0 { return "\(value / 3600) h \((value % 3600) / 60) min \(value % 60) sec" } if value / 60 > 0 { return "\(value / 60) min \(value % 60) sec" } if value == 1 { return "1 second" } return "\(value) seconds" } } private extension IndexPath { static let destinationSection = 0 static let detailsSection = 1 static let ttl = IndexPath(row: 0, section: 1) var isDestination: Bool { return section == IndexPath.destinationSection && row == 0 } var isDetailsSection: Bool { return section == IndexPath.detailsSection } }
36.739946
112
0.605881
87df548a9988fe132bbef49d5d47ee8ec5a55b1d
1,042
/* See LICENSE folder for this sample’s licensing information. Abstract: A view showing a list of landmarks. */ import SwiftUI struct LandmarkList: View { @EnvironmentObject private var userData: UserData var body: some View { List { Toggle(isOn: $userData.showFavoritesOnly) { Text("Show Favorites Only") } ForEach(userData.landmarks) { landmark in if !self.userData.showFavoritesOnly || landmark.isFavorite { NavigationButton( destination: LandmarkDetail(landmark: landmark)) { LandmarkRow(landmark: landmark) } } } } .navigationBarTitle(Text("Landmarks"), displayMode: .large) } } #if DEBUG struct LandmarksList_Previews: PreviewProvider { static var previews: some View { NavigationView { LandmarkList() .environmentObject(UserData()) } } } #endif
24.809524
76
0.560461
187fdae7dabf75623c194f7755ac6569cff278bb
4,594
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public class MediaFile: APIModel { /** The way in which the media file is delivered. */ public enum DeliveryType: String, Codable { case stream = "Stream" case progressive = "Progressive" case download = "Download" public static let cases: [DeliveryType] = [ .stream, .progressive, .download, ] } /** The resolution of the video media. */ public enum Resolution: String, Codable { case sd = "SD" case hd720 = "HD-720" case hd1080 = "HD-1080" case unknown = "Unknown" public static let cases: [Resolution] = [ .sd, .hd720, .hd1080, .unknown, ] } /** The name of the media file. */ public var name: String /** The way in which the media file is delivered. */ public var deliveryType: DeliveryType /** The url to access the media file. */ public var url: URL /** The type of drm used to encrypt the media. 'None' if unencrypted. */ public var drm: String /** The format the media was encoded in. */ public var format: String /** The resolution of the video media. */ public var resolution: Resolution /** The width of the video media. */ public var width: Int /** The height of the video media. */ public var height: Int /** The language code for the media, e.g. 'en'. */ public var language: String /** The number of audio channels. */ public var channels: Int? public init(name: String, deliveryType: DeliveryType, url: URL, drm: String, format: String, resolution: Resolution, width: Int, height: Int, language: String, channels: Int? = nil) { self.name = name self.deliveryType = deliveryType self.url = url self.drm = drm self.format = format self.resolution = resolution self.width = width self.height = height self.language = language self.channels = channels } private enum CodingKeys: String, CodingKey { case name case deliveryType case url case drm case format case resolution case width case height case language case channels } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(.name) deliveryType = try container.decode(.deliveryType) url = try container.decode(.url) drm = try container.decode(.drm) format = try container.decode(.format) resolution = try container.decode(.resolution) width = try container.decode(.width) height = try container.decode(.height) language = try container.decode(.language) channels = try container.decodeIfPresent(.channels) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(deliveryType, forKey: .deliveryType) try container.encode(url, forKey: .url) try container.encode(drm, forKey: .drm) try container.encode(format, forKey: .format) try container.encode(resolution, forKey: .resolution) try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) try container.encode(language, forKey: .language) try container.encodeIfPresent(channels, forKey: .channels) } public func isEqual(to object: Any?) -> Bool { guard let object = object as? MediaFile else { return false } guard self.name == object.name else { return false } guard self.deliveryType == object.deliveryType else { return false } guard self.url == object.url else { return false } guard self.drm == object.drm else { return false } guard self.format == object.format else { return false } guard self.resolution == object.resolution else { return false } guard self.width == object.width else { return false } guard self.height == object.height else { return false } guard self.language == object.language else { return false } guard self.channels == object.channels else { return false } return true } public static func == (lhs: MediaFile, rhs: MediaFile) -> Bool { return lhs.isEqual(to: rhs) } }
32.125874
187
0.622987
ff6f5674a83f2c46ed0ebe0388c79035bd479b7d
2,291
// // SceneDelegate.swift // SegueExample // // Created by Yunjia Gao on 2/6/22. // 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.226415
147
0.712789