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
018fadbc62ae6842c0787f06917f4818407cad35
4,404
//Predicate.swift /* MIT License Copyright (c) 2019 Jordhan Leoture 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 /// Predicate represents a condition on an `Input`. public class Predicate<Input> { // MARK: - Properties /// Description of the Predicate. public var description: String private let predicate: (Input) -> Bool // MARK: - Init private init(description: String, predicate: @escaping (Input) -> Bool) { self.description = description self.predicate = predicate } // MARK: - Public Methods /// Creates a `Predicate<Input>`. /// - Parameter description: The description of the Predicate. /// - Parameter predicate: The block that will be used to verify that the entry statisfies the Predicate. /// - Returns: A new `Predicate<Input>`. public static func match(description: String = "custom matcher", _ predicate: @escaping (Input) -> Bool) -> Predicate<Input> { Predicate(description: description, predicate: predicate) } /// Creates a `AnyPredicate`. /// - Parameter value: The value to match. /// - Parameter file: The file name where the method is called. /// - Parameter line: The line where the method is called. /// - Returns: A `AnyPredicate` able to match `value`. /// - Important: If value cannot be cast to `AnyPredicate` or to `AnyObject` a `fatalError` will be raised. public static func match(_ value: Input, file: StaticString = #file, line: UInt = #line) -> AnyPredicate { switch value { case let value as AnyPredicate: return value case let value as AnyObject: return Predicate<AnyObject>.match(description: "\(value)") { $0 === value } default: return ErrorHandler().handle( InternalError.castTwice(source: value, firstTarget: AnyPredicate.self, secondTarget: AnyObject.self), file: file, line: line) } } /// Creates a `Predicate<Input>`. /// - Parameter description: The description of the Predicate. /// - Parameter keyPath: The keyPath that will be used to verify that the entry statisfies the Predicate. /// - Returns: A new `Predicate<Input>`. public class func match(description: String = "KeyPath matcher", _ keyPath: KeyPath<Input, Bool>) -> Predicate<Input> { .match(description: description) { $0[keyPath: keyPath] } } /// Creates a `Predicate<Input>` able to match any value of type `Input`. public static func any() -> Predicate<Input> { .match(description: "any") { _ in true } } /// Creates a `Predicate<Input>` able to match any value of type `Input` not matched by an other predicate. /// - Parameter predicate: The predicate to not match. /// - Returns: A new `Predicate<Input>`. public static func not(_ predicate: Predicate<Input>) -> Predicate<Input> { .match(description: "not \(predicate)") { !predicate.satisfy(by: $0) } } } // MARK: - AnyPredicate extension Predicate: AnyPredicate { /// Check if an `element` satifies the predicate. /// - Parameter element: The element to check. /// - Returns: True if `element` is of type `Input` and satisfies the predicate, false otherwise. /// - SeeAlso: `AnyPredicate` public func satisfy(by element: Any?) -> Bool { guard let element = element as? Input else { return false } return predicate(element) } }
38.973451
109
0.692098
26eec6b4b78e2fc0ceb63871c07b3baf9f87e243
5,956
// // UIViewController.swift // WolmoCore // // Created by Guido Marucci Blas on 5/7/16. // Copyright © 2016 Wolox. All rights reserved. // import UIKit public extension UIViewController { /** Loads the childViewController into the specified containerView. It can be done after self's view is initialized, as it uses constraints to determine the childViewController size. Take into account that self will retain the childViewController, so if for any other reason the childViewController is retained in another place, this would lead to a memory leak. In that case, one should call unloadViewController(). - parameter childViewController: The controller to load. - parameter into: The containerView into which the controller will be loaded. - parameter viewPositioning: Back or Front. Default: Front */ public func load(childViewController: UIViewController, into containerView: UIView, with insets: UIEdgeInsets = .zero, in viewPositioning: ViewPositioning = .front, layout: LayoutMode = .constraints, respectSafeArea: Bool = false) { childViewController.willMove(toParent: self) addChild(childViewController) childViewController.didMove(toParent: self) childViewController.view.add(into: containerView, with: insets, in: viewPositioning, layout: layout, respectSafeArea: respectSafeArea) } /** Unloads a childViewController and its view from its parentViewController. */ public func unloadFromParentViewController() { view.removeFromSuperview() removeFromParent() } /** Unloads all childViewController and their view from self. */ public func unloadChildViewControllers() { for childController in self.children { childController.unloadFromParentViewController() } } } // MARK: - Navigation Bar public extension UIViewController { /** Configures the navigation bar to have a particular image as back button. - parameter image: The image of the back button. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ public func setNavigationBarBackButton(_ image: UIImage) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.topItem?.title = "" navigationController.navigationBar.backIndicatorImage = image navigationController.navigationBar.backIndicatorTransitionMaskImage = image } /** Configures the navigation bar color. - parameter color: The new color of the navigation bar. This represents the navigation bar background color. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ public func setNavigationBarColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barTintColor = color } /** Configures the navigation bar tint color. - parameter color: The new tint color of the navigation bar. This represents the color of the left and right button items. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ public func setNavigationBarTintColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.tintColor = color } /** Configures the navigation bar style. - parameter style: The new style of the navigation bar. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ public func setNavigationBarStyle(_ style: UIBarStyle) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barStyle = style } /** Sets a collection of buttons as the navigation bar left buttons. - parameter buttons: the Array of buttons to use. */ public func setNavigationLeftButtons(_ buttons: [UIBarButtonItem]) { navigationItem.leftBarButtonItems = buttons } /** Sets a collection of buttons as the navigation bar right buttons. - parameter buttons: the Array of buttons to use. */ public func setNavigationRightButtons(_ buttons: [UIBarButtonItem]) { navigationItem.rightBarButtonItems = buttons } /** Adds and configures a label to use as title of the navigation bar. - parameter title: the string of the label. - parameter font: the font to use for the label. - parameter color: the color of the text. */ public func setNavigationBarTitle(_ title: String, font: UIFont, color: UIColor) { let label = UILabel(frame: .zero) label.backgroundColor = .clear label.font = font label.textColor = color label.adjustsFontSizeToFitWidth = true label.text = title label.sizeToFit() navigationItem.titleView = label } /** Adds an ImageView with the image passed as the titleView of the navigation bar. - parameter image: The image to set as title. */ public func setNavigationBarTitleImage(_ image: UIImage) { navigationItem.titleView = UIImageView(image: image) } }
38.928105
161
0.679147
2037400031fa2a10cf85ee302bdb5da1ca9afb8c
265
// // Dilution.swift // Darkroom Timer // // Created by John Jones on 1/18/22. // import Foundation struct Dilution: Decodable, Encodable, Identifiable { var id: String { return self.ratio } let ratio: String let speeds: [Speed] }
14.722222
53
0.622642
f5ad249b73dcab8447e9d471c69935c4171ff724
6,799
// // XNUISettingsVC.swift // XNLogger // // Created by Sunil Sharma on 16/08/19. // Copyright © 2019 Sunil Sharma. All rights reserved. // import UIKit class XNUISettingsVC: XNUIBaseViewController { @IBOutlet weak var settingsTableView: UITableView! var settingCategory: [XNUISettingCategory] = [] override func viewDidLoad() { super.viewDidLoad() configureViews() loadData() settingsTableView.reloadData() } func configureViews() { self.headerView?.setTitle("Settings") self.edgesForExtendedLayout = [] let closeButton = helper.createNavButton( imageName: "close", imageInsets: UIEdgeInsets(top: 15, left: 25, bottom: 9, right: 5)) closeButton.addTarget(self, action: #selector(dismissNetworkUI), for: .touchUpInside) self.headerView?.addRightBarItems([closeButton]) settingsTableView.register(ofType: XNUISettingsCell.self) settingsTableView.delegate = self settingsTableView.dataSource = self } func loadData() { let utility = XNUIHelper() let generalCategory = XNUISettingCategory() let startStop = XNUISettingItem(title: "Network Logging", type: .startStopLog) startStop.value = XNLogger.shared.isEnabled() generalCategory.items.append(startStop) let logSettings = XNUISettingCategory(title: " ") let textOnlyRequest = XNUISettingItem(title: "Log unreadable request body", subTitle: "Enable to log image, pdf, binary, etc.", type: .logUnreadableRequest, value: false) textOnlyRequest.value = XNUIManager.shared.uiLogHandler.logFormatter.logUnreadableReqstBody logSettings.items.append(textOnlyRequest) let textOnlyResponse = XNUISettingItem(title: "Log unreadable response", subTitle: "Enable to log image, pdf, binary, etc.", type: .logUnreadableResponse, value: false) textOnlyResponse.value = XNUIManager.shared.uiLogHandler.logFormatter.logUnreadableRespBody logSettings.items.append(textOnlyResponse) let clearActions = XNUISettingCategory(title: " ") let clearLog = XNUISettingItem(title: "Clear data", type: .clearData) clearLog.textColor = UIColor.systemRed clearActions.items.append(clearLog) let info = XNUISettingCategory(title: "About") let version = XNUISettingItem(title: "Version - \(utility.getVersion())", type: .version) version.textColor = UIColor.darkGray info.items.append(version) let help = XNUISettingItem(title: "Help", type: .help) if #available(iOS 13.0, *) { help.textColor = UIColor.link } else { help.textColor = UIColor.systemBlue } info.items.append(help) var categories: [XNUISettingCategory] = [] categories.append(generalCategory) categories.append(logSettings) categories.append(clearActions) categories.append(info) self.settingCategory = categories } func updateLog(isEnabled: Bool) { if isEnabled { XNLogger.shared.startLogging() } else { XNLogger.shared.stopLogging() } } func updateLogUnreadableRequest(isEnabled: Bool) { XNUIManager.shared.uiLogHandler.logFormatter.logUnreadableReqstBody = isEnabled } func updateLogUnreadableResponse(isEnabled: Bool) { XNUIManager.shared.uiLogHandler.logFormatter.logUnreadableRespBody = isEnabled } func clearLogData() { XNUIManager.shared.clearLogs() if let logNav = self.tabBarController?.viewControllers?.first as? UINavigationController, let logListVC = logNav.viewControllers.first as? XNUILogListVC { logNav.popToRootViewController(animated: false) logListVC.updateLoggerUI() } } @objc func dismissNetworkUI() { XNUIManager.shared.dismissUI() } } extension XNUISettingsVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return settingCategory.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return settingCategory[section].items.count } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 3 } else { return UITableView.automaticDimension } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let category = settingCategory[section] return category.title } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNonzeroMagnitude } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: XNUISettingsCell = tableView.dequeueReusableCell(for: indexPath) let settingItem = settingCategory[indexPath.section].items[indexPath.row] cell.delegate = self cell.updateCell(with: settingItem) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = settingCategory[indexPath.section].items[indexPath.row] if item.type == .clearData { clearLogData() } if item.type == .help, let helpUrl = URL(string: "https://github.com/sunilsharma08/XNLogger") { if UIApplication.shared.canOpenURL(helpUrl) { UIApplication.shared.openURL(helpUrl) } } DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) { tableView.deselectRow(at: indexPath, animated: true) } } } extension XNUISettingsVC: XNUISettingsCellDelegate { func switchValueChanged(_ isOn: Bool, settingItem: XNUISettingItem) { if settingItem.type == .startStopLog { updateLog(isEnabled: isOn) } if settingItem.type == .logUnreadableRequest { updateLogUnreadableRequest(isEnabled: isOn) } if settingItem.type == .logUnreadableResponse { updateLogUnreadableResponse(isEnabled: isOn) } } }
35.973545
178
0.651272
fc6cbe952d79f1a7be77b1a01a6aeb5da6ac1179
3,722
// // IBBSEditorBaseViewController.swift // iBBS // // Created by Augus on 10/12/15. // Copyright © 2015 iAugus. All rights reserved. // import UIKit class IBBSEditorBaseViewController: ZSSRichTextEditor { override func viewDidLoad() { super.viewDidLoad() shouldShowKeyboard = false navigationItem.rightBarButtonItem = UIBarButtonItem(title: BUTTON_SEND, style: .Plain, target: self, action: #selector(sendAction)) formatHTML = false // Set the base URL if you would like to use relative links, such as to images. baseURL = NSURL(string: "http://iAugus.com") // Set the toolbar item color toolbarItemTintColor = UIColor.blackColor() // Set the toolbar selected color toolbarItemSelectedTintColor = CUSTOM_THEME_COLOR // Choose which toolbar items to show // enabledToolbarItems = [ZSSRichTextEditorToolbarBold, ZSSRichTextEditorToolbarH1, ZSSRichTextEditorToolbarParagraph] /** ZSSRichTextEditorToolbarBold ZSSRichTextEditorToolbarItalic ZSSRichTextEditorToolbarSubscript ZSSRichTextEditorToolbarSuperscript ZSSRichTextEditorToolbarStrikeThrough ZSSRichTextEditorToolbarUnderline ZSSRichTextEditorToolbarRemoveFormat ZSSRichTextEditorToolbarJustifyLeft ZSSRichTextEditorToolbarJustifyCenter ZSSRichTextEditorToolbarJustifyRight ZSSRichTextEditorToolbarJustifyFull ZSSRichTextEditorToolbarH1 ZSSRichTextEditorToolbarH2 ZSSRichTextEditorToolbarH3 ZSSRichTextEditorToolbarH4 ZSSRichTextEditorToolbarH5 ZSSRichTextEditorToolbarH6 ZSSRichTextEditorToolbarTextColor ZSSRichTextEditorToolbarBackgroundColor ZSSRichTextEditorToolbarUnorderedList ZSSRichTextEditorToolbarOrderedList ZSSRichTextEditorToolbarHorizontalRule ZSSRichTextEditorToolbarIndent ZSSRichTextEditorToolbarOutdent ZSSRichTextEditorToolbarInsertImage ZSSRichTextEditorToolbarInsertLink ZSSRichTextEditorToolbarRemoveLink ZSSRichTextEditorToolbarQuickLink ZSSRichTextEditorToolbarUndo ZSSRichTextEditorToolbarRedo ZSSRichTextEditorToolbarViewSource ZSSRichTextEditorToolbarParagraph ZSSRichTextEditorToolbarAll ZSSRichTextEditorToolbarNone */ } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.tintColor = CUSTOM_THEME_COLOR navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : CUSTOM_THEME_COLOR] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func showInsertURLAlternatePicker() { dismissAlertView() let picker = IBBSPickerViewController() picker.demoView = self let nav = UINavigationController() nav.navigationBar.translucent = false presentViewController(nav, animated: true, completion: nil) } override func showInsertImageAlternatePicker() { dismissAlertView() let picker = IBBSPickerViewController() picker.demoView = self picker.isInsertImagePicker = true let nav = UINavigationController() nav.navigationBar.translucent = false presentViewController(nav, animated: true, completion: nil) } func exportHTML() { NSLog("%@", getHTML()) } func sendAction() {} }
33.836364
139
0.702311
d7ed33502ebe02d8280dfea746520ce11c534f6f
3,412
// // AppDelegate.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2015-09-16. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import UIKit import ReactiveSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func _setupAppearance() { let font = UIFont(name: "AvenirNext-Medium", size: 16)! UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName: font ] UIBarButtonItem.appearance().setTitleTextAttributes([ NSFontAttributeName: font ], for: .normal) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { self._setupAppearance() let splitVC = self.window!.rootViewController as! UISplitViewController splitVC.delegate = self splitVC.preferredDisplayMode = .allVisible let mainNavC = splitVC.viewControllers[0] as! UINavigationController let mainVC = mainNavC.topViewController as! MasterViewController // NOTE: use dispatch_after to check `splitVC.collapsed` after delegation is complete (for iPad) // FIXME: look for better solution DispatchQueue.main.asyncAfter(deadline: .now() + 1) { if !splitVC.isCollapsed { mainVC.showDetailViewController(at: 0) } } 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:. } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { return true } }
45.493333
285
0.737104
222937005ad437c0464fde53347dbd77b272f76a
884
// RUN: %target-swift-frontend -parse-as-library -O -module-name=test %s -emit-sil | %FileCheck %s // FIXME: https://bugs.swift.org/browse/SR-2808 // XFAIL: resilient_stdlib final class Item {} final public class Escaper { var myItem: Item = Item() @inline(never) func update(items: [Item]) { myItem = items[0] } // CHECK-LABEL: sil [noinline] @_TFC4test7Escaper15badStuffHappensfT_T_ : $@convention(method) (@guaranteed Escaper) -> () { // CHECK: %2 = alloc_ref $Item // CHECK: alloc_ref [stack] [tail_elems $Item * %{{[0-9]+}} : $Builtin.Word] $_ContiguousArrayStorage<Item> // CHECK: return @inline(never) public func badStuffHappens() { // Check that 'item' is not stack promoted, because it escapes to myItem. let item = Item() // On the other hand, the array buffer of the array literal should be stack promoted. update(items:[item]) } }
30.482759
124
0.677602
26d3d8bba7e01a9fb57d7dcbbc35efdfd749a100
515
// // DPActivityIndicatorStyle.swift // DPActivityIndicatorExample // // Created by Dennis Pashkov on 4/15/16. // Copyright © 2016 Dennis Pashkov. All rights reserved. // public enum DPActivityIndicatorStyle: Int { case Native func displayValue() -> String { switch ( self ) { case .Native: return "Native" } } static func allStyles() -> [DPActivityIndicatorStyle] { return [.Native] } }
19.074074
59
0.549515
e6756ef33af03dbeb02231c19a62abb4ff390044
7,744
// // TweetsViewController.swift // Twitter // // Created by Arnav Jain on 25/02/17. // Copyright © 2017 Arnav Jain. All rights reserved. // import UIKit class TweetsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! static var tweets: [Tweet]? let refreshControl = UIRefreshControl() var profileTweet:NSDictionary! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension refreshControl.addTarget(self, action: #selector(refreshControlAction(refreshControl:)), for: .valueChanged) tableView.insertSubview(refreshControl, at: 0) TwitterClient.sharedInstance?.homeTimeline(success: { (tweets: [Tweet]) in TweetsViewController.tweets = tweets self.tableView.reloadData() for tweet in tweets { print(tweet) } }, failure: { (error: Error) in print(error.localizedDescription) }) // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { TwitterClient.sharedInstance?.homeTimeline(success: { (tweets: [Tweet]) in TweetsViewController.tweets = tweets self.tableView.reloadData() for tweet in tweets { //print(tweet.imageURL) } }, failure: { (error: Error) in print(error.localizedDescription) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // @IBAction func imageViewPressed(_ sender: Any) { // let senderView = sender as! UIImageView // let tweet = TweetsViewController.tweets![senderView.tag] as! Tweet // print("tweet") // } @IBAction func avatarButton(_ sender: Any) { let senderCell = sender as! UIButton let tweet = TweetsViewController.tweets?[senderCell.tag] print((tweet?.screen_name!)!) TwitterClient.sharedInstance?.getUser(id: (tweet?.screen_name!)!, success: { (response: NSDictionary) in self.profileTweet = response self.performSegue(withIdentifier: "profile", sender: sender) print(response) }, failure: { (error: Error) in print(error.localizedDescription) }) print("hello") } func refreshControlAction(refreshControl: UIRefreshControl) { TwitterClient.sharedInstance?.homeTimeline(success: { (tweets: [Tweet]) in TweetsViewController.tweets = tweets self.tableView.reloadData() for tweet in tweets { print(tweet) } }, failure: { (error: Error) in print(error.localizedDescription) }) refreshControl.endRefreshing() } @IBAction func onLogoutPressed(_ sender: AnyObject) { TwitterClient.sharedInstance?.logout() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let tweets = TweetsViewController.tweets { return tweets.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell", for: indexPath) as! TweetCell cell.selectionStyle = UITableViewCellSelectionStyle.none cell.tweetLabel.text = TweetsViewController.tweets![indexPath.row].text cell.tweet = TweetsViewController.tweets![indexPath.row] cell.indexPathRow = indexPath.row if let imageURL = TweetsViewController.tweets![indexPath.row].imageURL { let newImageURL = imageURL.replacingOccurrences(of: "_normal", with: "") cell.avatarImageView.setImageWith(URL(string: newImageURL)!) cell.userLabel.text = TweetsViewController.tweets![indexPath.row].user cell.avatarButton.tag = indexPath.row cell.avatarImageView.tag = indexPath.row if cell.tweet.favourited == true { //self.favImgView.image = UIImage(named: "favor-icon-red") cell.favButton.setImage(UIImage(named: "favor-icon-red"), for: .normal) } else { //self.favImgView.image = UIImage(named: "favor-icon") cell.favButton.setImage(UIImage(named: "favor-icon"), for: .normal) } if cell.tweet.retweeted == true { cell.retweetButton.setImage(UIImage(named: "retweet-icon-green"), for: .normal) //self.favImgView.image = UIImage(named: "retweet-icon") } else { cell.retweetButton.setImage(UIImage(named: "retweet-icon"), for: .normal) } print(cell.tweet) } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detail" { let senderCell = sender as! TweetCell let destination = segue.destination as! DetailsViewController let indexPath = tableView.indexPath(for: senderCell) print(indexPath) destination.tweet = TweetsViewController.tweets?[indexPath!.row as! Int] destination.indexPath = indexPath!.row destination.ImageName = senderCell.tweet.imageURL } if segue.identifier == "currentuser" { let destination = segue.destination as! ProfileViewController destination.backImageURL = User.currentUser?.dictionary!["profile_banner_url"] as! String destination.avatarImageURL = (User.currentUser?.dictionary!["profile_image_url_https"] as! String).replacingOccurrences(of: "_normal", with: "") destination.followersText = User.currentUser!.dictionary!["followers_count"] as! Int destination.followingText = User.currentUser!.dictionary!["friends_count"] as! Int destination.tweetsText = User.currentUser!.dictionary!["statuses_count"] as! Int print(User.currentUser!.dictionary!) //print(User.currentUser!.dictionary!["followers_count"] as? String) } if segue.identifier == "profile" { let destination = segue.destination as! ProfileViewController if let url = self.profileTweet["profile_banner_url"] as? String { destination.backImageURL = self.profileTweet["profile_banner_url"] as! String } destination.avatarImageURL = (self.profileTweet["profile_image_url_https"] as! String).replacingOccurrences(of: "_normal", with: "") destination.followersText = self.profileTweet["followers_count"] as! Int destination.followingText = self.profileTweet["friends_count"] as! Int destination.tweetsText = self.profileTweet["statuses_count"] as! Int } } }
39.510204
156
0.622159
7ae5e948b4f37b01fbe1fb04c837c6d2d6d07431
1,494
// // TripMapDetails.swift // SEATCode // // Created by Luis Valdés on 11/10/2020. // import Foundation import MapKit import Polyline struct TripMapDetails { let origin: LocationAnnotation let destination: LocationAnnotation let stops: [LocationAnnotation] let route: MKPolyline? init(trip: Trip) { origin = LocationAnnotation(stopId: nil, title: "Origin", latitude: trip.origin.latitude, longitude: trip.origin.longitude) destination = LocationAnnotation(stopId: nil, title: "Destination", latitude: trip.destination.latitude, longitude: trip.destination.longitude) stops = trip.stops.map { LocationAnnotation(stopId: $0.id, title: nil, latitude: $0.latitude, longitude: $0.longitude) } route = Polyline(encodedPolyline: trip.route).mkPolyline } } final class LocationAnnotation: NSObject, MKAnnotation { let stopId: Int? let title: String? let subtitle: String? = nil let coordinate: CLLocationCoordinate2D init(stopId: Int?, title: String?, latitude: Double, longitude: Double) { self.stopId = stopId self.title = title self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) super.init() } }
31.787234
105
0.585676
8f9f78a5571ef601e5a920ab00a6bc160873e1e3
40,616
// // Contract.swift // SwiftFHIR // // Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Contract) on 2016-09-16. // 2016, SMART Health IT. // import Foundation /** * Contract. * * A formal agreement between parties regarding the conduct of business, exchange of information or other matters. */ public class Contract: DomainResource { override public class var resourceType: String { get { return "Contract" } } /// Contract Action. public var action: [CodeableConcept]? /// Contract Action Reason. public var actionReason: [CodeableConcept]? /// Contract Actor. public var actor: [ContractActor]? /// Effective time. public var applies: Period? /// Authority under which this Contract has standing. public var authority: [Reference]? /// Binding Contract. public var bindingAttachment: Attachment? /// Binding Contract. public var bindingReference: Reference? /// Domain in which this Contract applies. public var domain: [Reference]? /// Contract Friendly Language. public var friendly: [ContractFriendly]? /// Contract identifier. public var identifier: Identifier? /// When this Contract was issued. public var issued: DateTime? /// Contract Legal Language. public var legal: [ContractLegal]? /// Computable Contract Language. public var rule: [ContractRule]? /// Contract Signer. public var signer: [ContractSigner]? /// Contract Subtype. public var subType: [CodeableConcept]? /// Subject of this Contract. public var subject: [Reference]? /// Contract Term List. public var term: [ContractTerm]? /// Contract Tyoe. public var type: CodeableConcept? /// Contract Valued Item. public var valuedItem: [ContractValuedItem]? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["action"] { presentKeys.insert("action") if let val = exist as? [FHIRJSON] { self.action = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "action", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["actionReason"] { presentKeys.insert("actionReason") if let val = exist as? [FHIRJSON] { self.actionReason = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "actionReason", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["actor"] { presentKeys.insert("actor") if let val = exist as? [FHIRJSON] { self.actor = ContractActor.instantiate(fromArray: val, owner: self) as? [ContractActor] } else { errors.append(FHIRJSONError(key: "actor", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["applies"] { presentKeys.insert("applies") if let val = exist as? FHIRJSON { self.applies = Period(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "applies", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["authority"] { presentKeys.insert("authority") if let val = exist as? [FHIRJSON] { self.authority = Reference.instantiate(fromArray: val, owner: self) as? [Reference] } else { errors.append(FHIRJSONError(key: "authority", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["bindingAttachment"] { presentKeys.insert("bindingAttachment") if let val = exist as? FHIRJSON { self.bindingAttachment = Attachment(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "bindingAttachment", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["bindingReference"] { presentKeys.insert("bindingReference") if let val = exist as? FHIRJSON { self.bindingReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "bindingReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["domain"] { presentKeys.insert("domain") if let val = exist as? [FHIRJSON] { self.domain = Reference.instantiate(fromArray: val, owner: self) as? [Reference] } else { errors.append(FHIRJSONError(key: "domain", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["friendly"] { presentKeys.insert("friendly") if let val = exist as? [FHIRJSON] { self.friendly = ContractFriendly.instantiate(fromArray: val, owner: self) as? [ContractFriendly] } else { errors.append(FHIRJSONError(key: "friendly", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["identifier"] { presentKeys.insert("identifier") if let val = exist as? FHIRJSON { self.identifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "identifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["issued"] { presentKeys.insert("issued") if let val = exist as? String { self.issued = DateTime(string: val) } else { errors.append(FHIRJSONError(key: "issued", wants: String.self, has: type(of: exist))) } } if let exist = js["legal"] { presentKeys.insert("legal") if let val = exist as? [FHIRJSON] { self.legal = ContractLegal.instantiate(fromArray: val, owner: self) as? [ContractLegal] } else { errors.append(FHIRJSONError(key: "legal", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["rule"] { presentKeys.insert("rule") if let val = exist as? [FHIRJSON] { self.rule = ContractRule.instantiate(fromArray: val, owner: self) as? [ContractRule] } else { errors.append(FHIRJSONError(key: "rule", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["signer"] { presentKeys.insert("signer") if let val = exist as? [FHIRJSON] { self.signer = ContractSigner.instantiate(fromArray: val, owner: self) as? [ContractSigner] } else { errors.append(FHIRJSONError(key: "signer", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["subType"] { presentKeys.insert("subType") if let val = exist as? [FHIRJSON] { self.subType = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "subType", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["subject"] { presentKeys.insert("subject") if let val = exist as? [FHIRJSON] { self.subject = Reference.instantiate(fromArray: val, owner: self) as? [Reference] } else { errors.append(FHIRJSONError(key: "subject", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["term"] { presentKeys.insert("term") if let val = exist as? [FHIRJSON] { self.term = ContractTerm.instantiate(fromArray: val, owner: self) as? [ContractTerm] } else { errors.append(FHIRJSONError(key: "term", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["type"] { presentKeys.insert("type") if let val = exist as? FHIRJSON { self.type = CodeableConcept(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "type", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["valuedItem"] { presentKeys.insert("valuedItem") if let val = exist as? [FHIRJSON] { self.valuedItem = ContractValuedItem.instantiate(fromArray: val, owner: self) as? [ContractValuedItem] } else { errors.append(FHIRJSONError(key: "valuedItem", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let action = self.action { json["action"] = action.map() { $0.asJSON(with: options) } } if let actionReason = self.actionReason { json["actionReason"] = actionReason.map() { $0.asJSON(with: options) } } if let actor = self.actor { json["actor"] = actor.map() { $0.asJSON(with: options) } } if let applies = self.applies { json["applies"] = applies.asJSON(with: options) } if let authority = self.authority { json["authority"] = authority.map() { $0.asJSON(with: options) } } if let bindingAttachment = self.bindingAttachment { json["bindingAttachment"] = bindingAttachment.asJSON(with: options) } if let bindingReference = self.bindingReference { json["bindingReference"] = bindingReference.asJSON(with: options) } if let domain = self.domain { json["domain"] = domain.map() { $0.asJSON(with: options) } } if let friendly = self.friendly { json["friendly"] = friendly.map() { $0.asJSON(with: options) } } if let identifier = self.identifier { json["identifier"] = identifier.asJSON(with: options) } if let issued = self.issued { json["issued"] = issued.asJSON(with: options) } if let legal = self.legal { json["legal"] = legal.map() { $0.asJSON(with: options) } } if let rule = self.rule { json["rule"] = rule.map() { $0.asJSON(with: options) } } if let signer = self.signer { json["signer"] = signer.map() { $0.asJSON(with: options) } } if let subType = self.subType { json["subType"] = subType.map() { $0.asJSON(with: options) } } if let subject = self.subject { json["subject"] = subject.map() { $0.asJSON(with: options) } } if let term = self.term { json["term"] = term.map() { $0.asJSON(with: options) } } if let type = self.type { json["type"] = type.asJSON(with: options) } if let valuedItem = self.valuedItem { json["valuedItem"] = valuedItem.map() { $0.asJSON(with: options) } } return json } } /** * Contract Actor. * * List of Contract actors. */ public class ContractActor: BackboneElement { override public class var resourceType: String { get { return "ContractActor" } } /// Contract Actor Type. public var entity: Reference? /// Contract Actor Role. public var role: [CodeableConcept]? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(entity: Reference) { self.init(json: nil) self.entity = entity } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["entity"] { presentKeys.insert("entity") if let val = exist as? FHIRJSON { self.entity = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entity", wants: FHIRJSON.self, has: type(of: exist))) } } else { errors.append(FHIRJSONError(key: "entity")) } if let exist = js["role"] { presentKeys.insert("role") if let val = exist as? [FHIRJSON] { self.role = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "role", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let entity = self.entity { json["entity"] = entity.asJSON(with: options) } if let role = self.role { json["role"] = role.map() { $0.asJSON(with: options) } } return json } } /** * Contract Friendly Language. * * The "patient friendly language" versionof the Contract in whole or in parts. "Patient friendly language" means the * representation of the Contract and Contract Provisions in a manner that is readily accessible and understandable by * a layperson in accordance with best practices for communication styles that ensure that those agreeing to or signing * the Contract understand the roles, actions, obligations, responsibilities, and implication of the agreement. */ public class ContractFriendly: BackboneElement { override public class var resourceType: String { get { return "ContractFriendly" } } /// Easily comprehended representation of this Contract. public var contentAttachment: Attachment? /// Easily comprehended representation of this Contract. public var contentReference: Reference? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(contentAttachment: Attachment, contentReference: Reference) { self.init(json: nil) self.contentAttachment = contentAttachment self.contentReference = contentReference } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["contentAttachment"] { presentKeys.insert("contentAttachment") if let val = exist as? FHIRJSON { self.contentAttachment = Attachment(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentAttachment", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["contentReference"] { presentKeys.insert("contentReference") if let val = exist as? FHIRJSON { self.contentReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentReference", wants: FHIRJSON.self, has: type(of: exist))) } } // check if nonoptional expanded properties are present if nil == self.contentAttachment && nil == self.contentReference { errors.append(FHIRJSONError(key: "content*")) } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let contentAttachment = self.contentAttachment { json["contentAttachment"] = contentAttachment.asJSON(with: options) } if let contentReference = self.contentReference { json["contentReference"] = contentReference.asJSON(with: options) } return json } } /** * Contract Legal Language. * * List of Legal expressions or representations of this Contract. */ public class ContractLegal: BackboneElement { override public class var resourceType: String { get { return "ContractLegal" } } /// Contract Legal Text. public var contentAttachment: Attachment? /// Contract Legal Text. public var contentReference: Reference? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(contentAttachment: Attachment, contentReference: Reference) { self.init(json: nil) self.contentAttachment = contentAttachment self.contentReference = contentReference } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["contentAttachment"] { presentKeys.insert("contentAttachment") if let val = exist as? FHIRJSON { self.contentAttachment = Attachment(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentAttachment", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["contentReference"] { presentKeys.insert("contentReference") if let val = exist as? FHIRJSON { self.contentReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentReference", wants: FHIRJSON.self, has: type(of: exist))) } } // check if nonoptional expanded properties are present if nil == self.contentAttachment && nil == self.contentReference { errors.append(FHIRJSONError(key: "content*")) } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let contentAttachment = self.contentAttachment { json["contentAttachment"] = contentAttachment.asJSON(with: options) } if let contentReference = self.contentReference { json["contentReference"] = contentReference.asJSON(with: options) } return json } } /** * Computable Contract Language. * * List of Computable Policy Rule Language Representations of this Contract. */ public class ContractRule: BackboneElement { override public class var resourceType: String { get { return "ContractRule" } } /// Computable Contract Rules. public var contentAttachment: Attachment? /// Computable Contract Rules. public var contentReference: Reference? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(contentAttachment: Attachment, contentReference: Reference) { self.init(json: nil) self.contentAttachment = contentAttachment self.contentReference = contentReference } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["contentAttachment"] { presentKeys.insert("contentAttachment") if let val = exist as? FHIRJSON { self.contentAttachment = Attachment(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentAttachment", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["contentReference"] { presentKeys.insert("contentReference") if let val = exist as? FHIRJSON { self.contentReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "contentReference", wants: FHIRJSON.self, has: type(of: exist))) } } // check if nonoptional expanded properties are present if nil == self.contentAttachment && nil == self.contentReference { errors.append(FHIRJSONError(key: "content*")) } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let contentAttachment = self.contentAttachment { json["contentAttachment"] = contentAttachment.asJSON(with: options) } if let contentReference = self.contentReference { json["contentReference"] = contentReference.asJSON(with: options) } return json } } /** * Contract Signer. * * Party signing this Contract. */ public class ContractSigner: BackboneElement { override public class var resourceType: String { get { return "ContractSigner" } } /// Contract Signatory Party. public var party: Reference? /// Contract Documentation Signature. public var signature: String? /// Contract Signer Type. public var type: Coding? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(party: Reference, signature: String, type: Coding) { self.init(json: nil) self.party = party self.signature = signature self.type = type } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["party"] { presentKeys.insert("party") if let val = exist as? FHIRJSON { self.party = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "party", wants: FHIRJSON.self, has: type(of: exist))) } } else { errors.append(FHIRJSONError(key: "party")) } if let exist = js["signature"] { presentKeys.insert("signature") if let val = exist as? String { self.signature = val } else { errors.append(FHIRJSONError(key: "signature", wants: String.self, has: type(of: exist))) } } else { errors.append(FHIRJSONError(key: "signature")) } if let exist = js["type"] { presentKeys.insert("type") if let val = exist as? FHIRJSON { self.type = Coding(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "type", wants: FHIRJSON.self, has: type(of: exist))) } } else { errors.append(FHIRJSONError(key: "type")) } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let party = self.party { json["party"] = party.asJSON(with: options) } if let signature = self.signature { json["signature"] = signature.asJSON(with: options) } if let type = self.type { json["type"] = type.asJSON(with: options) } return json } } /** * Contract Term List. * * One or more Contract Provisions, which may be related and conveyed as a group, and may contain nested groups. */ public class ContractTerm: BackboneElement { override public class var resourceType: String { get { return "ContractTerm" } } /// Contract Term Action. public var action: [CodeableConcept]? /// Contract Term Action Reason. public var actionReason: [CodeableConcept]? /// Contract Term Actor List. public var actor: [ContractTermActor]? /// Contract Term Effective Time. public var applies: Period? /// Nested Contract Term Group. public var group: [ContractTerm]? /// Contract Term identifier. public var identifier: Identifier? /// Contract Term Issue Date Time. public var issued: DateTime? /// Contract Term Subtype. public var subType: CodeableConcept? /// Subject of this Contract Term. public var subject: Reference? /// Human readable Contract term text. public var text: String? /// Contract Term Type. public var type: CodeableConcept? /// Contract Term Valued Item. public var valuedItem: [ContractTermValuedItem]? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["action"] { presentKeys.insert("action") if let val = exist as? [FHIRJSON] { self.action = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "action", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["actionReason"] { presentKeys.insert("actionReason") if let val = exist as? [FHIRJSON] { self.actionReason = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "actionReason", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["actor"] { presentKeys.insert("actor") if let val = exist as? [FHIRJSON] { self.actor = ContractTermActor.instantiate(fromArray: val, owner: self) as? [ContractTermActor] } else { errors.append(FHIRJSONError(key: "actor", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["applies"] { presentKeys.insert("applies") if let val = exist as? FHIRJSON { self.applies = Period(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "applies", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["group"] { presentKeys.insert("group") if let val = exist as? [FHIRJSON] { self.group = ContractTerm.instantiate(fromArray: val, owner: self) as? [ContractTerm] } else { errors.append(FHIRJSONError(key: "group", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } if let exist = js["identifier"] { presentKeys.insert("identifier") if let val = exist as? FHIRJSON { self.identifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "identifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["issued"] { presentKeys.insert("issued") if let val = exist as? String { self.issued = DateTime(string: val) } else { errors.append(FHIRJSONError(key: "issued", wants: String.self, has: type(of: exist))) } } if let exist = js["subType"] { presentKeys.insert("subType") if let val = exist as? FHIRJSON { self.subType = CodeableConcept(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "subType", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["subject"] { presentKeys.insert("subject") if let val = exist as? FHIRJSON { self.subject = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "subject", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["text"] { presentKeys.insert("text") if let val = exist as? String { self.text = val } else { errors.append(FHIRJSONError(key: "text", wants: String.self, has: type(of: exist))) } } if let exist = js["type"] { presentKeys.insert("type") if let val = exist as? FHIRJSON { self.type = CodeableConcept(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "type", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["valuedItem"] { presentKeys.insert("valuedItem") if let val = exist as? [FHIRJSON] { self.valuedItem = ContractTermValuedItem.instantiate(fromArray: val, owner: self) as? [ContractTermValuedItem] } else { errors.append(FHIRJSONError(key: "valuedItem", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let action = self.action { json["action"] = action.map() { $0.asJSON(with: options) } } if let actionReason = self.actionReason { json["actionReason"] = actionReason.map() { $0.asJSON(with: options) } } if let actor = self.actor { json["actor"] = actor.map() { $0.asJSON(with: options) } } if let applies = self.applies { json["applies"] = applies.asJSON(with: options) } if let group = self.group { json["group"] = group.map() { $0.asJSON(with: options) } } if let identifier = self.identifier { json["identifier"] = identifier.asJSON(with: options) } if let issued = self.issued { json["issued"] = issued.asJSON(with: options) } if let subType = self.subType { json["subType"] = subType.asJSON(with: options) } if let subject = self.subject { json["subject"] = subject.asJSON(with: options) } if let text = self.text { json["text"] = text.asJSON(with: options) } if let type = self.type { json["type"] = type.asJSON(with: options) } if let valuedItem = self.valuedItem { json["valuedItem"] = valuedItem.map() { $0.asJSON(with: options) } } return json } } /** * Contract Term Actor List. * * List of actors participating in this Contract Provision. */ public class ContractTermActor: BackboneElement { override public class var resourceType: String { get { return "ContractTermActor" } } /// Contract Term Actor. public var entity: Reference? /// Contract Term Actor Role. public var role: [CodeableConcept]? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } /** Convenience initializer, taking all required properties as arguments. */ public convenience init(entity: Reference) { self.init(json: nil) self.entity = entity } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["entity"] { presentKeys.insert("entity") if let val = exist as? FHIRJSON { self.entity = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entity", wants: FHIRJSON.self, has: type(of: exist))) } } else { errors.append(FHIRJSONError(key: "entity")) } if let exist = js["role"] { presentKeys.insert("role") if let val = exist as? [FHIRJSON] { self.role = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept] } else { errors.append(FHIRJSONError(key: "role", wants: Array<FHIRJSON>.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let entity = self.entity { json["entity"] = entity.asJSON(with: options) } if let role = self.role { json["role"] = role.map() { $0.asJSON(with: options) } } return json } } /** * Contract Term Valued Item. * * Contract Provision Valued Item List. */ public class ContractTermValuedItem: BackboneElement { override public class var resourceType: String { get { return "ContractTermValuedItem" } } /// Contract Term Valued Item Effective Tiem. public var effectiveTime: DateTime? /// Contract Term Valued Item Type. public var entityCodeableConcept: CodeableConcept? /// Contract Term Valued Item Type. public var entityReference: Reference? /// Contract Term Valued Item Price Scaling Factor. public var factor: NSDecimalNumber? /// Contract Term Valued Item Identifier. public var identifier: Identifier? /// Total Contract Term Valued Item Value. public var net: Quantity? /// Contract Term Valued Item Difficulty Scaling Factor. public var points: NSDecimalNumber? /// Contract Term Valued Item Count. public var quantity: Quantity? /// Contract Term Valued Item fee, charge, or cost. public var unitPrice: Quantity? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["effectiveTime"] { presentKeys.insert("effectiveTime") if let val = exist as? String { self.effectiveTime = DateTime(string: val) } else { errors.append(FHIRJSONError(key: "effectiveTime", wants: String.self, has: type(of: exist))) } } if let exist = js["entityCodeableConcept"] { presentKeys.insert("entityCodeableConcept") if let val = exist as? FHIRJSON { self.entityCodeableConcept = CodeableConcept(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entityCodeableConcept", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["entityReference"] { presentKeys.insert("entityReference") if let val = exist as? FHIRJSON { self.entityReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entityReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["factor"] { presentKeys.insert("factor") if let val = exist as? NSNumber { self.factor = NSDecimalNumber(json: val) } else { errors.append(FHIRJSONError(key: "factor", wants: NSNumber.self, has: type(of: exist))) } } if let exist = js["identifier"] { presentKeys.insert("identifier") if let val = exist as? FHIRJSON { self.identifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "identifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["net"] { presentKeys.insert("net") if let val = exist as? FHIRJSON { self.net = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "net", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["points"] { presentKeys.insert("points") if let val = exist as? NSNumber { self.points = NSDecimalNumber(json: val) } else { errors.append(FHIRJSONError(key: "points", wants: NSNumber.self, has: type(of: exist))) } } if let exist = js["quantity"] { presentKeys.insert("quantity") if let val = exist as? FHIRJSON { self.quantity = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "quantity", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["unitPrice"] { presentKeys.insert("unitPrice") if let val = exist as? FHIRJSON { self.unitPrice = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "unitPrice", wants: FHIRJSON.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let effectiveTime = self.effectiveTime { json["effectiveTime"] = effectiveTime.asJSON(with: options) } if let entityCodeableConcept = self.entityCodeableConcept { json["entityCodeableConcept"] = entityCodeableConcept.asJSON(with: options) } if let entityReference = self.entityReference { json["entityReference"] = entityReference.asJSON(with: options) } if let factor = self.factor { json["factor"] = factor.asJSON(with: options) } if let identifier = self.identifier { json["identifier"] = identifier.asJSON(with: options) } if let net = self.net { json["net"] = net.asJSON(with: options) } if let points = self.points { json["points"] = points.asJSON(with: options) } if let quantity = self.quantity { json["quantity"] = quantity.asJSON(with: options) } if let unitPrice = self.unitPrice { json["unitPrice"] = unitPrice.asJSON(with: options) } return json } } /** * Contract Valued Item. * * Contract Valued Item List. */ public class ContractValuedItem: BackboneElement { override public class var resourceType: String { get { return "ContractValuedItem" } } /// Contract Valued Item Effective Tiem. public var effectiveTime: DateTime? /// Contract Valued Item Type. public var entityCodeableConcept: CodeableConcept? /// Contract Valued Item Type. public var entityReference: Reference? /// Contract Valued Item Price Scaling Factor. public var factor: NSDecimalNumber? /// Contract Valued Item Identifier. public var identifier: Identifier? /// Total Contract Valued Item Value. public var net: Quantity? /// Contract Valued Item Difficulty Scaling Factor. public var points: NSDecimalNumber? /// Count of Contract Valued Items. public var quantity: Quantity? /// Contract Valued Item fee, charge, or cost. public var unitPrice: Quantity? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["effectiveTime"] { presentKeys.insert("effectiveTime") if let val = exist as? String { self.effectiveTime = DateTime(string: val) } else { errors.append(FHIRJSONError(key: "effectiveTime", wants: String.self, has: type(of: exist))) } } if let exist = js["entityCodeableConcept"] { presentKeys.insert("entityCodeableConcept") if let val = exist as? FHIRJSON { self.entityCodeableConcept = CodeableConcept(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entityCodeableConcept", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["entityReference"] { presentKeys.insert("entityReference") if let val = exist as? FHIRJSON { self.entityReference = Reference(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "entityReference", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["factor"] { presentKeys.insert("factor") if let val = exist as? NSNumber { self.factor = NSDecimalNumber(json: val) } else { errors.append(FHIRJSONError(key: "factor", wants: NSNumber.self, has: type(of: exist))) } } if let exist = js["identifier"] { presentKeys.insert("identifier") if let val = exist as? FHIRJSON { self.identifier = Identifier(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "identifier", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["net"] { presentKeys.insert("net") if let val = exist as? FHIRJSON { self.net = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "net", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["points"] { presentKeys.insert("points") if let val = exist as? NSNumber { self.points = NSDecimalNumber(json: val) } else { errors.append(FHIRJSONError(key: "points", wants: NSNumber.self, has: type(of: exist))) } } if let exist = js["quantity"] { presentKeys.insert("quantity") if let val = exist as? FHIRJSON { self.quantity = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "quantity", wants: FHIRJSON.self, has: type(of: exist))) } } if let exist = js["unitPrice"] { presentKeys.insert("unitPrice") if let val = exist as? FHIRJSON { self.unitPrice = Quantity(json: val, owner: self) } else { errors.append(FHIRJSONError(key: "unitPrice", wants: FHIRJSON.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let effectiveTime = self.effectiveTime { json["effectiveTime"] = effectiveTime.asJSON(with: options) } if let entityCodeableConcept = self.entityCodeableConcept { json["entityCodeableConcept"] = entityCodeableConcept.asJSON(with: options) } if let entityReference = self.entityReference { json["entityReference"] = entityReference.asJSON(with: options) } if let factor = self.factor { json["factor"] = factor.asJSON(with: options) } if let identifier = self.identifier { json["identifier"] = identifier.asJSON(with: options) } if let net = self.net { json["net"] = net.asJSON(with: options) } if let points = self.points { json["points"] = points.asJSON(with: options) } if let quantity = self.quantity { json["quantity"] = quantity.asJSON(with: options) } if let unitPrice = self.unitPrice { json["unitPrice"] = unitPrice.asJSON(with: options) } return json } }
30.42397
120
0.666929
9112bf873e2f869efe49ec6a028bcec4f8372542
2,249
// // CustomPickerViewController.swift // Pickers // // Created by arcui on 2016-10-02. // Copyright © 2016 Dyhoer. All rights reserved. // import UIKit class CustomPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{ private var images:[UIImage]! @IBOutlet weak var winLabel: UILabel! @IBOutlet weak var picker: UIPickerView! override func viewDidLoad() { super.viewDidLoad() images = [ UIImage(named: "seven")!, UIImage(named: "bar")!, UIImage(named: "crown")!, UIImage(named: "cherry")!, UIImage(named: "lemon")!, UIImage(named: "apple")! ] winLabel.text = " " arc4random_stir() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func spin(_ sender: AnyObject) { var win = false var numInRow = -1 var lastVal = -1 for i in 0..<5 { let newValue = Int(arc4random_uniform(UInt32(images.count))) if newValue == lastVal { numInRow += 1 } else { numInRow = 1 } lastVal = newValue picker.selectRow(newValue, inComponent: i, animated: true) picker.reloadComponent(i) win = numInRow >= 3 ? true : false } winLabel.text = win ? "WINNER!" : " " } // MARK:- // MARK: Picker Data Source Methods func numberOfComponents(in pickerView: UIPickerView) -> Int { return 5 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return images.count } // MARK:- // MARK: Picker Delegate Methods func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let image = images[row] let imageView = UIImageView(image: image) return imageView } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 64 } }
28.1125
132
0.580258
902c291eb20282a9c71dd6c631626625d2de2468
428
// // Project «Synopsis» // Created by Jeorge Taflanidi // import Foundation import SourceKittenFramework class ProtocolDescriptionParser: ExtensibleParser<ProtocolDescription> { override func isRawExtensibleDescription(_ element: [String : AnyObject]) -> Bool { guard let kind: String = element.kind else { return false} return SwiftDeclarationKind.`protocol`.rawValue == kind } }
21.4
87
0.705607
9bbc86440d33bbff4262bc369d01baa61236d4fb
1,378
import Foundation public struct ANSIParser: Sequence { private let string: String public init(string: String) { self.string = string } public func makeIterator() -> _ANSIParserIterator { return _ANSIParserIterator(string) } public struct _ANSIParserIterator: IteratorProtocol { let scanner: Scanner var state: Attributes init(_ string: String) { self.scanner = Scanner(string: string) self.scanner.charactersToBeSkipped = nil self.state = Attributes.pure } public mutating func next() -> (String, Attributes)? { guard !scanner.isAtEnd else { return nil } if let text = scanText() { return (text, state) } else { applyASCIICodes() return next() } } private func scanText() -> String? { var captured: NSString? = nil if scanner.scanUpTo("\\u001B[", into: &captured), let captured = captured { return captured as String } else { return nil } } private mutating func applyASCIICodes() { while scanner.scanString("\\u001B[", into: nil) { var code: Int = 0 while scanner.scanInt(&code) { state = state.apply(code: code) scanner.scanString(";", into: nil) } scanner.scanString("m", into: nil) } } } }
23.355932
81
0.58418
0e98229e0856154403ae8b10d1fc923215ed77ca
940
// // ModalPage.swift // Example // // Created by 晋先森 on 2019/6/15. // Copyright © 2019 晋先森. All rights reserved. // import SwiftUI struct ModalPage : View { @State var showModal = false // var modal: Modal { // return Modal(PickerPage(),onDismiss: { // print("View Dismiss !") // self.showModal = false // }) // } var body: some View { VStack { Button(action: { self.showModal = true }) { Text("Modal View") .bold() .font(.system(.largeTitle, design: .serif)) }//.presentation(showModal ? modal:nil) // .sheet(isPresented: $showModal, content: PickerPage()) } } } #if DEBUG struct ModalPage_Previews : PreviewProvider { static var previews: some View { ModalPage() } } #endif
20.434783
68
0.489362
33638b4b24768e779ee3ef758307223fe8d77646
1,586
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 CoreGraphics public extension UIEdgeInsets { var bma_horziontalInset: CGFloat { return self.left + self.right } var bma_verticalInset: CGFloat { return self.top + self.bottom } } extension UIEdgeInsets: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(self.top) hasher.combine(self.left) hasher.combine(self.bottom) hasher.combine(self.right) } }
34.478261
78
0.750315
ef21ac6d85528bdbe0e2215df315768cded1f2d3
13,243
// // NotifirePopAnimationController.swift // Notifire // // Created by David Bielik on 11/11/2018. // Copyright © 2018 David Bielik. All rights reserved. // import UIKit class NotifireAlertViewController: NotifirePoppableViewController { enum AlertStyle: Equatable { /// The alert style to use for alerts that show a successful user action. (shows a checkmark ✅) case success /// The alert style to use for alerts that show that something failed (shows a cross ❌) case fail var image: UIImage { return self == .success ? #imageLiteral(resourceName: "checkmark.circle") : #imageLiteral(resourceName: "xmark.circle") } var color: UIColor { return self == .success ? .compatibleGreen : .compatibleRed } } // MARK: - Properties var containerCenterYConstraint: NSLayoutConstraint! private static let verticalMargin: CGFloat = Size.standardMargin * 1.5 // MARK: Views let containerView: UIView = { let view = UIView() view.backgroundColor = .compatibleSecondarySystemGroupedBackground view.layer.cornerRadius = Theme.alertCornerRadius view.layer.shadowRadius = 6 view.layer.shadowOpacity = 0.4 view.layer.shadowOffset = CGSize(width: 0, height: 0) return view }() var viewToPop: UIView { return containerView } let titleLabel = UILabel(style: .alertTitle) let informationLabel = UILabel(style: .alertInformation) let actionViewsStackView: UIStackView = { let stack = UIStackView(arrangedSubviews: []) stack.axis = .vertical stack.distribution = .fillProportionally stack.alignment = .center stack.spacing = 0 return stack }() // MARK: Model /// The title of the alert var alertTitle: String? { didSet { updateLabels() } } /// The main text of the alert var alertText: String? { didSet { updateLabels() } } /// The style of the alert displayed (optional) let alertStyle: AlertStyle? var actionControls: [NotifireAlertAction: UIControl] = [:] var actions: [NotifireAlertAction] = [] // MARK: - Lifecycle init(alertTitle: String?, alertText: String?, alertStyle: AlertStyle? = nil) { self.alertTitle = alertTitle self.alertText = alertText self.alertStyle = alertStyle super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError() } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.black.withAlphaComponent(0.5) containerView.layoutMargins = UIEdgeInsets(top: Self.verticalMargin, left: Size.extendedMargin, bottom: Self.verticalMargin, right: Size.extendedMargin) modalTransitionStyle = .crossDissolve updateLabels() layout() setAlertStyleImageIfNeeded() actions.forEach { addToStackView(action: $0) } } // MARK: - Private private func updateLabels() { titleLabel.text = alertTitle informationLabel.text = alertText } func layout() { view.add(subview: containerView) containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true containerCenterYConstraint = containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor) containerCenterYConstraint.isActive = true let widthConstraint = containerView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.72) widthConstraint.priority = UILayoutPriority(999) widthConstraint.isActive = true let heightConstraint = containerView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor, multiplier: 0.5) heightConstraint.priority = UILayoutPriority(999) heightConstraint.isActive = true // Title containerView.add(subview: titleLabel) // lower the title priority because if the image is present it needs to be above the titleLabel let titleTopAnchor = titleLabel.topAnchor.constraint(equalTo: containerView.layoutMarginsGuide.topAnchor) titleTopAnchor.priority = .init(950) titleTopAnchor.isActive = true titleLabel.leadingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.leadingAnchor).isActive = true titleLabel.trailingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.trailingAnchor).isActive = true containerView.add(subview: informationLabel) informationLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: Size.textFieldSpacing * 0.5).isActive = true informationLabel.leadingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.leadingAnchor).isActive = true informationLabel.trailingAnchor.constraint(equalTo: containerView.layoutMarginsGuide.trailingAnchor).isActive = true containerView.add(subview: actionViewsStackView) actionViewsStackView.topAnchor.constraint(equalTo: informationLabel.bottomAnchor, constant: Self.verticalMargin).isActive = true actionViewsStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true actionViewsStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true actionViewsStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true } private func setAlertStyleImageIfNeeded() { guard let style = alertStyle else { return } let imageView = UIImageView(image: style.image.withRenderingMode(.alwaysTemplate)) imageView.contentMode = .scaleAspectFit imageView.tintColor = style.color containerView.add(subview: imageView) imageView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true imageView.topAnchor.constraint(equalTo: containerView.layoutMarginsGuide.topAnchor).isActive = true imageView.bottomAnchor.constraint(equalTo: titleLabel.topAnchor, constant: -Size.extendedMargin).isActive = true imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true imageView.heightAnchor.constraint(equalToConstant: Size.Image.alertSuccessFailImage).isActive = true imageView.setContentCompressionResistancePriority(.init(1000), for: .vertical) } private func addToStackView(action: NotifireAlertAction) { guard actionViewsStackView.superview == containerView else { return } let newActionControl = ActionButton(type: .system) newActionControl.titleLabel?.set(style: .alertAction) newActionControl.setTitle(action.title, for: .normal) newActionControl.onProperTap = { _ in action.handler?(action) } if case .neutral = action.style { newActionControl.tintColor = .compatibleLabel } if case .negative = action.style { newActionControl.tintColor = .compatibleRed } let separatorView = HairlineView() actionViewsStackView.addArrangedSubview(separatorView) separatorView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true separatorView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true actionViewsStackView.addArrangedSubview(newActionControl) newActionControl.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true newActionControl.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true newActionControl.heightAnchor.constraint(equalToConstant: Size.componentHeight).isActive = true actionControls[action] = newActionControl } // MARK: - Public public func add(action: NotifireAlertAction) { actions.append(action) addToStackView(action: action) } } class NotifireAlertAction: Hashable { static func == (lhs: NotifireAlertAction, rhs: NotifireAlertAction) -> Bool { return lhs.title == rhs.title && lhs.style == rhs.style } func hash(into hasher: inout Hasher) { hasher.combine(title) hasher.combine(style) } typealias ActionHandler = ((NotifireAlertAction) -> Void)? enum Style: Hashable { case negative case positive case neutral } let title: String let style: Style let handler: ActionHandler init(title: String, style: Style, handler: ActionHandler = nil) { self.title = title self.style = style self.handler = handler } } class NotifireInputAlertViewController: NotifireAlertViewController, KeyboardObserving { // MARK: - Properties let viewModel: NotifireAlertViewModel // MARK: Views var validatableInput: ValidatableTextInput? private var validatingAction: NotifireAlertAction? // MARK: - Initialization init(alertTitle: String?, alertText: String?, viewModel: NotifireAlertViewModel) { self.viewModel = viewModel super.init(alertTitle: alertTitle, alertText: alertText) } required init?(coder aDecoder: NSCoder) { fatalError() } deinit { stopObservingNotifications() } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() addKeyboardDismissOnTap(to: view) startObservingNotifications() setupValidatingAction() keyboardObserverHandler.onKeyboardNotificationCallback = { [weak self] expanding, notification in if expanding { guard let keyboardHeight = self?.keyboardObserverHandler.keyboardHeight(from: notification) else { return } self?.containerCenterYConstraint.constant = -0.5*keyboardHeight } else { self?.containerCenterYConstraint.constant = 0 } } } override func layout() { super.layout() guard let validatableInput = self.validatableInput else { return } actionViewsStackView.insertArrangedSubview(validatableInput, at: 0) validatableInput.widthAnchor.constraint(equalTo: titleLabel.widthAnchor).isActive = true validatableInput.heightAnchor.constraint(equalToConstant: Size.componentHeight).isActive = true actionViewsStackView.setCustomSpacing(Size.extendedMargin, after: validatableInput) } // MARK: - Private private func setupValidatingAction() { if let validatingAction = self.validatingAction, let validatableInput = self.validatableInput { let controlToEnableAfterValidation = actionControls[validatingAction] controlToEnableAfterValidation?.isEnabled = validatableInput.isValid viewModel.createComponentValidator(with: [validatableInput]) viewModel.afterValidation = { valid in controlToEnableAfterValidation?.isEnabled = valid } } } // MARK: - Public public func createValidatableInput(title: String, secure: Bool, rules: [ComponentRule], validatingAction: NotifireAlertAction) { guard self.validatableInput == nil else { return } let textField = BorderedTextField() textField.setPlaceholder(text: title) textField.isSecureTextEntry = secure let validatableInput = ValidatableTextInput(textField: textField) validatableInput.validatingViewModelBinder = ValidatingViewModelBinder(viewModel: viewModel, for: \.textFieldText) validatableInput.rules = rules validatableInput.showsValidState = false self.validatableInput = validatableInput self.validatingAction = validatingAction } // MARK: - KeyboardObserving var keyboardObserverHandler = KeyboardObserverHandler() } final class NotifireAlertViewModel: InputValidatingViewModel { var textFieldText: String = "" } class NotifirePopAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var animator: UIViewPropertyAnimator? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.48 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to) as? NotifirePoppableViewController else { return } let containerView = transitionContext.containerView let viewToPop = toVC.viewToPop toVC.view.alpha = 0 viewToPop.transform = CGAffineTransform(scaleX: 1.14, y: 1.14) containerView.addSubview(toVC.view) containerView.bringSubviewToFront(toVC.view) let duration = transitionDuration(using: transitionContext) let popAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 0.65) { viewToPop.transform = .identity toVC.view.alpha = 1 } popAnimator.addCompletion { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } popAnimator.isUserInteractionEnabled = true animator = popAnimator popAnimator.startAnimation() } }
41.127329
160
0.705278
fee3f2cb1ecf329af2b8696779b03c4e58db3e76
227
// // ScreeningScreeningModuleInput.swift // Gleam // // Created by Каратаев Алексей on 09/11/2018. // Copyright © 2018 Apptolab. All rights reserved. // import Foundation @objc protocol ScreeningModuleInput: class { }
16.214286
51
0.722467
c139566bcab69e14c7bacb9db8e93c8d994d7781
1,732
// SPDX-License-Identifier: MIT // Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. import UIKit class TunnelEditKeyValueCell: KeyValueCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) keyLabel.textAlignment = .right valueTextField.textAlignment = .left let widthRatioConstraint = NSLayoutConstraint(item: keyLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 0.4, constant: 0) // In case the key doesn't fit into 0.4 * width, // set a CR priority > the 0.4-constraint's priority. widthRatioConstraint.priority = .defaultHigh + 1 widthRatioConstraint.isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TunnelEditEditableKeyValueCell: TunnelEditKeyValueCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) copyableGesture = false if #available(iOS 13.0, *) { valueTextField.textColor = .label } else { valueTextField.textColor = .black } valueTextField.isEnabled = true valueLabelScrollView.isScrollEnabled = false valueTextField.widthAnchor.constraint(equalTo: valueLabelScrollView.widthAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() copyableGesture = false } }
32.679245
170
0.683603
dddf0fed79ff5731587bfddcffa64a081152e048
4,335
// // InfoViewController.swift // TVVLCPlayer // // Created by Jérémy Marchand on 31/12/2018. // Copyright © 2018 Jérémy Marchand. All rights reserved. // import UIKit import TVVLCKit class InfoViewController: UIViewController { var player: VLCMediaPlayer! @IBOutlet weak var mainStackView: UIStackView! @IBOutlet weak var rightStackView: UIStackView! @IBOutlet weak var artworkImageView: UIImageView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var captionLabel: UILabel! @IBOutlet weak var qualityImageView: UIImageView! @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var artworkWidthConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() configure() // TODO: Find a better way to handle variable height of the info panel var height = mainStackView.frame.height if artworkImageView.isHidden { height = captionLabel.bounds.height + titleLabel.bounds.height + 40 if !textView.isHidden { height += textView.contentSize.height } } else { height = 240 } preferredContentSize = CGSize(width: 1920, height: height) } func configure() { configureTitle() configureCaption() configureArtwork() configureDescription() } func configureArtwork() { let mediaDict = player.media?.metaDictionary if let image = mediaDict?[VLCMetaInformationArtwork] as? UIImage { artworkImageView.image = image artworkImageView.isHidden = false artworkWidthConstraint.constant = 200 / image.size.height * image.size.width } else { artworkImageView.isHidden = true } } func configureTitle() { let mediaDict = player.media?.metaDictionary if let title = mediaDict?[VLCMetaInformationTitle] as? String { titleLabel.text = title } else { titleLabel.text = player.media?.url.absoluteString } } func configureCaption() { let media = player.media var caption: String = "" if let time = media?.length.string { caption.append(time) } let bundle = Bundle(for: InfoViewController.self) captionLabel.text = caption let videoSize: CGSize if let width = media?.metaDictionary[VLCMediaTracksInformationVideoWidth] as? NSNumber, let height = media?.metaDictionary[VLCMediaTracksInformationVideoWidth] as? NSNumber { videoSize = CGSize(width: width.doubleValue, height: height.doubleValue) } else { videoSize = player.videoSize } if videoSize >= CGSize(width: 3840, height: 2160) { qualityImageView.image = UIImage(named: "4k", in: bundle, compatibleWith: nil) } else if player.videoSize >= CGSize(width: 1280, height: 720) { qualityImageView.image = UIImage(named: "hd", in: bundle, compatibleWith: nil) } else { qualityImageView.image = nil } } func configureDescription() { let mediaDict = player.media.metaDictionary let texts = [VLCMetaInformationDescription, VLCMetaInformationCopyright].compactMap { mediaDict[$0] as? String } textView.text = texts.joined(separator: "\n") textView.textContainerInset = UIEdgeInsets.zero textView.textContainer.lineFragmentPadding = 0 textView.isHidden = texts.isEmpty } } private func >= (lhs: CGSize, rhs: CGSize) -> Bool { return lhs.height >= rhs.height && lhs.width >= rhs.width } private extension VLCTime { var string: String? { guard let rawDuration = value?.doubleValue else { return nil } let duration = rawDuration / 1000 let formatter = DateComponentsFormatter() formatter.zeroFormattingBehavior = .pad formatter.unitsStyle = .abbreviated if duration >= 3600 { formatter.allowedUnits = [.hour, .minute, .second] } else { formatter.allowedUnits = [.minute, .second] } return formatter.string(from: duration) ?? nil } }
33.346154
121
0.631603
ac6bc6e2442c38ffaa942272ad442ff024e9faba
699
// // Video.swift // BottomTabBar // // Created by UDLAP on 1/16/18. // Copyright © 2018 151211. All rights reserved. // import Foundation class Video { private var titulo:String private var descripcion:String private var urlString:String private var url:URL init(_ unTitulo:String,_ unaDescripcion:String,_ unaURL:String) { titulo = unTitulo descripcion = unaDescripcion urlString = unaURL url = URL(string: urlString)! } func getTitulo()->String{ return titulo } func getDescripcion()->String{ return descripcion } func getURLsString() -> String{ return urlString } }
19.971429
69
0.619456
690623c95ce6b7482b8953c6aad49426f9bfcc60
15,517
// // TempiBeatDetectorValidation.swift // TempiBeatDetection // // Created by John Scalo on 5/1/16. // Copyright © 2016 John Scalo. See accompanying License.txt for terms. import Foundation import AVFoundation extension TempiBeatDetector { func validate() { // self.validateStudioSet1() self.validateHomeSet1() // self.validateThreesSet1() // self.validateUtilitySet1() } private func projectURL() -> NSURL { let projectPath = "/Users/jscalo/Developer/Tempi/com.github/TempiBeatDetection" return NSURL.fileURLWithPath(projectPath) } private func validationSetup() { if self.savePlotData { let projectURL: NSURL = self.projectURL() var plotDataURL = projectURL.URLByAppendingPathComponent("Peak detection plots") plotDataURL = plotDataURL.URLByAppendingPathComponent("\(self.currentTestName)-plotData.txt") var plotMarkersURL = projectURL.URLByAppendingPathComponent("Peak detection plots") plotMarkersURL = plotMarkersURL.URLByAppendingPathComponent("\(self.currentTestName)-plotMarkers.txt") do { try NSFileManager.defaultManager().removeItemAtURL(plotDataURL) try NSFileManager.defaultManager().removeItemAtURL(plotMarkersURL) } catch _ { /* normal if file not yet created */ } self.plotFFTDataFile = fopen(plotDataURL.fileSystemRepresentation, "w") self.plotMarkersFile = fopen(plotMarkersURL.fileSystemRepresentation, "w") } self.testTotal = 0 self.testCorrect = 0 } private func validationFinish() { let result = 100.0 * Float(self.testCorrect) / Float(self.testTotal) print(String(format:"[%@] accuracy: %.01f%%\n", self.currentTestName, result)); self.testSetResults.append(result) } private func testAudio(path: String, label: String, actualTempo: Float, startTime: Double = 0.0, endTime: Double = 0.0, minTempo: Float = 40.0, maxTempo: Float = 240.0, variance: Float = 2.0) { let projectURL: NSURL = self.projectURL() let songURL = projectURL.URLByAppendingPathComponent("Test Media/\(path)") let avAsset: AVURLAsset = AVURLAsset(URL: songURL) print("Start testing: \(path)") self.currentTestName = label; self.startTime = startTime self.endTime = endTime self.minTempo = minTempo self.maxTempo = maxTempo self.setupCommon() self.validationSetup() self.allowedTempoVariance = variance let assetReader: AVAssetReader do { assetReader = try AVAssetReader(asset: avAsset) } catch let e as NSError { print("*** AVAssetReader failed with \(e)") return } let settings: [String : AnyObject] = [ AVFormatIDKey : Int(kAudioFormatLinearPCM), AVSampleRateKey : self.sampleRate, AVLinearPCMBitDepthKey : 32, AVLinearPCMIsFloatKey : true, AVNumberOfChannelsKey : 1 ] let output: AVAssetReaderAudioMixOutput = AVAssetReaderAudioMixOutput.init(audioTracks: avAsset.tracks, audioSettings: settings) assetReader.addOutput(output) if !assetReader.startReading() { print("assetReader.startReading() failed") return } var samplePtr: Int = 0 self.testActualTempo = actualTempo var queuedSamples: [Float] = [Float]() repeat { var status: OSStatus = 0 guard let nextBuffer = output.copyNextSampleBuffer() else { break } let bufferSampleCnt = CMSampleBufferGetNumSamples(nextBuffer) var bufferList = AudioBufferList( mNumberBuffers: 1, mBuffers: AudioBuffer( mNumberChannels: 1, mDataByteSize: 4, mData: nil)) var blockBuffer: CMBlockBuffer? status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(nextBuffer, nil, &bufferList, sizeof(AudioBufferList), nil, nil, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &blockBuffer) if status != 0 { print("*** CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer failed with error \(status)") break } // Move samples from mData into our native [Float] format. // (There's probably an better way to do this using UnsafeBufferPointer but I couldn't make it work.) for i in 0..<bufferSampleCnt { let ptr = UnsafePointer<Float>(bufferList.mBuffers.mData) let newPtr = ptr + i let sample = unsafeBitCast(newPtr.memory, Float.self) queuedSamples.append(sample) } // We have a big buffer of audio (whatever CoreAudio decided to give us). // Now iterate over the buffer, sending a chunkSize's (e.g. 4096 samples) worth of data to the analyzer and then // shifting by hopSize (e.g. 132 samples) after each iteration. If there's not enough data in the buffer (bufferSampleCnt < chunkSize), // then add the data to the queue and get the next buffer. while queuedSamples.count >= self.chunkSize { let timeStamp: Double = Double(samplePtr) / Double(self.sampleRate) if self.endTime > 0.01 { if timeStamp < self.startTime || timeStamp > self.endTime { queuedSamples.removeFirst(self.hopSize) samplePtr += self.hopSize continue } } let subArray: [Float] = Array(queuedSamples[0..<self.chunkSize]) self.analyzeAudioChunk(timeStamp: timeStamp, samples: subArray) samplePtr += self.hopSize queuedSamples.removeFirst(self.hopSize) } } while true print("Finished testing: \(path)") if self.savePlotData { fclose(self.plotFFTDataFile) fclose(self.plotMarkersFile) } self.validationFinish() } private func testSetSetupForSetName(setName: String) { print("Starting validation set \(setName)"); self.currentTestSetName = setName self.testSetResults = [Float]() } private func testSetFinish() { let mean: Float = tempi_mean(self.testSetResults) print(String(format:"Validation set [%@] accuracy: %.01f%%\n", self.currentTestSetName, mean)); } private func oneOffTest() { self.testSetSetupForSetName("oneOff") self.testAudio("Studio/Learn To Fly.mp3", label: "learn-to-fly", actualTempo: 136, startTime: 0, endTime: 15, minTempo: 80, maxTempo: 160, variance: 2) self.testSetFinish() } private func validateStudioSet1 () { self.testSetSetupForSetName("studioSet1") self.testAudio("Studio/Skinny Sweaty Man.mp3", label: "skinny-sweaty-man", actualTempo: 141, startTime: 0, endTime: 15, minTempo: 80, maxTempo: 160, variance: 3) self.testAudio("Studio/Satisfaction.mp3", label: "satisfaction", actualTempo: 137, startTime: 0, endTime: 20, minTempo: 80, maxTempo: 160, variance: 2.5) self.testAudio("Studio/Louie, Louie.mp3", label: "louie-louie", actualTempo: 120, startTime: 0, endTime: 15, minTempo: 60, maxTempo: 120, variance: 3) self.testAudio("Studio/Learn To Fly.mp3", label: "learn-to-fly", actualTempo: 136, startTime: 0, endTime: 15, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Studio/HBFS.mp3", label: "harder-better-faster-stronger", actualTempo: 123, startTime: 0, endTime: 15, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Studio/Waving Flag.mp3", label: "waving-flag", actualTempo: 76, startTime: 0, endTime: 15, minTempo: 60, maxTempo: 120, variance: 2) self.testAudio("Studio/Back in Black.mp3", label: "back-in-black", actualTempo: 90, startTime: 0, endTime: 15, minTempo: 60, maxTempo: 120, variance: 2) self.testSetFinish() } private func validateHomeSet1 () { self.testSetSetupForSetName("homeSet1") self.testAudio("Home/AG-Blackbird-1.mp3", label: "ag-blackbird1", actualTempo: 94, minTempo: 60, maxTempo: 120, variance: 3) self.testAudio("Home/AG-Blackbird-2.mp3", label: "ag-blackbird2", actualTempo: 95, minTempo: 60, maxTempo: 120, variance: 3) self.testAudio("Home/AG-Sunset Road-116-1.mp3", label: "ag-sunsetroad1", actualTempo: 116, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Home/AG-Sunset Road-116-2.mp3", label: "ag-sunsetroad2", actualTempo: 116, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Home/Possum-1.mp3", label: "possum1", actualTempo: 79, minTempo: 60, maxTempo: 120, variance: 2) self.testAudio("Home/Possum-2.mp3", label: "possum2", actualTempo: 81, minTempo: 60, maxTempo: 120, variance: 3) self.testAudio("Home/Hard Top-1.mp3", label: "hard-top1", actualTempo: 133, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Home/Hard Top-2.mp3", label: "hard-top2", actualTempo: 146, minTempo: 80, maxTempo: 160, variance: 2) self.testAudio("Home/Definitely Delicate-1.mp3", label: "delicate1", actualTempo: 75, minTempo: 60, maxTempo: 120, variance: 3) self.testAudio("Home/Wildwood Flower-1.mp3", label: "wildwood1", actualTempo: 95, minTempo: 80, maxTempo: 160, variance: 3) self.testAudio("Home/Wildwood Flower-2.mp3", label: "wildwood2", actualTempo: 148, minTempo: 80, maxTempo: 160, variance: 3) self.testSetFinish() } private func validateThreesSet1 () { self.testSetSetupForSetName("threesSet1") self.testAudio("Threes/Norwegian Wood.mp3", label: "norwegian-wood", actualTempo: 180, startTime: 0, endTime: 0, minTempo: 100, maxTempo: 200, variance: 3) self.testAudio("Threes/Drive In Drive Out.mp3", label: "drive-in-drive-out", actualTempo: 81, startTime: 0, endTime: 0, minTempo: 60, maxTempo: 120, variance: 2) self.testAudio("Threes/Oh How We Danced.mp3", label: "oh-how-we-danced", actualTempo: 180, startTime: 0, endTime: 20, minTempo: 100, maxTempo: 200, variance: 2) self.testAudio("Threes/Texas Flood.mp3", label: "texas-flood", actualTempo: 60, startTime: 0, endTime: 20, minTempo: 40, maxTempo: 120, variance: 2) self.testAudio("Threes/Brahms Lullaby.mp3", label: "brahms-lullaby", actualTempo: 70, startTime: 0, endTime: 15, minTempo: 60, maxTempo: 120, variance: 2) self.testSetFinish() } private func validateUtilitySet1 () { self.testSetSetupForSetName("utilitySet1") self.testAudio("Utility/metronome-88.mp3", label: "metronome-88", actualTempo: 88, startTime: 0, endTime: 10, minTempo: 40, maxTempo: 240, variance: 1) self.testAudio("Utility/metronome-126.mp3", label: "metronome-126", actualTempo: 126, startTime: 0, endTime: 15, minTempo: 40, maxTempo: 240, variance: 1) self.testAudio("Utility/1sTones.wav", label: "1s-tones", actualTempo: 60, startTime: 0, endTime: 10, minTempo: 40, maxTempo: 240, variance: 1) self.testSetFinish() } }
38.219212
147
0.472321
f53f9ff5075f41a54e21c6f51de1beea57560e52
2,093
// // Created by ApodiniMigrator on 15.08.20 // Copyright © 2020 TUM LS1. All rights reserved. // import Foundation // MARK: - Model public struct User: Codable { // MARK: - CodingKeys private enum CodingKeys: String, CodingKey { case age case friends case githubProfile case id case isStudent case name } // MARK: - Properties public var age: UInt? public var friends: [UUID] public var githubProfile: URL public var id: UUID public var isStudent: String public var name: String // MARK: - Initializer public init( age: UInt?, friends: [UUID], githubProfile: URL, id: UUID, isStudent: String, name: String ) { self.age = age self.friends = friends self.githubProfile = githubProfile self.id = id self.isStudent = isStudent self.name = name } // MARK: - Encodable public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(age, forKey: .age) try container.encode(friends, forKey: .friends) try container.encode(githubProfile, forKey: .githubProfile) try container.encode(id, forKey: .id) try container.encode(try Bool.from(isStudent, script: 1), forKey: .isStudent) try container.encode(name, forKey: .name) } // MARK: - Decodable public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) age = try container.decodeIfPresent(UInt.self, forKey: .age) friends = try container.decode([UUID].self, forKey: .friends) githubProfile = try container.decode(URL.self, forKey: .githubProfile) id = try container.decode(UUID.self, forKey: .id) isStudent = try String.from(try container.decode(Bool.self, forKey: .isStudent), script: 2) name = try container.decode(String.self, forKey: .name) } }
30.333333
99
0.618729
9c2d5959cd7493cba724bb8cd297bf5c35e3d9da
1,459
// // MessageThreadInfo.swift // tl2swift // // Generated automatically. Any changes will be lost! // Based on TDLib 1.8.0-fa8feefe // https://github.com/tdlib/td/tree/fa8feefe // import Foundation /// Contains information about a message thread public struct MessageThreadInfo: Codable, Equatable { /// Identifier of the chat to which the message thread belongs public let chatId: Int64 /// A draft of a message in the message thread; may be null public let draftMessage: DraftMessage? /// Message thread identifier, unique within the chat public let messageThreadId: Int64 /// The messages from which the thread starts. The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id) public let messages: [Message] /// Information about the message thread public let replyInfo: MessageReplyInfo /// Approximate number of unread messages in the message thread public let unreadMessageCount: Int public init( chatId: Int64, draftMessage: DraftMessage?, messageThreadId: Int64, messages: [Message], replyInfo: MessageReplyInfo, unreadMessageCount: Int ) { self.chatId = chatId self.draftMessage = draftMessage self.messageThreadId = messageThreadId self.messages = messages self.replyInfo = replyInfo self.unreadMessageCount = unreadMessageCount } }
28.057692
151
0.696367
8a4d8c474d21da1c94c7b2dadc9d0f725dbbdfda
1,439
// // DateTimeUtil.swift // // // import Foundation struct DateTimeUtil { static func dateFormatter(type: DateValueType, tzid: String?) -> DateFormatter { let formatter = DateFormatter() formatter.timeZone = { if let tzid = tzid { return .init(identifier: tzid) } else { return .init(secondsFromGMT: 0) } }() formatter.dateFormat = { switch type { case .date: return Constant.Format.dateOnly case .dateTime, .period: return tzid == nil ? Constant.Format.utc : Constant.Format.dt } }() return formatter } static func params(type: DateValueType, tzid: String?) -> [ICalParameter] { let valueParam: ICalParameter? = { switch type { case .date: return .init(key: "VALUE", values: ["DATE"]) case .dateTime: return nil case .period: return .init(key: "VALUE", values: ["PERIOD"]) } }() let tzidParam: ICalParameter? = { if let tzid = tzid { return .init(key: "TZID", values: [tzid]) } else { return nil } }() return [valueParam, tzidParam].compactMap { $0 } } }
25.696429
84
0.464906
e8e629ce039bbfafca472339b8cf69d03cf98640
6,356
// // ViewController.swift // Tipping // // Created by Viet Dang Ba on 2/7/17. // Copyright © 2017 Viet Dang. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtBill: UITextField! @IBOutlet weak var lblTip: UILabel! @IBOutlet weak var lblTotal: UILabel! @IBOutlet weak var blankView: UIView! @IBOutlet weak var segTipPercent: UISegmentedControl! var themes = ["Light", "Dark"] var pickViewColour = UIColor.black var lowTip = 10 var medTip = 18 var highTip = 25 override func viewDidLoad() { super.viewDidLoad() txtBill.becomeFirstResponder() txtBill.delegate = self // 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) UIView.animate(withDuration: 0.4, animations: { self.view.alpha = 1 }) let defaults = UserDefaults.standard lowTip = defaults.integer(forKey: "LowTip") print("Will apprear ", lowTip) if(lowTip == 0){ lowTip = 10 defaults.set(lowTip, forKey: "LowTip") } segTipPercent.setTitle(String(lowTip) + "%", forSegmentAt: 0) medTip = defaults.integer(forKey: "MediumTip") if(medTip == 0){ medTip = 18 defaults.set(medTip, forKey: "MediumTip") } segTipPercent.setTitle(String(medTip) + "%", forSegmentAt: 1) highTip = defaults.integer(forKey: "HighTip") if(highTip == 0){ highTip = 25 defaults.set(highTip, forKey: "HighTip") } defaults.synchronize() segTipPercent.setTitle(String(highTip) + "%", forSegmentAt: 2) calcTotal(nil) changeColor() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.animate(withDuration: 0.4, animations: { self.view.alpha = 0.5 }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } @IBAction func onViewTap(_ sender: Any) { view.endEditing(true); } @IBAction func calcTotal(_ sender: AnyObject?) { let defaults = UserDefaults.standard UIView.animate(withDuration: 1, animations: { self.blankView.alpha = 0 }) UIView.animate(withDuration: 0.5, animations: { self.blankView.alpha = 1 }) var tipPercentage = 0.0 if(segTipPercent.selectedSegmentIndex == 0){ tipPercentage = defaults.double(forKey: "LowTip") / 100 } else if (segTipPercent.selectedSegmentIndex == 1){ tipPercentage = defaults.double(forKey: "MediumTip") / 100 } else { tipPercentage = defaults.double(forKey: "HighTip") / 100 } let bill = Double(txtBill.text!) ?? 0 let tip = bill * (tipPercentage) let total = tip + bill let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = NSLocale.current let localizedTip = formatter.string(from: NSNumber(value: tip)) let localizedTotal = formatter.string(from: NSNumber(value: total)) lblTip.text = localizedTip lblTotal.text = localizedTotal } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if(string == "." && textField.text?.range(of:".") != nil){ return false } if(textField.text == "0"){ if(string != "."){ textField.text = ""; } } guard let text = textField.text else { return true } let newLength = text.characters.count + string.characters.count - range.length return newLength <= 9 // Bool } func changeColor() { let defaults = UserDefaults.standard let themeSetting = defaults.integer(forKey: "theme") if (themeSetting == 1) { self.view.backgroundColor = UIColor.black; //Get all UIViews in self.view.subViews for subview in self.view.subviews as [UIView] { //Check if the view is of UILabel class if let labelView = subview as? UILabel { //Set the color to label labelView.textColor = UIColor.blue; } if let textView = subview as? UITextField{ textView.textColor = UIColor.blue } if let pickerView = subview as? UIPickerView{ pickerView.backgroundColor = UIColor.black } } pickViewColour = UIColor.red } else { self.view.backgroundColor = UIColor.white; //Get all UIViews in self.view.subViews for subview in self.view.subviews as [UIView] { //Check if the view is of UILabel class if let labelView = subview as? UILabel { //Set the color to label labelView.textColor = UIColor.black; } if let textView = subview as? UITextField{ textView.textColor = UIColor.black; } if let pickerView = subview as? UIPickerView{ pickerView.backgroundColor = UIColor.white } } pickViewColour = UIColor.black } } }
29.981132
129
0.536029
33defa632eb13c65dc176d0575315fc0444e5290
2,086
// // AppDelegate.swift // SampleNoCocoaPods // // Created by Jack Rosen on 8/26/19. // Copyright © 2019 Jack Rosen. 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. 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:. } }
44.382979
279
0.78907
1dcbf46af1cdd193881503b7c69721f99e870b79
3,637
// Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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 ADAL class ViewController: UIViewController { @IBOutlet weak var statusTextField: UITextView? 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. } func updateStatusField(_ text: String) { guard Thread.isMainThread else { DispatchQueue.main.async { self.updateStatusField(text) } return } statusTextField?.text = text; } @IBAction func acquireToken(_ sender:UIButton) { guard let authContext = ADAuthenticationContext(authority: "https://login.microsoftonline.com/common", error: nil) else { print("Failed to create auth context") return } authContext.acquireToken(withResource: "https://graph.windows.net", clientId: "b92e0ba5-f86e-4411-8e18-6b5f928d968a", redirectUri: URL(string: "urn:ietf:wg:oauth:2.0:oob")!) { [weak self] (result) in guard let weakself = self else { return } guard result.status == AD_SUCCEEDED else { if result.error!.domain == ADAuthenticationErrorDomain && result.error!.code == ADErrorCode.ERROR_UNEXPECTED.rawValue { weakself.updateStatusField("Unexpected internal error occured") } else { weakself.updateStatusField(result.error!.description) } return } var expiresOnString = "(nil)" guard let tokenCacheItem = result.tokenCacheItem else { weakself.updateStatusField("No token cache item returned") return } expiresOnString = String(describing: tokenCacheItem.expiresOn) let status = String(format: "Access token: %@\nexpiration:%@", result.accessToken!, expiresOnString) weakself.updateStatusField(status) } } }
36.37
129
0.608194
cc94b339d408752d822c4459537037f5cb6f277e
2,119
// // ScaleViewController.swift // iOSWork // // Created by Stan Hu on 2022/2/10. // import UIKit import SnapKit class ScaleViewController: UIViewController { let lblScale = UILabel() override func viewDidLoad() { super.viewDidLoad() title = "视图缩放" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "生成图片", style: .plain, target: self, action: #selector(createImg)) view.addSubview(imgScale) imgScale.clipsToBounds = true imgScale.snp.makeConstraints { make in make.centerX.equalTo(view) make.centerY.equalTo(view) make.width.equalTo(ScreenWidth) } view.addSubview(btnStep) btnStep.snp.makeConstraints { make in make.centerX.equalTo(view) make.top.equalTo(100) } lblScale.setFont(font: 20).color(color: UIColor.cyan).addTo(view: view).snp.makeConstraints { make in make.top.equalTo(btnStep.snp.bottom) make.centerX.equalTo(btnStep) } // Do any additional setup after loading the view. } @objc func stepChange(sender:UIStepper){ print(sender.value) lblScale.text = "\(sender.value)倍" imgScale.transform = CGAffineTransform(scaleX: sender.value, y: sender.value) } @objc func createImg(){ let img = imgScale.asImage() print(img.size) // img.saveToAlbum() print(img.memorySize) UIPasteboard.general.image = img } lazy var btnStep: UIStepper = { let v = UIStepper() v.stepValue = 0.1 v.value = 1 v.maximumValue = 2 v.minimumValue = 0.1 v.addTarget(self, action: #selector(stepChange(sender:)), for: .valueChanged) v.backgroundColor = UIColor.white return v }() lazy var imgScale: UIImageView = { let v = UIImageView(image: UIImage(named: "3")) v.contentMode = .scaleAspectFill return v }() }
24.929412
133
0.572912
d709cd9c335f6ac15485621024004020bd0455d5
2,024
// // Int64+TaskInfo.swift // Tiercel // // Created by Daniels on 2019/1/22. // Copyright © 2019 Daniels. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Int64: TiercelCompatible {} extension TiercelWrapper where Base == Int64 { /// 返回下载速度的字符串,如:1MB/s /// /// - Returns: public func convertSpeedToString() -> String { let size = convertBytesToString() return [size, "s"].joined(separator: "/") } /// 返回 00:00格式的字符串 /// /// - Returns: public func convertTimeToString() -> String { let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional return formatter.string(from: TimeInterval(base)) ?? "" } /// 返回字节大小的字符串 /// /// - Returns: public func convertBytesToString() -> String { return ByteCountFormatter.string(fromByteCount: base, countStyle: .file) } }
33.733333
81
0.682312
87c26ea09d346d3ea87d77a4a7fbdc5d0d3a97fb
1,086
// // FrontViewController.swift // CALayer // // Created by Deepak Kumar on 07/01/19. // Copyright © 2019 deepak. All rights reserved. // import UIKit class FrontViewController: UIViewController { // MARK: - Properties @IBOutlet weak var newsImageView: UIImageView! @IBOutlet weak var newsHeadingLabel: UILabel! @IBOutlet weak var newsTextView: UITextView! @IBOutlet weak var footerCaptionLabel: UILabel! @IBOutlet weak var overlayView: UIView! @IBOutlet weak var topViewTopConstraint: NSLayoutConstraint! // MARK: - Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initialSetup() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - Private Methods private func initialSetup() { } // MARK: - IBAction Methods @IBAction func moreButtonTapped(_ sender: UIButton) { } @IBAction func reloadButtonTapped(_ sender: UIButton) { print("Reload") } }
24.133333
64
0.677716
e2033ae04f2cd8d3e55e90b870d88ee1f57c5b16
422
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "KYAActivationDurations", platforms: [ .macOS(.v10_12) ], products: [ .library(name: "KYAActivationDurations", targets: ["KYAActivationDurations"]), ], dependencies: [ ], targets: [ .target(name: "KYAActivationDurations", dependencies: []), ], cxxLanguageStandard: .cxx17 )
21.1
86
0.623223
d75c59217ea03edc0463c78708ece5d08b2c65bf
13,459
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import SnapKit protocol ClientPickerViewControllerDelegate { func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) } struct ClientPickerViewControllerUX { static let TableHeaderRowHeight = CGFloat(50) static let TableHeaderTextFont = UIFont.systemFont(ofSize: 16) static let TableHeaderTextColor = UIColor.gray static let TableHeaderTextPaddingLeft = CGFloat(20) static let DeviceRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) static let DeviceRowHeight = CGFloat(50) static let DeviceRowTextFont = UIFont.systemFont(ofSize: 16) static let DeviceRowTextPaddingLeft = CGFloat(72) static let DeviceRowTextPaddingRight = CGFloat(50) } /// The ClientPickerViewController displays a list of clients associated with the provided Account. /// The user can select a number of devices and hit the Send button. /// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. /// That is up to it's delegate, who can listen for cancellation and success events. class ClientPickerViewController: UITableViewController { var profile: Profile? var profileNeedsShutdown = true var clientPickerDelegate: ClientPickerViewControllerDelegate? var reloading = true var clients: [RemoteClient] = [] var selectedClients = NSMutableSet() // ShareItem has been added as we are now using this class outside of the ShareTo extension to provide Share To functionality // And in this case we need to be able to store the item we are sharing as we may not have access to the // url later. Currently used only when sharing an item from the Tab Tray from a Preview Action. var shareItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Send Tab", tableName: "SendTo", comment: "Title of the dialog that allows you to send a tab to a different device") refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(ClientPickerViewController.refresh), for: UIControlEvents.valueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem( title: Strings.SendToCancelButton, style: .plain, target: self, action: #selector(ClientPickerViewController.cancel) ) tableView.register(ClientPickerTableViewHeaderCell.self, forCellReuseIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier) tableView.register(ClientPickerTableViewCell.self, forCellReuseIdentifier: ClientPickerTableViewCell.CellIdentifier) tableView.register(ClientPickerNoClientsTableViewCell.self, forCellReuseIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier) tableView.tableFooterView = UIView(frame: CGRect.zero) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let refreshControl = refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPoint(x: 0, y: height) } reloadClients() } override func numberOfSections(in tableView: UITableView) -> Int { if clients.count == 0 { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if clients.count == 0 { return 1 } else { if section == 0 { return 1 } else { return clients.count } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if clients.count > 0 { if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewHeaderCell } else { let clientCell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewCell clientCell.nameLabel.text = clients[indexPath.row].name clientCell.clientType = clients[indexPath.row].type == "mobile" ? ClientType.Mobile : ClientType.Desktop clientCell.checked = selectedClients.contains(indexPath) cell = clientCell } } else { if reloading == false { cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerNoClientsTableViewCell } else { cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "ClientCell") } } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if clients.count > 0 && indexPath.section == 1 { tableView.deselectRow(at: indexPath, animated: true) if selectedClients.contains(indexPath) { selectedClients.remove(indexPath) } else { selectedClients.add(indexPath) } tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) navigationItem.rightBarButtonItem?.isEnabled = (selectedClients.count != 0) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if clients.count > 0 { if indexPath.section == 0 { return ClientPickerViewControllerUX.TableHeaderRowHeight } else { return ClientPickerViewControllerUX.DeviceRowHeight } } else { return tableView.frame.height } } fileprivate func reloadClients() { // If we were not given a profile, open the default profile. This happens in case we are called from an app // extension. That also means that we need to shut down the profile, otherwise the app extension will be // terminated when it goes into the background. if self.profile == nil { self.profile = BrowserProfile(localName: "profile") self.profileNeedsShutdown = true } guard let profile = self.profile else { return } // Re-open the profile it was shutdown. This happens when we run from an app extension, where we must // make sure that the profile is only open for brief moments of time. if profile.isShutdown { profile.reopen() } reloading = true profile.getClients().upon({ result in withExtendedLifetime(profile) { // If we are running from an app extension then make sure we shut down the profile as soon as we are // done with it. if self.profileNeedsShutdown { profile.shutdown() } self.reloading = false guard let c = result.successValue else { return } self.clients = c DispatchQueue.main.async { if self.clients.count == 0 { self.navigationItem.rightBarButtonItem = nil } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Send", tableName: "SendTo", comment: "Navigation bar button to Send the current page to a device"), style: UIBarButtonItemStyle.done, target: self, action: #selector(ClientPickerViewController.send)) self.navigationItem.rightBarButtonItem?.isEnabled = false } self.selectedClients.removeAllObjects() self.tableView.reloadData() self.refreshControl?.endRefreshing() } } }) } func refresh() { reloadClients() } func cancel() { clientPickerDelegate?.clientPickerViewControllerDidCancel(self) } func send() { var clients = [RemoteClient]() for indexPath in selectedClients { clients.append(self.clients[(indexPath as AnyObject).row]) } clientPickerDelegate?.clientPickerViewController(self, didPickClients: clients) // Replace the Send button with a loading indicator since it takes a while to sync // up our changes to the server. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) loadingIndicator.color = .darkGray loadingIndicator.startAnimating() let customBarButton = UIBarButtonItem(customView: loadingIndicator) self.navigationItem.rightBarButtonItem = customBarButton } } class ClientPickerTableViewHeaderCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewSectionHeader" let nameLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.TableHeaderTextFont nameLabel.text = NSLocalizedString("Available devices:", tableName: "SendTo", comment: "Header for the list of devices table") nameLabel.textColor = ClientPickerViewControllerUX.TableHeaderTextColor nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.TableHeaderTextPaddingLeft) make.centerY.equalTo(self) make.right.equalTo(self) } preservesSuperviewLayoutMargins = false layoutMargins = UIEdgeInsets.zero separatorInset = UIEdgeInsets.zero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ClientType: String { case Mobile = "deviceTypeMobile" case Desktop = "deviceTypeDesktop" } class ClientPickerTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewCell" var nameLabel: UILabel var checked: Bool = false { didSet { self.accessoryType = checked ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none } } var clientType: ClientType = ClientType.Mobile { didSet { self.imageView?.image = UIImage(named: clientType.rawValue) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { nameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.DeviceRowTextFont nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = NSLineBreakMode.byWordWrapping self.tintColor = ClientPickerViewControllerUX.DeviceRowTintColor self.preservesSuperviewLayoutMargins = false self.selectionStyle = UITableViewCellSelectionStyle.none } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.DeviceRowTextPaddingLeft) make.centerY.equalTo(self.snp.centerY) make.right.equalTo(self.snp.right).offset(-ClientPickerViewControllerUX.DeviceRowTextPaddingRight) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ClientPickerNoClientsTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerNoClientsTableViewCell" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupHelpView(contentView, introText: NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", tableName: "SendTo", comment: "Error message shown in the remote tabs panel"), showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise. // Move the separator off screen separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
41.928349
306
0.672635
61f258a22e54c005e9f5e2515027043e68d5cd00
3,225
// // File.swift // // // Created by 山田良治 on 2019/11/15. // import Foundation /// Directory including xcode resources struct XCAssets: Directory, BundlerProtocol { struct BundleResult { let success: XCAssets let errors: [Error] } typealias Contents = [XCAssetsItem] /// The url of xcassets var url: URL /// The name of xcassets var name: String /// The items of xcassets var contents: [XCAssetsItem] init(url: URL) throws { self.url = url self.name = url.lastPathComponent let contentURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []) var contents: [XCAssetsItem] = [] contents.append(contentsOf: try contentURLs .filter { $0.pathExtension == "colorset" } .compactMap { try XCAssetsItem.colorset(Colorset(url: $0)) } ) contents.append(contentsOf: try contentURLs .filter { $0.pathExtension == "imageset" } .compactMap { try XCAssetsItem.imageset(Imageset(url: $0)) } ) if let contentsJsonURL: URL = contentURLs.first(where: { $0.lastPathComponent == "Contents.json" }) { let data = try Data(contentsOf: contentsJsonURL) let rootContents = try JSONDecoder().decode(RootContents.self, from: data) contents.append(XCAssetsItem.rootContentsJSON(rootContents)) } self.contents = contents } func bundled() -> BundleResult { let colorAssets = Bundler(source: contents.colorset).bundled() let colorBundleSuccessValues: [XCAssetsItem] = colorAssets .compactMap { try? $0.get() } .compactMap { .colorset($0) } let colorBundleErrors = colorAssets.compactMap { $0.error } let imageAssets = Bundler(source: contents.imageset).bundled() let imageBundleSuccessValues: [XCAssetsItem] = imageAssets .compactMap { try? $0.get() } .compactMap { .imageset($0)} let imageBundleErrors = imageAssets.compactMap { $0.error } let bundledSuccessValues: [XCAssetsItem] = { if let rootJSON = contents.rootContentsJSON { return colorBundleSuccessValues + imageBundleSuccessValues + [XCAssetsItem.rootContentsJSON(rootJSON)] } else { return colorBundleSuccessValues + imageBundleSuccessValues } }() let bundledErrors: [Error] = colorBundleErrors + imageBundleErrors /// I may use `Prototype` pattern in this context. var bundledAssets = self bundledAssets.contents = bundledSuccessValues return BundleResult(success: bundledAssets, errors: bundledErrors) } } extension Result { var error: Error? { if case .failure(let aError) = self { return aError } else { return nil } } }
31.930693
118
0.567442
7abe78b527d3c7496f2c0312c8296aa5d95b881a
9,919
// // RequestCreateViewController.swift // FirstCitizen // // Created by Lee on 25/09/2019. // Copyright © 2019 Kira. All rights reserved. // import UIKit import NMapsMap import TLPhotoPicker class RequestCreateViewController: UIViewController { private let tableView = UITableView() var fromMap = true var cell1 = RequestCreatePoliceStationCell() var cell7 = RequestCreateTextAddCell() var cell9 = RequestCreateTextAddCell() var cell10 = ImagePickerCell() var mainAdd = "" var detailAdd = "" var shortAdd = "현재 위치" var location = NMGLatLng() var category = 1 var police = 0 var imageArr = [UIImage]() var selectedAssets = [TLPHAsset]() { willSet(new) { imageArr = [] new.forEach { imageArr.append($0.fullResolutionImage ?? UIImage()) } cell10.imageArr = imageArr } } private let policeStation = [ "없음", "서울 강남 경찰서", "서울 강동 경찰서", "서울 강북 경찰서", "서울 강서 경찰서", "서울 관악 경찰서", "서울 광진 경찰서", "서울 구로 경찰서", "서울 금천 경찰서", "서울 남대문 경찰서", "서울 노원 경찰서", "서울 도봉 경찰서", "서울 동대문 경찰서", "서울 동작 경찰서", "서울 마포 경찰서", "서울 방배 경찰서", "서울 서대문 경찰서", "서울 서부 경찰서", "서울 서초 경찰서", "서울 성동 경찰서", "서울 성북 경찰서", "서울 송파 경찰서", "서울 수서 경찰서", "서울 양천 경찰서", "서울 영등포 경찰서", "서울 용산 경찰서", "서울 은평 경찰서", "서울 종로 경찰서", "서울 종암 경찰서", "서울 중량 경찰서", "서울 중부 경찰서", "서울 혜화 경찰서" ] var root: CreateRoot? override func viewDidLoad() { super.viewDidLoad() print("category in create", category) view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))) navigationSet() configure() autoLayout() } @objc func handleTap(_ sender: UITapGestureRecognizer) { if sender.state == .ended { view.endEditing(true) tableView.endEditing(true) } sender.cancelsTouchesInView = false } private func navigationSet() { navigationItem.title = "의뢰하기" navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.barTintColor = .white let barButton = UIBarButtonItem(title: "의 뢰", style: .done, target: self, action: #selector(barButtonAction)) navigationItem.rightBarButtonItem = barButton let backButton = UIBarButtonItem(image: UIImage(named: "navi-arrow-24x24"), style: .done, target: self, action: #selector(touchUpBackButton)) navigationItem.leftBarButtonItem = backButton } @objc func touchUpBackButton() { guard let tempRoot = root else { return } switch tempRoot { case .map: presentingViewController?.dismiss(animated: true) case .setting: navigationController?.popViewController(animated: true) } } @objc private func barButtonAction() { print("didTapbarbtn") let titleCell = cell7 let title = titleCell.textField.text ?? "오류" let contentCell = cell9 let content = contentCell.textView.text ?? "오류" let lat = location.lat let lng = location.lng let timeFormatter = DateFormatter() timeFormatter.locale = Locale(identifier: "ko") timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let time = timeFormatter.string(from: Date()) print("category: ", category) let requestData = RequestData(category: category, police: police, title: title, content: content, score: 50, mainAdd: mainAdd, detailAdd: detailAdd, lat: lat, lng: lng, time: time) print(requestData) NetworkService.createRequestWithImage(data: requestData, images: imageArr) { if $0 { DispatchQueue.main.async { if self.fromMap { self.dismiss(animated: true) } else { self.navigationController?.popViewController(animated: true) } } } print($0) } // NetworkService.createRequest(data: requestData) { // if $0 { // self.dismiss(animated: true) // } // print($0) // } } private func configure() { view.backgroundColor = .white tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none view.addSubview(tableView) view.bindToKeyboard() } private struct Standard { static let space: CGFloat = 8 } private func autoLayout() { let guide = view.safeAreaLayoutGuide tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true } } extension RequestCreateViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 11 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = " 관할 경찰서" cell.textLabel?.upsFontHeavy(ofSize: 24) return cell case 1: let cell = cell1 // cell.picker.selectRow(police, inComponent: police, animated: true) cell.picker.dataSource = self cell.picker.delegate = self return cell case 2: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = " 위치 입력" cell.textLabel?.upsFontHeavy(ofSize: 24) return cell case 3: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = "\(shortAdd) \(detailAdd)" cell.textLabel?.textAlignment = .center cell.textLabel?.upsFontHeavy(ofSize: 15) return cell case 4: let cell = RequestCreateAddressCell() cell.setting(type: .map) return cell case 5: let cell = RequestCreateAddressCell() cell.setting(type: .text) return cell case 6: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = " 제목" cell.textLabel?.upsFontHeavy(ofSize: 24) return cell case 7: let cell = cell7 cell.setting(type: .field) cell.textField.delegate = self return cell case 8: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = " 내용" cell.textLabel?.upsFontHeavy(ofSize: 24) return cell case 9: let cell = cell9 cell.setting(type: .view) return cell case 10: let cell = cell10 cell.delegate = self // cell.imageArr = self.imageArr return cell default: return UITableViewCell() } } } extension RequestCreateViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } extension RequestCreateViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return policeStation.count } } extension RequestCreateViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return policeStation[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print("police: ", row) police = row } } extension RequestCreateViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { // did tap map case 4: let vc = LocationWithMap() vc.delegate = self navigationController?.pushViewController(vc, animated: true) // did tap address case 5: let vc = LocationWithAddVC() vc.delegate = self navigationController?.pushViewController(vc, animated: true) default: break } } } extension RequestCreateViewController: LocationWithMapDelegate { func sendAddress(main: String, detail: String, short: String, location: NMGLatLng) { self.mainAdd = main self.detailAdd = detail self.shortAdd = short self.location = location self.tableView.reloadData() } } extension RequestCreateViewController: LocationWithAddVCDelegate { func sendAdd(main: String, detail: String, short: String, location: NMGLatLng) { self.mainAdd = main self.detailAdd = detail self.shortAdd = short self.location = location self.tableView.reloadData() } } extension RequestCreateViewController: ImagePickerCellDelegate { func didTapImageAddBtn() { print("didTapImageAddBtn") let picker = TLPhotosPickerViewController() picker.delegate = self self.present(picker, animated: true) } func tableviewReload() { self.tableView.reloadData() } } extension RequestCreateViewController: TLPhotosPickerViewControllerDelegate { func dismissPhotoPicker(withTLPHAssets: [TLPHAsset]) { self.selectedAssets = withTLPHAssets } }
24.612903
145
0.623248
d6d21fc49f7a20f02fd2e494dcbfafb3c00ff327
1,451
// // ProfileTableViewCell.swift // SimpleTwitter // // Created by LING HAO on 4/20/17. // Copyright © 2017 CodePath. All rights reserved. // import UIKit class ProfileTableViewCell: UITableViewCell { @IBOutlet var profileBackgroundImage: UIImageView! @IBOutlet var profileImage: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var screenNameLabel: UILabel! @IBOutlet var followingCount: UILabel! @IBOutlet var followerCount: UILabel! @IBOutlet var imageHeight: NSLayoutConstraint! @IBOutlet var imageWidth: NSLayoutConstraint! var user: User! { didSet { if let image = user.profileBackgroundUrl { profileBackgroundImage.setImageWith(image) } if let image = user.profileUrl { profileImage.setImageWith(image) } nameLabel.text = user.name if let screenName = user.screenName { screenNameLabel.text = "@" + screenName } followingCount.text = String(user.followingCount) followerCount.text = String(user.followersCount) } } 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 } }
27.903846
65
0.631978
871827f3bd9e03ed7a887e0322c008bdd68eb3bd
845
// // EndpointType.swift // theMovieDB // // Created by Andres Enrique Carrillo Miranda on 23/12/21. // import Alamofire protocol EndpointType: URLRequestConvertible { var baseURL: String { get } var path: String { get } var httpMethod: HTTPMethod { get } var params: [String: Any]? { get } var encoder: ParameterEncoding { get } } extension EndpointType { var baseURL: String { return NetworkConstants.baseURL } func asURLRequest() throws -> URLRequest { let url = try baseURL.asURL().appendingPathComponent(path) var urlRequest = try URLRequest(url: url, method: httpMethod) urlRequest.timeoutInterval = 20 urlRequest.httpMethod = httpMethod.rawValue urlRequest = try encoder.encode(urlRequest, with: params) return urlRequest } }
25.606061
69
0.662722
218ed1f9f25e91de5ccc9b91641c2cdd5885f034
3,649
// URLExtensionsTests.swift - Copyright 2020 SwifterSwift @testable import SwifterSwift import XCTest #if canImport(Foundation) import Foundation final class URLExtensionsTests: XCTestCase { var url = URL(string: "https://www.google.com")! let params = ["q": "swifter swift"] let queryUrl = URL(string: "https://www.google.com?q=swifter%20swift")! func testQueryParameters() { let url = URL(string: "https://www.google.com?q=swifter%20swift&steve=jobs&empty")! guard let parameters = url.queryParameters else { XCTAssert(false) return } XCTAssertEqual(parameters.count, 2) XCTAssertEqual(parameters["q"], "swifter swift") XCTAssertEqual(parameters["steve"], "jobs") XCTAssertNil(parameters["empty"]) } func testOptionalStringInitializer() { XCTAssertNil(URL(string: nil, relativeTo: nil)) XCTAssertNil(URL(string: nil)) let baseURL = URL(string: "https://www.example.com") XCTAssertNotNil(baseURL) XCTAssertNil(URL(string: nil, relativeTo: baseURL)) let string = "/index.html" let optionalString: String? = string XCTAssertEqual(URL(string: optionalString, relativeTo: baseURL), URL(string: string, relativeTo: baseURL)) XCTAssertEqual( URL(string: optionalString, relativeTo: baseURL)?.absoluteString, "https://www.example.com/index.html") } func testAppendingQueryParameters() { XCTAssertEqual(url.appendingQueryParameters(params), queryUrl) } func testAppendQueryParameters() { url.appendQueryParameters(params) XCTAssertEqual(url, queryUrl) } func testValueForQueryKey() { let url = URL(string: "https://google.com?code=12345&empty")! let codeResult = url.queryValue(for: "code") let emtpyResult = url.queryValue(for: "empty") let otherResult = url.queryValue(for: "other") XCTAssertEqual(codeResult, "12345") XCTAssertNil(emtpyResult) XCTAssertNil(otherResult) } func testDeletingAllPathComponents() { let url = URL(string: "https://domain.com/path/other/")! let result = url.deletingAllPathComponents() XCTAssertEqual(result.absoluteString, "https://domain.com/") } func testDeleteAllPathComponents() { var url = URL(string: "https://domain.com/path/other/")! url.deleteAllPathComponents() XCTAssertEqual(url.absoluteString, "https://domain.com/") } #if os(iOS) || os(tvOS) func testThumbnail() { XCTAssertNil(url.thumbnail()) let videoUrl = Bundle(for: URLExtensionsTests.self) .url(forResource: "big_buck_bunny_720p_1mb", withExtension: "mp4")! XCTAssertNotNil(videoUrl.thumbnail()) XCTAssertNotNil(videoUrl.thumbnail(fromTime: 1)) } #endif func testDropScheme() { let urls: [String: String?] = [ "https://domain.com/path/other/": "domain.com/path/other/", "https://domain.com": "domain.com", "http://domain.com": "domain.com", "file://domain.com/image.jpeg": "domain.com/image.jpeg", "://apple.com": "apple.com", "//apple.com": "apple.com", "apple.com": "apple.com", "http://": nil, "//": "//" ] urls.forEach { input, expected in guard let url = URL(string: input) else { return XCTFail("Failed to initialize URL.") } XCTAssertEqual(url.droppedScheme()?.absoluteString, expected, "input url: \(input)") } } } #endif
33.787037
114
0.623733
ef33eca582ae58145114bf6c6961a4cf1a25ef43
989
// // RemoteLoggerMonitorTests.swift // RemoteLoggerMonitorTests // // Created by k2moons on 2020/07/15. // Copyright © 2020 k2terada. All rights reserved. // @testable import RemoteLoggerMonitor import XCTest class RemoteLoggerMonitorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } 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 { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
29.969697
111
0.683519
7a4422de05e99c6c647240e11aa2f9709823017c
4,484
import UIKit /** View controller for the "Training Data" and "Testing Data" screens. */ class DataViewController: UITableViewController { var imagesByLabel: ImagesByLabel! let headerNib = UINib(nibName: "SectionHeaderView", bundle: nil) override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem let cellNib = UINib(nibName: "ExampleCell", bundle: nil) tableView.register(cellNib, forCellReuseIdentifier: "ExampleCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print(#function) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { imagesByLabel.numberOfLabels } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { imagesByLabel.numberOfImages(for: imagesByLabel.labelName(of: section)) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { imagesByLabel.labelName(of: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 88 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = headerNib.instantiate(withOwner: self, options: nil)[0] as! SectionHeaderView view.label.text = imagesByLabel.labelName(of: section) view.takePictureCallback = takePicture view.choosePhotoCallback = choosePhoto view.section = section view.cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) return view } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 132 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as! ExampleCell let label = imagesByLabel.labelName(of: indexPath.section) if let image = imagesByLabel.image(for: label, at: indexPath.row) { cell.exampleImageView.image = image cell.notFoundLabel.isHidden = true } else { cell.exampleImageView.image = nil cell.notFoundLabel.isHidden = false } return cell } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { indexPath } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the image from the data source. let label = imagesByLabel.labelName(of: indexPath.section) imagesByLabel.removeImage(for: label, at: indexPath.row) // Refresh the table view. tableView.deleteRows(at: [indexPath], with: .automatic) } } // MARK: - Choosing photos var pickPhotoForSection = 0 func takePicture(section: Int) { pickPhotoForSection = section presentPhotoPicker(sourceType: .camera) } func choosePhoto(section: Int) { pickPhotoForSection = section presentPhotoPicker(sourceType: .photoLibrary) } func presentPhotoPicker(sourceType: UIImagePickerController.SourceType) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = sourceType picker.allowsEditing = true present(picker, animated: true) } } extension DataViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) // Grab the image. let image = info[UIImagePickerController.InfoKey.editedImage] as! UIImage // Add the image to the data model. let label = labels.labelNames[pickPhotoForSection] imagesByLabel.addImage(image, for: label) // Refresh the table view. let count = imagesByLabel.numberOfImages(for: label) let indexPath = IndexPath(row: count - 1, section: pickPhotoForSection) tableView.insertRows(at: [indexPath], with: .automatic) } }
34.229008
142
0.740633
d68714e50149d147d8c5640551960f579c368148
1,624
// // DongtaiCollectionViewCell.swift // TodayNews // // Created by 邓康大 on 2019/4/10. // Copyright © 2019 邓康大. All rights reserved. // import UIKit import SVProgressHUD class DongtaiCollectionViewCell: UICollectionViewCell, RegisterCellFromNib { @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var iconButton: UIButton! @IBOutlet weak var gifLabel: UILabel! var isPostSmallVideo = false { didSet { iconButton.theme_setImage(isPostSmallVideo ? "images.smallvideo_all_32x32_" : nil, forState: .normal) } } var thumbImage = ThumbImage() { didSet { thumbImageView.kf.setImage(with: URL(string: thumbImage.urlString)) gifLabel.isHidden = !(thumbImage.type == .gif) } } var largeImage = LargeImage() { didSet { thumbImageView.kf.setImage(with: URL(string: largeImage.urlString), placeholder: nil, options: nil, progressBlock: { (receivedSize, totalSize) in let progress = receivedSize / totalSize SVProgressHUD.showProgress(Float(progress)) SVProgressHUD.setBackgroundColor(.clear) SVProgressHUD.setForegroundColor(.white) }) { (image, error, cacheType, url) in SVProgressHUD.dismiss() } } } override func awakeFromNib() { super.awakeFromNib() thumbImageView.layer.theme_borderColor = "colors.grayColor230" thumbImageView.layer.borderWidth = 1 theme_backgroundColor = "colors.cellBackgroundColor" } }
30.074074
157
0.634236
d50d8ed5059bb67e0313d0ce8fda90314eb5912e
176
import Foundation extension Data { public static func testJson(_ json: Any) throws -> Data { try JSONSerialization.data(withJSONObject: json, options: []) } }
22
69
0.681818
bf636fa0279286d3c79bc567d76fab0960fabbbe
2,275
// // DotRatingsView.swift // MovieDemo // // Created by Oscar Vernis on 17/09/20. // Copyright © 2020 Oscar Vernis. All rights reserved. // import UIKit @IBDesignable class DotRatingsView: UIView { @IBInspectable var rating: Float = 0 { didSet { if rating > 10 { rating = 10 } if rating < 0 { rating = 0 } setNeedsDisplay() } } @IBInspectable var isRatingAvailable: Bool = true { didSet { setNeedsDisplay() } } @IBInspectable var spacing: Int = 3 { didSet { setNeedsDisplay() } } private func drawRatingImage(_ name: String, position: Int, alpha: CGFloat = 1.0) { let itemSize = bounds.height let imageToDraw = UIImage(systemName: name)!.withTintColor(.systemOrange) let rect = CGRect(x: (itemSize * CGFloat(position)) + CGFloat(spacing * position), y: 0, width: itemSize, height: itemSize) imageToDraw.draw(in: rect, blendMode: .normal, alpha: alpha) } override func draw(_ rect: CGRect) { if !isRatingAvailable { for n in 0...4 { drawRatingImage("slash.circle", position: n, alpha: 0.6) } return } let halfRating = rating / 2 for n in 0...4 { if halfRating >= Float(n) + 0.9 { drawRatingImage("circle.fill", position: n) } else if halfRating >= Float(n) + 0.4, halfRating < Float(n) + 0.9 { drawRatingImage("circle.lefthalf.fill", position: n) } else { drawRatingImage("circle", position: n) } } } override func contentHuggingPriority(for axis: NSLayoutConstraint.Axis) -> UILayoutPriority { return .required } override func contentCompressionResistancePriority(for axis: NSLayoutConstraint.Axis) -> UILayoutPriority { return .required } override var intrinsicContentSize: CGSize { let itemSize = bounds.height return CGSize(width: (itemSize * 5) + CGFloat(spacing * 4), height: itemSize) } }
27.409639
131
0.542418
08a855f40d63d25f239456c1e30776432f3fdaf3
161
// // Created by color on 3/30/19. // import XCTest import GlibcExtraTests var tests = [XCTestCaseEntry]() tests += GlibcExtraTests.allTests() XCTMain(tests)
13.416667
35
0.726708
48edb86df204d41f27bbdcb9d67e35f9d02c9b43
1,668
// // VGSError.swift // VGSCollectSDK // // Created by Dima on 24.02.2020. // Copyright © 2020 VGS. All rights reserved. // import Foundation /// Type of `VGSError` and it status code. public enum VGSErrorType: Int { // MARK: - Text input data errors /// When input data is not valid, but required to be valid case inputDataIsNotValid = 1001 // MARK: - Files data errors /// When can't find file on device case inputFileNotFound = 1101 /// When can't find file on device case inputFileTypeIsNotSupported = 1102 /// When file size is larger then allowed limit case inputFileSizeExceedsTheLimit = 1103 /// When can't get access to file source case sourceNotAvailable = 1150 // MARK: - Other errors /// When response type is not supported case unexpectedResponseType = 1400 /// When reponse data format is not supported case unexpectedResponseDataFormat = 1401 } /// An error produced by `VGSCollectSDK`. Works similar to default `NSError` in iOS. public class VGSError: NSError { /// `VGSErrorType `- required for each `VGSError` instance public let type: VGSErrorType! /// Code assiciated with `VGSErrorType` override public var code: Int { return type.rawValue } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal required init(type: VGSErrorType, userInfo info: VGSErrorInfo? = nil) { self.type = type super.init(domain: VGSCollectSDKErrorDomain, code: type.rawValue, userInfo: info?.asDictionary) } }
26.903226
103
0.658273
eb11efcc18647d4bf641e72158312583e715f5e0
14,751
/* Abstract: The file contains html-types. Authors: - Mats Moll (https://github.com/matsmoll) Contributors: - Mattes Mohr (https://github.com/mattesmohr) Note: If you about to add something to the file, stick to the official documentation to keep the code consistent. */ /// A name for a element. /// /// ```html /// <meta name="viewport"> /// ``` public enum Names: String { case author = "author" case description = "description" case generator = "generator" case keywords = "keywords" case viewport = "viewport" case applicationName = "application-name" } /// A typ for buttons. /// /// ```html /// <button type="submit"></button> /// ``` public enum Buttons: String { /// Submits form data. case submit case button /// Resets the form data to its initial values. case reset } /// A encoding for the form submission. /// /// ```html /// <form enctype="text/plain"></form> /// ``` public enum Encoding: String { /// Encodes the data before sent to server. case urlEncoded = "application/x-www-form-urlencoded" /// Allows to upload file data. case multipart = "multipart/form-data" case plainText = "text/plain" } /// A method for the form submission. /// /// ```html /// <form method="get"></form> /// ``` public enum Method: String { /// Sends the form data as a post transaction. case post /// Appends the form data to name/value pairs. case get } /// A type of input elements. /// /// ```html /// <input type="password"> /// ``` public enum Inputs: String { case text case button case checkbox case color case date case email case file case hidden case image case month case number case password case radio case range case reset case search case submit case time case url case week case datetimeLocal = "datetime-local" case phone = "tel" } /// A language /// /// ```html /// <html lang="en"></html> /// ``` public enum Language: String { case abkhazian = "ab" case afar = "aa" case afrikaans = "af" case akan = "ak" case albanian = "sq" case amharic = "am" case arabic = "ar" case aragonese = "an" case armenian = "hy" case assamese = "as" case avaric = "av" case avestan = "ae" case aymara = "ay" case bambara = "bm" case bashkir = "ba" case baske = "eu" case belarusian = "be" case bengali = "bn" case bihari = "bh" case bislama = "bl" case bosnian = "bs" case breton = "br" case bulgarian = "bg" case burmese = "my" case catalan = "ca" case chamorro = "ch" case chechen = "ce" case chichewa, chewa, nyanja = "ny" case chinese = "zh" case chuvash = "cv" case cornish = "kw" case corsican = "co" case cree = "cr" case croation = "hr" case czech = "cs" case danish = "da" case divehi, dhivehi, maldivian = "dv" case dutch = "nl" case dzongkha = "dz" case english = "en" case esperanto = "eo" case estonian = "et" case ewe = "ee" case faroese = "fo" case fijian = "fj" case finnish = "fi" case french = "fr" case fula, fulah, pulaar, pular = "ff" case galician = "gl" case gaelicScottish = "gd" case gaelicManx = "gv" case georgian = "ka" case german = "de" case greek = "el" case guarani = "gn" case gujarati = "gu" case haitianCreole = "ht" case hausa = "ha" case hebrew = "he" case herero = "hz" case hindi = "hi" case hiriMotu = "ho" case hungarian = "hu" case icelandic = "is" case ido = "io" case igbo = "ig" case indonesian = "id" case interlingua = "ia" case interlingue = "ie" case inuktitut = "iu" case inupiak = "ik" case irish = "ga" case italian = "it" case japanese = "ja" case javanese = "jv" case kalaallisut, greenlandic = "kl" case kannada = "kn" case kanuri = "kr" case kashmiri = "ks" case kazakh = "kk" case khmer = "km" case kikuyu = "ki" case kinyarwandaRwanda = "rw" case kirundi = "rn" case kyrgyz = "ky" case komi = "kv" case kongo = "kg" case korean = "ko" case kurdish = "ku" case kwanyama = "kj" case lao = "lo" case latin = "la" case latvianLettish = "lv" case limburgish = "li" case lingala = "ln" case lithuanian = "lt" case lugaKatanga = "lu" case lugandaGanda = "lg" case luxembourgish = "lb" case macedonian = "mk" case malagasy = "mg" case malay = "ms" case malayalam = "ml" case maltese = "mt" case maori = "mi" case marathi = "mr" case marshallese = "mh" case moldavian = "mo" case mongolian = "mn" case nauru = "na" case navajo = "nv" case ndonga = "ng" case northernNdebele = "nd" case nepali = "ne" case norwegian = "no" case norwegianBokmål = "nb" case norwegianNynorsk = "nn" case nuosu, sichuanYi = "ii" case occitan = "oc" case ojibwe = "oj" case oldChurchSlavonic, oldBulgarian = "cu" case oriya = "or" case oromo = "om" case ossetian = "os" case pāli = "pi" case pashto, pushto = "ps" case persian = "fa" case polish = "pl" case portuguese = "pt" case punjabi = "pa" case quechua = "qu" case romansh = "rm" case romanian = "ro" case russian = "ru" case sami = "se" case samoan = "sm" case sango = "sg" case sanskrit = "sa" case serbian = "sr" case serboCroatian = "sh" case sesotho = "st" case setswana = "tn" case shona = "sn" case sindhi = "sd" case sinhalese = "si" case slovak = "sk" case slovenian = "sl" case somali = "so" case southernNdebele = "nr" case spanish = "es" case sundanese = "su" case swahili = "sw" case swati, siswati, swazi = "ss" case swedish = "sv" case tagalog = "tl" case tahitian = "ty" case tajik = "tg" case tamil = "ta" case tatar = "tt" case telugu = "te" case thai = "th" case tibetan = "bo" case tigrinya = "ti" case tonga = "to" case tsonga = "ts" case turkish = "tr" case turkmen = "tk" case twi = "tw" case uyghur = "ug" case ukrainian = "uk" case urdu = "ur" case uzbek = "uz" case venda = "ve" case vietnamese = "vi" case volapük = "vo" case wallon = "wa" case welsh = "cy" case wolof = "wo" case westernFrisian = "fy" case xhosa = "xh" case yiddish = "yi" case yoruba = "yo" case zhuang, chuang = "za" case zulu = "zu" } /// A reference information on a link. /// /// ```html /// <a referrerpolicy="no-referrer"></a> /// ``` public enum Policy: String { case strictOriginWhenCrossOrigin = "strict-origin-when-cross-origin" case noReferrer = "no-referrer" case noReferrerWhenDowngrade = "no-referrer-when-downgrade" case origin = "origin" case originWhenCrossOrigin = "origin-when-cross-origin" case sameOrigin = "same-origin" case strictOrigin = "strict-origin" case unsafeUrl = "unsafe-url" } /// A reference information between a link and the current document. /// /// ```html /// <a rel="next"></a> /// ``` public enum Relation: String { case alternate case author case help case icon case licence case next case pingback case preconnect case prefetch case preload case prerender case prev case search case stylesheet case noFollow = "nofollow" case noReferrer = "noreferrer" case noOpener = "noopener" case dnsPrefetch = "dns-prefetch" case appleTouchIcon = "apple-touch-icon" case appleTouchStartupImage = "apple-touch-startup-image" case shortcutIcon = "shortcut icon" } /// A target for reference links. /// /// ```html /// <button type="submit"></button> /// ``` public enum Target: String { /// Opens the target in a separate tab or window. case blank = "_blank" /// Opens the target in the parent frame. case parent = "_parent" /// Opens the target in the full frame of the window. case top = "_top" } /// The type is for /// /// ```html /// <area shape="rect"> /// ``` public enum Shape: String { case `default` case circle case polygon = "poly" case rectangle = "rect" } /// A manner of text wrapping. /// /// ```html /// <textarea wrap="hard"> /// ``` public enum Wrapping: String { /// Does not wrap the text after form submission. case soft /// Wraps the text, after form submission. case hard } /// A text direction. /// /// ```html /// <p dir="rtl"></p> /// ``` public enum Direction: String { /// Sets the direction left to right. case leftToRight = "ltr" /// Sets the direction right to left. case rightToLeft = "rtl" /// Decides the direction by its content. case auto } /// The type is for /// /// ```html /// <link type="text/css"></link> /// ``` public enum Medias: String { case html = "text/html" case css = "text/css" case ogg = "video/ogg" case mp4 = "video/mp4" case webm = "video/webm" case mpeg = "audio/mpeg" case javascript = "application/javascript" case xIcon = "image/x-icon" } /// The type is for /// /// ```html /// <ol type="I"></ol> /// ``` public enum Marker: String { case decimal = "1" case uppercaseAlpha = "A" case lowercaseAlpha = "a" case uppercaseRoman = "I" case lowercaseRoman = "i" } /// The type is for /// /// ```html /// <!DOCTYPE html5> /// ``` public enum Doctypes: String { case html5 = "html" case html4Strict = #"HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd""# case html4Transitional = #"HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd""# case html4Frameset = #"HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd""# case xhtmlStrict = #"html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""# case xhtmlTransitional = #"html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""# case xhtmlFrameset = #"html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd""# case xhtml = #"html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd""# } /// The type is for /// /// ```html /// <meta property="og:title"> /// ``` public enum Graphs: String { case title = "og:title" case image = "og:image" case description = "og:description" case type = "og:type" case url = "og:url" case locale = "og:locale" case siteName = "og:site_name" } /// The type is for /// /// ```html /// <input enterkeyhint="next"> /// ``` public enum Hint: String { case enter case done case go case next case previous case search case send } /// The type is for /// /// ```html /// <input autocapitalize="words"></input> /// ``` public enum Capitalization: String { /// Does not capitlize. case off = "off" /// Capitlizes the entire text. case characters = "characters" /// Capitlizes the first letter of each word. case words = "words" /// Capitlizes first letter of the sentence. case sentences = "sentences" } /// A character encoding for the html-document. /// /// ```html /// <meta charset="utf-8"> /// ``` public enum Charset: String { /// Specifies the encoding for unicode. case utf8 = "utf-8" case utf16 = "utf-16" /// Specifies the encoding for windows-1252. case ansi = "windows-1252" /// Specifies the encoding for latin alphabet. case iso = "iso-8859-1" } /// The type is for /// /// ```html /// <meta http-equiv="refresh"> /// ``` public enum Equivalent: String { case content = "content-type" case `default` = "default-style" case refresh = "refresh" } /// The type is for /// /// ```html /// <a role="button"></a> /// ``` public enum Roles: String { case alert case alertDialog = "alertdialog" case application case article case banner case button case cell case checkbox case columnHeader = "columnheader" case combobox case command case comment case complementary case composite case contentInfo = "contentinfo" case definition case dialog case directory case document case feed case figure case form case grid case gridCell = "gridcell" case group case heading case img case input case landmark case list case listBox = "listbox" case listItem = "listitem" case log case main case mark case marquee case math case menu case menuBar = "menubar" case menuItem = "menuitem" case menuItemCheckbox = "menuitemcheckbox" case menuItemRadio = "menuitemradio" case meter case navigation case none case note case option case presentation case radio case range case region case roleType = "roletype" case row case rowGroup = "rowgroup" case rowHeader = "rowheader" case scrollbar case search case searchBox = "searchbox" case sectionHead = "sectionhead" case select case separator case status case structure case suggestion case `switch` case tab case table case tabList = "tablist" case tabPanel = "tabpanel" case term case textbox case timer case toolbar case tooltip case tree case treeGrid = "treegrid" case treeItem = "treeitem" case widget case window } /// The type is for /// /// ```html /// <line stroke-linecap="square"> /// ``` public enum Linecap: String { case butt case square case round } /// The type is for /// /// ```html /// <path stroke-linejoin="bevel"></path> /// ``` public enum Linejoin: String { case miter case round case bevel } /// The type is for /// /// ```html /// <span translate="yes"></span> /// ``` public enum Decision: String { case yes case no } /// The type is for /// /// ```html /// <track kind="subtitles"> /// ``` public enum Kinds: String { case captions case chapters case descriptions case metadata case subtitles } /// The type is for /// /// ```html /// <audio preload="none"> /// ``` public enum Preload: String { case auto case metadata case none }
21.471616
143
0.590401
01633f81cf2c8bf7c6139fc50fd6e2e6d81315b1
2,172
// // SettingViewController.swift // TipCalculator // // Created by SongYuda on 12/16/16. // Copyright © 2016 SongYuda. All rights reserved. // import UIKit class SettingViewController: UIViewController { @IBOutlet weak var tipController: UISegmentedControl! @IBOutlet weak var DefaultController: UISegmentedControl! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeTip(_ sender: Any) { let defaults = UserDefaults.standard if(tipController.selectedSegmentIndex == 0) { defaults.set([0.1,0.15,0.2], forKey: "Percentages") defaults.set(0, forKey: "Index1") defaults.synchronize() } if(tipController.selectedSegmentIndex == 1) { defaults.set([0.15,0.18,0.2], forKey: "Percentages") defaults.set(1, forKey: "Index1") defaults.synchronize() } if(tipController.selectedSegmentIndex == 2) { defaults.set([0.18,0.2,0.25], forKey: "Percentages") defaults.set(2, forKey: "Index1") defaults.synchronize() } } override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard defaults.synchronize() let index1 = defaults.integer(forKey: "Index1") tipController.selectedSegmentIndex = index1 let index2 = defaults.integer(forKey: "Index2") DefaultController.selectedSegmentIndex = index2 } @IBAction func changeDefault(_ sender: Any) { let defaults = UserDefaults.standard defaults.set(DefaultController.selectedSegmentIndex, forKey: "Index2") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.478261
106
0.634899
6a9a6cacae48df08917905e0ec2837aa6aafefd8
456
// // NonTranslucentNavigationBar.swift // GoodsScanner // // Created by Alexander Kozlov on 9/12/19. // Copyright © 2019 iTomych. All rights reserved. // import UIKit class NonTranslucentNavigationBar: UINavigationBar { override init(frame: CGRect) { super.init(frame: frame) isTranslucent = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isTranslucent = false } }
20.727273
52
0.662281
9ba6571ee33a0f7ae03f570a3a2032154b022994
7,172
// // Mutation.swift // OrderedCollection // // Created by Vitali Kurlovich on 1/15/19. // import Foundation public protocol MutationCollectionCapacity { var capacity: Int { get } mutating func reserveCapacity(_ minimumCapacity: Int) } public protocol MutationCollectionAppend { associatedtype Element /// Adds a new element at the end of the collection. /// /// - Parameter newElement: The element to append to the collection. mutating func append(_ newElement: Element) /// Adds the elements of a sequence to the end of the collection. /// /// - Parameter newElements: The elements to append to the collection. mutating func append<S>(contentsOf newElements: S) where Element == S.Element, S: Sequence } public protocol MutationCollectionInsert { associatedtype Element /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the collection. /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the collection or equal to its `endIndex` /// property. mutating func insert(_ newElement: Element, at i: Int) /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*n* + *m*), where *n* is length of this collection and /// *m* is the length of `newElements`. If `i == endIndex`, this method /// is equivalent to `append(contentsOf:)`. mutating func insert<C>(contentsOf newElements: C, at i: Int) where C: Collection, Element == C.Element } public protocol MutationCollectionReplace { associatedtype Element /// Replaces the specified subrange of elements with the given collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*n* + *m*), where *n* is length of this collection and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the collection, the complexity /// is O(*m*). mutating func replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C: Collection, R: RangeExpression, Element == C.Element, Array<Element>.Index == R.Bound } public protocol MutationCollectionRemove { associatedtype Element /// Removes and returns the element at the specified position. /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the collection. /// - Returns: The element at the specified index. mutating func remove(at index: Int) -> Element /// Removes and returns the last element of the collection. /// /// - Returns: The last element of the collection. mutating func removeLast() -> Element /// Removes the specified number of elements from the beginning of the /// collection. /// /// - Parameter k: The number of elements to remove from the collection. /// `k` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeFirst(_ k: Int) /// Removes the given number of elements from the end of the collection. /// /// - Parameter k: The number of elements to remove. `k` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to remove. mutating func removeLast(_ k: Int) /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeFirst() -> Element /// Removes all elements from the collection. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. mutating func removeAll(keepingCapacity keepCapacity: Bool) /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes three elements from the middle of an array of /// measurements. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeSubrange<R>(_ bounds: R) where R: RangeExpression, Array<Element>.Index == R.Bound /// Removes all the elements that satisfy the given predicate. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be removed from the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows /// Removes and returns the last element of the collection. /// /// - Returns: The last element of the collection if the collection is not /// empty; otherwise, `nil`. /// /// - Complexity: O(1) mutating func popLast() -> Element? } extension Array: MutationCollectionCapacity {} extension ArraySlice: MutationCollectionCapacity {} extension Array: MutationCollectionAppend {} extension ArraySlice: MutationCollectionAppend {} extension Array: MutationCollectionRemove {} extension ArraySlice: MutationCollectionRemove {} extension Array: MutationCollectionReplace {} extension ArraySlice: MutationCollectionReplace {} extension Array: MutationCollectionInsert {} extension ArraySlice: MutationCollectionInsert {}
36.969072
161
0.673034
64a974d1d22fd3759d70eebc082448471ead679d
2,384
// // NSDate+Category.swift // DSWeibo // // Created by xiaomage on 16/9/13. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit extension Date { static func dateWithStr(time: String) ->Date { // 1.将服务器返回给我们的时间字符串转换为NSDate // 1.1.创建formatter let formatter = DateFormatter() // 1.2.设置时间的格式 formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy" // 1.3设置时间的区域(真机必须设置, 否则可能不能转换成功) formatter.locale = Locale(identifier: "en") // 1.4转换字符串, 转换好的时间是去除时区的时间 let createdDate = formatter.date(from: time)! return createdDate } /** 刚刚(一分钟内) X分钟前(一小时内) X小时前(当天) 昨天 HH:mm(昨天) MM-dd HH:mm(一年内) yyyy-MM-dd HH:mm(更早期) */ var descDate:String{ let calendar = NSCalendar.current // 1.判断是否是今天 if calendar.isDateInToday(self) { // 1.0获取当前时间和系统时间之间的差距(秒数) let since = Int(NSDate().timeIntervalSince(self)) // 1.1是否是刚刚 if since < 60 { return "刚刚" } // 1.2多少分钟以前 if since < 60 * 60 { return "\(since/60)分钟前" } // 1.3多少小时以前 return "\(since / (60 * 60))小时前" } // 2.判断是否是昨天 var formatterStr = "HH:mm" if calendar.isDateInYesterday(self) { // 昨天: HH:mm formatterStr = "昨天:" + formatterStr }else { // 3.处理一年以内 formatterStr = "MM-dd " + formatterStr // 4.处理更早时间 // let comps = calendar.components(NSCalendar.Unit.Year, fromDate: self, toDate: NSDate(), options: NSCalendar.Options(rawValue: 0)) let comps = calendar.dateComponents([.year], from: self, to: Date()) if comps.year! >= 1 { formatterStr = "yyyy-" + formatterStr } } // 5.按照指定的格式将时间转换为字符串 // 5.1.创建formatter let formatter = DateFormatter() // 5.2.设置时间的格式 formatter.dateFormat = formatterStr // 5.3设置时间的区域(真机必须设置, 否则可能不能转换成功) formatter.locale = Locale(identifier: "en") // 5.4格式化 return formatter.string(from: self) } }
25.361702
143
0.491611
29b5ac0f44d0ddc50c71e36ce991b79a20a244b9
8,925
// // CacheProvider.swift // ImageAsyncTest // // Created by Yury Nechaev on 15.10.16. // Copyright © 2016 Yury Nechaev. All rights reserved. // import UIKit public typealias CacheCompletionClosure = ((_ success: Bool) -> (Void)) let maxMemoryCacheSize : Int64 = 10 * 1024 * 1024 // 10Mb public class CacheProvider { internal var memoryCache: [String: CacheEntry] = [:] public var configuration: CacheConfiguration public static let sharedInstance : CacheProvider = { let options : CacheOptions = [.memory, .disk] let conf = CacheConfiguration(options: options, memoryCacheLimit: maxMemoryCacheSize) let instance = CacheProvider(configuration: conf) return instance }() public init(configuration: CacheConfiguration) { self.configuration = configuration } public func cacheForKey(_ key: String, completion: @escaping ((_ data: Data?) -> Void)) { if let memCache = memoryCacheForKey(key) { completion(memCache) } else { diskCacheForKey(key, completion: completion) } } public func memoryCacheForKey(_ key: String) -> Data? { if configuration.options.contains(.memory) { if let cacheHit = memoryCache[key] { yn_logInfo("Mem cache hit: \(key)") return cacheHit.data } yn_logInfo("Mem cache miss: \(key)") } return nil } public func diskCacheForKey(_ key: String, completion: @escaping ((_ data: Data?) -> Void)) { if configuration.options.contains(.disk) { let filePath = fileInCacheDirectory(filename: key) let url = URL(fileURLWithPath: filePath) readCache(fileUrl: url, completion: { (data) in if let cacheHit = data { yn_logInfo("Disk cache hit: \(key)") self.cacheDataToMemory(key, cacheHit) completion(cacheHit) return } else { yn_logInfo("Disk cache miss: \(key)") completion(nil) return } }) } else { completion(nil) } } public func cacheData(_ key: String, _ data: Data, completion: CacheCompletionClosure? = nil) { cacheDataToMemory(key, data) cacheDataToDisk(key, data, completion: completion) } public func cacheDataToMemory(_ key: String, _ data: Data) { if configuration.options.contains(.memory) { let entry = CacheEntry(data: data, date: Date()) yn_logInfo("Cache store: \(key)") memoryCache[key] = entry cleanMemoryCache() } } public func cacheDataToDisk(_ key: String, _ data: Data, completion: CacheCompletionClosure? = nil) { if configuration.options.contains(.disk) { let filePath = fileInCacheDirectory(filename: key) let url = URL(fileURLWithPath: filePath) saveCache(cacheData: data, fileUrl: url, completion: completion) } else { if let completionClosure = completion { completionClosure(true) } } } public func cleanMemoryCache() { let sorted = memoryCache.values.sorted { (entry1, entry2) -> Bool in return entry1.date > entry2.date } let maxSize = configuration.memoryCacheLimit let memorySize = memoryCacheSize() if memorySize > maxSize { yn_logInfo("Memory cache \(memoryCacheSize()) > max \(maxSize)") var size : Int64 = 0 var newCache : Array<CacheEntry> = [] for cacheEntry in sorted { size += cacheEntry.data.count if size > maxSize { yn_logInfo("Found \(sorted.count - newCache.count) elements exceeding capacity") filterCacheWithArray(array: newCache) break } newCache.append(cacheEntry) } } } public func clearMemoryCache() { memoryCache.removeAll() } public func diskCacheSize() -> Int64 { let files = cacheFolderFiles() var folderSize : Int64 = 0 for file in files { do { let attributes = try FileManager.default.attributesOfItem(atPath: file) let fileSize = attributes[FileAttributeKey.size] as! NSNumber folderSize += fileSize.int64Value } catch let error { yn_logInfo("Cache folder file attribute error: \(error)") } } return folderSize } public func memoryCacheSize() -> Int64 { var size: Int64 = 0 for cacheEntry in memoryCache.values { size += cacheEntry.data.count } return size } public func clearDiskCache() { let files = cacheFolderFiles() for file in files { yn_logInfo("Trying to delete \(file)") do { try FileManager.default.removeItem(atPath: file) yn_logInfo("Deleted disk cache: \(file)") } catch let error { yn_logInfo("Cache folder read error: \(error)") } } } public func clearCache() { clearMemoryCache() clearDiskCache() } func cacheFolderFiles() -> [String] { var returnedValue: [String] = [] do { let files = try FileManager.default.contentsOfDirectory(atPath: cachePath()) for file in files { let path = cachePath() let fullPath = (path as NSString).appendingPathComponent(file) returnedValue.append(fullPath) } } catch let error { yn_logInfo("Cache folder read error: \(error)") } return returnedValue } func filterCacheWithArray(array: Array <CacheEntry>) { let tempCache = memoryCache for (key, entry) in tempCache { if !array.contains(where: { (filterEntry) -> Bool in return entry.udid == filterEntry.udid }) { memoryCache.removeValue(forKey: key) yn_logInfo("Removing \(entry.udid)") } } } func cacheDirectory() -> String { let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] return documentsFolderPath } func cachePath() -> String { return (cacheDirectory() as NSString).appendingPathComponent("YNImageAsync") } func fileInCacheDirectory(filename: String) -> String { let writePath = cachePath() if (!FileManager.default.fileExists(atPath: writePath)) { do { try FileManager.default.createDirectory(atPath: writePath, withIntermediateDirectories: false, attributes: nil) } catch let error { yn_logError("Failed to create directory: \(writePath) - \(error)") } } if let escapedFilename = filename.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { return (writePath as NSString).appendingPathComponent(escapedFilename) } else { return (writePath as NSString).appendingPathComponent(filename) } } func readCache(fileUrl: URL, completion: @escaping ((_ data: Data?) -> Void)) { executeBackground { do { let data = try Data(contentsOf: fileUrl) yn_logInfo("Disk cache read success: \(fileUrl)") completion(data) } catch let readError { yn_logInfo("Disk cache read error: \(readError)") completion(nil) } } } func saveCache(cacheData: Data, fileUrl: URL, completion: CacheCompletionClosure? = nil) { executeBackground { do { try cacheData.write(to: fileUrl , options: Data.WritingOptions(rawValue: 0)) yn_logInfo("Disk cache write success: \(fileUrl)") if let completionClosure = completion { completionClosure(true) } } catch let saveError { yn_logError("Disk cache write error: \(saveError)") if let completionClosure = completion { completionClosure(false) } } } } func executeBackground(_ block:@escaping () -> Void) { if (Thread.isMainThread) { DispatchQueue.global(qos: .default).async { block() } } else { block() } } }
35
176
0.561008
eb679cc0d08fae9ad3719d4b59bd30a59ba945bc
520
import Foundation import CoreGraphics extension MeasurementFormatter { @inlinable public func string(from value: Double, _ unit: Unit) -> String { string(from: .init(value: value, unit: unit)) } @inlinable public func string(from value: Float, _ unit: Unit) -> String { string(from: .init(value: Double(value), unit: unit)) } @inlinable public func string(from value: CGFloat, _ unit: Unit) -> String { string(from: .init(value: Double(value), unit: unit)) } }
30.588235
80
0.646154
87e3b85e223bafd28e08e79b47f2237900905bf7
580
// RUN: %target-typecheck-verify-swift func f0(_ x: Int) -> Int { return 0 } func f0(_ x: Float) -> Float { return 0.0 } func f1() -> Int { return 0 } func f1() -> Float { return 0.0 } struct Y { func f0(_ x: Int) -> Int { return 0 } func f0(_ x: Float) -> Float { return 0.0 } func f1() -> Int { return 0 } func f1() -> Float { return 0.0 } } func testParenOverloads(_ x: inout Int, y: Y) { x = f0(x) x = (f0)(x) x = ((f0))(x) x = f1() x = (f1)() x = ((f1))() x = y.f0(x) x = (y.f0)(x) x = ((y.f0))(x) x = y.f1() x = (y.f1)() x = ((y.f1))() }
19.333333
47
0.486207
2681203560203127788274b3aed35c26630ef348
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T{enum S<h{protocol A{{ } func g:A struct A:B<T> struct B<a
23.7
87
0.742616
22ecac3f67b7d5ed495f6bd3c1166184d8dfff4c
1,244
// // MF_Segue_AskVC.swift // Introvert // // Created by 张高歌 on 15/12/6. // Copyright © 2015年 weIntroverts. All rights reserved. // import UIKit import CoreData ////////ext:----------Manage Segues---------------- extension AskViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { func cancel() { //Todo self.backupQuestion() } func done() { // 存储 saveQuestion() // 传coreDataStack let destinationController = segue.destination as! UINavigationController let topController = destinationController.topViewController as! DetailViewController topController.coreDataStack = self.coreDataStack // 传question let fetch = NSFetchRequest(entityName: "CDQuestion") let results = try! coreDataStack.managedObjectContext.fetch(fetch) as! [CDQuestion] let currentQuestion = results.last! topController.question = currentQuestion } switch (sender! as! UIBarButtonItem).title! { case "取消": cancel() case "完成": done() default: break } } }
30.341463
96
0.572347
2fc02f456407a577e37775be57249bf55167b1f7
757
import XCTest import StripeAnimationLayer class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
26.103448
111
0.606341
795c852a0963442ccc1df5569124370c0d8a6a45
611
import Foundation final class WarningConditionViolation: DataValidating { let preservesCondition: () -> Bool let onWarning: (DataValidatingDelegate) -> Void init( onWarning: @escaping (DataValidatingDelegate) -> Void, preservesCondition: @escaping () -> Bool ) { self.preservesCondition = preservesCondition self.onWarning = onWarning } func validate(notifying delegate: DataValidatingDelegate) -> DataValidationProblem? { if preservesCondition() { return nil } onWarning(delegate) return .warning } }
24.44
89
0.651391
29442e20e9bff300e80dfe20768e656d580c6948
6,096
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. import SotoCore /// Error enum for Textract public struct TextractErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case badDocumentException = "BadDocumentException" case documentTooLargeException = "DocumentTooLargeException" case humanLoopQuotaExceededException = "HumanLoopQuotaExceededException" case idempotentParameterMismatchException = "IdempotentParameterMismatchException" case internalServerError = "InternalServerError" case invalidJobIdException = "InvalidJobIdException" case invalidKMSKeyException = "InvalidKMSKeyException" case invalidParameterException = "InvalidParameterException" case invalidS3ObjectException = "InvalidS3ObjectException" case limitExceededException = "LimitExceededException" case provisionedThroughputExceededException = "ProvisionedThroughputExceededException" case throttlingException = "ThrottlingException" case unsupportedDocumentException = "UnsupportedDocumentException" } private let error: Code public let context: AWSErrorContext? /// initialize Textract public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see limits. public static var badDocumentException: Self { .init(.badDocumentException) } /// The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. public static var documentTooLargeException: Self { .init(.documentTooLargeException) } /// Indicates you have exceeded the maximum number of active human in the loop workflows available public static var humanLoopQuotaExceededException: Self { .init(.humanLoopQuotaExceededException) } /// A ClientRequestToken input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. public static var idempotentParameterMismatchException: Self { .init(.idempotentParameterMismatchException) } /// Amazon Textract experienced a service issue. Try your call again. public static var internalServerError: Self { .init(.internalServerError) } /// An invalid job identifier was passed to GetDocumentAnalysis or to GetDocumentAnalysis. public static var invalidJobIdException: Self { .init(.invalidJobIdException) } /// Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. public static var invalidKMSKeyException: Self { .init(.invalidKMSKeyException) } /// An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. public static var invalidParameterException: Self { .init(.invalidParameterException) } /// Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 public static var invalidS3ObjectException: Self { .init(.invalidS3ObjectException) } /// An Amazon Textract service limit was exceeded. For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. public static var limitExceededException: Self { .init(.limitExceededException) } /// The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. public static var provisionedThroughputExceededException: Self { .init(.provisionedThroughputExceededException) } /// Amazon Textract is temporarily unable to process the request. Try your call again. public static var throttlingException: Self { .init(.throttlingException) } /// The format of the input document isn't supported. Documents for synchronous operations can be in PNG or JPEG format only. Documents for asynchronous operations can be in PDF format. public static var unsupportedDocumentException: Self { .init(.unsupportedDocumentException) } } extension TextractErrorType: Equatable { public static func == (lhs: TextractErrorType, rhs: TextractErrorType) -> Bool { lhs.error == rhs.error } } extension TextractErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
62.204082
344
0.741798
56ce31c1026845b7c216d2f1c41c23952dc71ddb
726
// // TextFieldCell.swift // WHCoreServicesDemo // // Created by Hsiao, Wayne on 2019/10/10. // Copyright © 2019 Wayne Hsiao. All rights reserved. // import UIKit class TextFieldCell: UITableViewCell { @IBOutlet weak var textField: UITextField! { didSet { textField.delegate = self } } static let nibName = "TextFieldCell" 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 } } extension TextFieldCell: UITextFieldDelegate { }
19.621622
65
0.637741
215bec7e78af2bae03d9cbd1af53f2bf2feeae24
2,469
// // Tabs.swift // Brotherhoold Alchemist SwiftUI // // Created by Dave Poirier on 2022-04-09. // Copyright © 2022 Dave Poirier. All rights reserved. // import SwiftUI struct Tabs: View { @State var buttonsWidth: CGFloat = .zero @Binding var selectedTab: Tab @Environment(\.colorScheme) var colorScheme private var shadowColor: Color { if colorScheme == .dark { return Color.white } return Color.black } var body: some View { HStack { ForEach(Tab.allCases, id: \.rawValue) { tab in tabButton(tab) } } .padding() .background( RoundedRectangle(cornerRadius: .infinity) .foregroundColor(Color(UIColor.systemBackground)) .shadow(color: shadowColor, radius: 12.0) ) } private func selectTab(_ tab: Tab) { selectedTab = tab } private func tabButton(_ tab: Tab) -> some View { Button(action: { selectTab(tab) }) { Text(tab.rawValue) } .foregroundColor(tabColor(tab)) .frame(minWidth: buttonsWidth) .overlay(MinWidthCoordinator(via: $buttonsWidth)) } private func tabColor(_ tab: Tab) -> Color { if tab == selectedTab { return Color(UIColor.systemBlue) } return Color("itemForeground") } private func tabDecorator(_ tab: Tab) -> some View { VStack { if tab != selectedTab { Color.clear } else { Color(UIColor.systemBlue) .frame(width: buttonsWidth, height: 1.0) .id("tabDecorator") } } } } struct Tabs_Previews: PreviewProvider { static var previews: some View { ZStack { Tabs(selectedTab: Binding( get: { .recipes}, set: { _ in /* ignored */ })) } .background(Color("itemBackground")) .previewDevice("iPhone 13 Pro") .previewDisplayName("Dark") .preferredColorScheme(.dark) ZStack { Tabs(selectedTab: Binding( get: { .recipes}, set: { _ in /* ignored */ })) } .background(Color("itemBackground")) .previewDisplayName("Light") .preferredColorScheme(.light) .previewDevice("iPhone 13 Pro") } }
25.71875
65
0.527339
f7834318e7939ae08c69c892af4dbecc81f27aa1
1,154
// https://github.com/Quick/Quick import Quick import Nimble import SwiftbyHet class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
22.627451
60
0.357886
ab0a68b8766fc74ca5daba6082edb85338ce7d96
11,720
// Sources/SwiftProtobuf/Google_Protobuf_Timestamp+Extensions.swift - Timestamp extensions // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Extend the generated Timestamp message with customized JSON coding, /// arithmetic operations, and convenience methods. /// // ----------------------------------------------------------------------------- import Foundation private let minTimestampSeconds: Int64 = -62135596800 // 0001-01-01T00:00:00Z private let maxTimestampSeconds: Int64 = 253402300799 // 9999-12-31T23:59:59Z // TODO: Add convenience methods to interoperate with standard // date/time classes: an initializer that accepts Unix timestamp as // Int or Double, an easy way to convert to/from Foundation's // NSDateTime (on Apple platforms only?), others? // Parse an RFC3339 timestamp into a pair of seconds-since-1970 and nanos. private func parseTimestamp(s: String) throws -> (Int64, Int32) { // Convert to an array of integer character values let value = s.utf8.map{Int($0)} if value.count < 20 { throw JSONDecodingError.malformedTimestamp } // Since the format is fixed-layout, we can just decode // directly as follows. let zero = Int(48) let nine = Int(57) let dash = Int(45) let colon = Int(58) let plus = Int(43) let letterT = Int(84) let letterZ = Int(90) let period = Int(46) func fromAscii2(_ digit0: Int, _ digit1: Int) throws -> Int { if digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine { throw JSONDecodingError.malformedTimestamp } return digit0 * 10 + digit1 - 528 } func fromAscii4( _ digit0: Int, _ digit1: Int, _ digit2: Int, _ digit3: Int ) throws -> Int { if (digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine || digit2 < zero || digit2 > nine || digit3 < zero || digit3 > nine) { throw JSONDecodingError.malformedTimestamp } return digit0 * 1000 + digit1 * 100 + digit2 * 10 + digit3 - 53328 } // Year: 4 digits followed by '-' let year = try fromAscii4(value[0], value[1], value[2], value[3]) if value[4] != dash || year < Int(1) || year > Int(9999) { throw JSONDecodingError.malformedTimestamp } // Month: 2 digits followed by '-' let month = try fromAscii2(value[5], value[6]) if value[7] != dash || month < Int(1) || month > Int(12) { throw JSONDecodingError.malformedTimestamp } // Day: 2 digits followed by 'T' let mday = try fromAscii2(value[8], value[9]) if value[10] != letterT || mday < Int(1) || mday > Int(31) { throw JSONDecodingError.malformedTimestamp } // Hour: 2 digits followed by ':' let hour = try fromAscii2(value[11], value[12]) if value[13] != colon || hour > Int(23) { throw JSONDecodingError.malformedTimestamp } // Minute: 2 digits followed by ':' let minute = try fromAscii2(value[14], value[15]) if value[16] != colon || minute > Int(59) { throw JSONDecodingError.malformedTimestamp } // Second: 2 digits (following char is checked below) let second = try fromAscii2(value[17], value[18]) if second > Int(61) { throw JSONDecodingError.malformedTimestamp } // timegm() is almost entirely useless. It's nonexistent on // some platforms, broken on others. Everything else I've tried // is even worse. Hence the code below. // (If you have a better way to do this, try it and see if it // passes the test suite on both Linux and OS X.) // Day of year let mdayStart: [Int] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] var yday = Int64(mdayStart[month - 1]) let isleap = (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)) if isleap && (month > 2) { yday += 1 } yday += Int64(mday - 1) // Days since start of epoch (including leap days) var daysSinceEpoch = yday daysSinceEpoch += Int64(365 * year) - Int64(719527) daysSinceEpoch += Int64((year - 1) / 4) daysSinceEpoch -= Int64((year - 1) / 100) daysSinceEpoch += Int64((year - 1) / 400) // Second within day var daySec = Int64(hour) daySec *= 60 daySec += Int64(minute) daySec *= 60 daySec += Int64(second) // Seconds since start of epoch let t = daysSinceEpoch * Int64(86400) + daySec // After seconds, comes various optional bits var pos = 19 var nanos: Int32 = 0 if value[pos] == period { // "." begins fractional seconds pos += 1 var digitValue = 100000000 while pos < value.count && value[pos] >= zero && value[pos] <= nine { nanos += Int32(digitValue * (value[pos] - zero)) digitValue /= 10 pos += 1 } } var seconds: Int64 = 0 // "Z" or "+" or "-" starts Timezone offset if pos >= value.count { throw JSONDecodingError.malformedTimestamp } else if value[pos] == plus || value[pos] == dash { if pos + 6 > value.count { throw JSONDecodingError.malformedTimestamp } let hourOffset = try fromAscii2(value[pos + 1], value[pos + 2]) let minuteOffset = try fromAscii2(value[pos + 4], value[pos + 5]) if hourOffset > Int(13) || minuteOffset > Int(59) || value[pos + 3] != colon { throw JSONDecodingError.malformedTimestamp } var adjusted: Int64 = t if value[pos] == plus { adjusted -= Int64(hourOffset) * Int64(3600) adjusted -= Int64(minuteOffset) * Int64(60) } else { adjusted += Int64(hourOffset) * Int64(3600) adjusted += Int64(minuteOffset) * Int64(60) } if adjusted < minTimestampSeconds || adjusted > maxTimestampSeconds { throw JSONDecodingError.malformedTimestamp } seconds = adjusted pos += 6 } else if value[pos] == letterZ { // "Z" indicator for UTC seconds = t pos += 1 } else { throw JSONDecodingError.malformedTimestamp } if pos != value.count { throw JSONDecodingError.malformedTimestamp } return (seconds, nanos) } private func formatTimestamp(seconds: Int64, nanos: Int32) -> String? { let (seconds, nanos) = normalizeForTimestamp(seconds: seconds, nanos: nanos) guard seconds >= minTimestampSeconds && seconds <= maxTimestampSeconds else { return nil } let (hh, mm, ss) = timeOfDayFromSecondsSince1970(seconds: seconds) let (YY, MM, DD) = gregorianDateFromSecondsSince1970(seconds: seconds) let dateString = "\(fourDigit(YY))-\(twoDigit(MM))-\(twoDigit(DD))" let timeString = "\(twoDigit(hh)):\(twoDigit(mm)):\(twoDigit(ss))" let nanosString = nanosToString(nanos: nanos) // Includes leading '.' if needed return "\(dateString)T\(timeString)\(nanosString)Z" } extension Google_Protobuf_Timestamp { /// Creates a new `Google_Protobuf_Timestamp` equal to the given number of /// seconds and nanoseconds. /// /// - Parameter seconds: The number of seconds. /// - Parameter nanos: The number of nanoseconds. public init(seconds: Int64 = 0, nanos: Int32 = 0) { self.init() self.seconds = seconds self.nanos = nanos } } extension Google_Protobuf_Timestamp: _CustomJSONCodable { mutating func decodeJSON(from decoder: inout JSONDecoder) throws { let s = try decoder.scanner.nextQuotedString() (seconds, nanos) = try parseTimestamp(s: s) } func encodedJSONString(options: JSONEncodingOptions) throws -> String { if let formatted = formatTimestamp(seconds: seconds, nanos: nanos) { return "\"\(formatted)\"" } else { throw JSONEncodingError.timestampRange } } } extension Google_Protobuf_Timestamp { /// Creates a new `Google_Protobuf_Timestamp` initialized relative to 00:00:00 /// UTC on 1 January 1970 by a given number of seconds. /// /// - Parameter timeIntervalSince1970: The `TimeInterval`, interpreted as /// seconds relative to 00:00:00 UTC on 1 January 1970. public init(timeIntervalSince1970: TimeInterval) { let sd = floor(timeIntervalSince1970) let nd = round((timeIntervalSince1970 - sd) * TimeInterval(nanosPerSecond)) let (s, n) = normalizeForTimestamp(seconds: Int64(sd), nanos: Int32(nd)) self.init(seconds: s, nanos: n) } /// Creates a new `Google_Protobuf_Timestamp` initialized relative to 00:00:00 /// UTC on 1 January 2001 by a given number of seconds. /// /// - Parameter timeIntervalSinceReferenceDate: The `TimeInterval`, /// interpreted as seconds relative to 00:00:00 UTC on 1 January 2001. public init(timeIntervalSinceReferenceDate: TimeInterval) { let sd = floor(timeIntervalSinceReferenceDate) let nd = round( (timeIntervalSinceReferenceDate - sd) * TimeInterval(nanosPerSecond)) // The addition of timeIntervalBetween1970And... is deliberately delayed // until the input is separated into an integer part and a fraction // part, so that we don't unnecessarily lose precision. let (s, n) = normalizeForTimestamp( seconds: Int64(sd) + Int64(Date.timeIntervalBetween1970AndReferenceDate), nanos: Int32(nd)) self.init(seconds: s, nanos: n) } /// Creates a new `Google_Protobuf_Timestamp` initialized to the same time as /// the given `Date`. /// /// - Parameter date: The `Date` with which to initialize the timestamp. public init(date: Date) { // Note: Internally, Date uses the "reference date," not the 1970 date. // We use it when interacting with Dates so that Date doesn't perform // any double arithmetic on our behalf, which might cost us precision. self.init( timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) } /// The interval between the timestamp and 00:00:00 UTC on 1 January 1970. public var timeIntervalSince1970: TimeInterval { return TimeInterval(self.seconds) + TimeInterval(self.nanos) / TimeInterval(nanosPerSecond) } /// The interval between the timestamp and 00:00:00 UTC on 1 January 2001. public var timeIntervalSinceReferenceDate: TimeInterval { return TimeInterval( self.seconds - Int64(Date.timeIntervalBetween1970AndReferenceDate)) + TimeInterval(self.nanos) / TimeInterval(nanosPerSecond) } /// A `Date` initialized to the same time as the timestamp. public var date: Date { return Date( timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate) } } private func normalizeForTimestamp( seconds: Int64, nanos: Int32 ) -> (seconds: Int64, nanos: Int32) { // The Timestamp spec says that nanos must be in the range [0, 999999999), // as in actual modular arithmetic. let s = seconds + Int64(div(nanos, nanosPerSecond)) let n = mod(nanos, nanosPerSecond) return (seconds: s, nanos: n) } public func + ( lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration ) -> Google_Protobuf_Timestamp { let (s, n) = normalizeForTimestamp(seconds: lhs.seconds + rhs.seconds, nanos: lhs.nanos + rhs.nanos) return Google_Protobuf_Timestamp(seconds: s, nanos: n) } public func + ( lhs: Google_Protobuf_Duration, rhs: Google_Protobuf_Timestamp ) -> Google_Protobuf_Timestamp { let (s, n) = normalizeForTimestamp(seconds: lhs.seconds + rhs.seconds, nanos: lhs.nanos + rhs.nanos) return Google_Protobuf_Timestamp(seconds: s, nanos: n) } public func - ( lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration ) -> Google_Protobuf_Timestamp { let (s, n) = normalizeForTimestamp(seconds: lhs.seconds - rhs.seconds, nanos: lhs.nanos - rhs.nanos) return Google_Protobuf_Timestamp(seconds: s, nanos: n) }
35.301205
90
0.669027
5b5f2cc919d8f1eb2e580a46a45c13be331cdd15
2,183
// // AppDelegate.swift // ImageSlideshow // // Created by Petr Zvoníček on 09/01/2015. // Copyright (c) 2015 Petr Zvoníček. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private 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:. } }
46.446809
285
0.75126
295601a0cae333b15ef86848bbef156d0ed442e9
1,833
// // TLSClientKeyExchangeTests.swift // SwiftTLS // // Created by Nico Schmidt on 27.03.15. // Copyright (c) 2015 Nico Schmidt. All rights reserved. // import XCTest @testable import SwiftTLS class TLSClientKeyExchangeTests: XCTestCase { static var allTests = [ ("test_writeTo__givesDataFromWhichTheSameMessageCanBeConstructed", test_writeTo__givesDataFromWhichTheSameMessageCanBeConstructed), ] func test_writeTo__givesDataFromWhichTheSameMessageCanBeConstructed() { class SUT : TLSClientKeyExchange { init!() { let encryptedPreMasterSecret : [UInt8] = [ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] var data = [UInt8]() data.write(TLSHandshakeType.clientKeyExchange.rawValue) data.writeUInt24(encryptedPreMasterSecret.count) data.write(UInt16(encryptedPreMasterSecret.count)) data.write(encryptedPreMasterSecret) super.init(inputStream: BinaryInputStream(data), context: TLSConnection()) } required init?(inputStream: InputStreamType, context: TLSConnection) { fatalError("init(inputStream:) has not been implemented") } } let context = TLSConnection() var data = [UInt8]() SUT().writeTo(&data, context: context) let msg2 = TLSClientKeyExchange(inputStream: BinaryInputStream(data), context: context)! var data2 = [UInt8]() msg2.writeTo(&data2, context: context) XCTAssertEqual(data, data2) } }
34.584906
139
0.597381
18e1b7325f65492bbcfad26f52bce3c43b8d8ec2
708
// // SearchViewControllerFactory.swift // BartenderApp // // Created by Christian Slanzi on 15.07.21. // import UIKit import CommonRouting protocol SearchViewControllerFactory { func makeSearchViewController() -> UIViewController } extension BartenderAppDependencies: SearchViewControllerFactory { func makeSearchViewController() -> UIViewController { let router = DefaultRouter(rootTransition: EmptyTransition()) let viewModel = SearchViewModel(router: router) viewModel.cocktailsLoader = makeCompositeDrinkLoader() let viewController = SearchViewController(viewModel: viewModel) router.root = viewController return viewController } }
27.230769
71
0.742938
1cef5c91d79421fcb888f86678d5ecf20d199a6b
397
// // CarInfoBasicView.swift // TeslaOrderForm // // Created by Craig Clayton on 2/13/20. // Copyright © 2020 Cocoa Academy. All rights reserved. // import SwiftUI struct CarInfoBasicView: View { var body: some View { Text("Car Info Basic View") } } struct CarInfoBasicView_Previews: PreviewProvider { static var previews: some View { CarInfoBasicView() } }
18.045455
56
0.670025
de9f32bce807ee052a393e00a925f2f06a5b31b4
170
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(FluentFirebirdDriverTests.allTests), ] } #endif
17
53
0.694118
e4b6d454f17c3b2bb5854eaa86742ddb5d68094c
2,113
// // SignerKeyXDR.swift // stellarsdk // // Created by Rogobete Christian on 13.02.18. // Copyright © 2018 Soneso. All rights reserved. // import Foundation public enum SignerKeyType: Int32 { case ed25519 = 0 case preAuthTx = 1 case hashX = 2 } public enum SignerKeyXDR: XDRCodable { case ed25519 (WrappedData32) case preAuthTx (WrappedData32) case hashX (WrappedData32) public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() let type = try container.decode(Int32.self) switch type { case SignerKeyType.ed25519.rawValue: self = .ed25519(try container.decode(WrappedData32.self)) case SignerKeyType.preAuthTx.rawValue: self = .preAuthTx(try container.decode(WrappedData32.self)) case SignerKeyType.hashX.rawValue: self = .hashX(try container.decode(WrappedData32.self)) default: self = .ed25519(try container.decode(WrappedData32.self)) } } private func type() -> Int32 { switch self { case .ed25519: return SignerKeyType.ed25519.rawValue case .preAuthTx: return SignerKeyType.preAuthTx.rawValue case .hashX: return SignerKeyType.hashX.rawValue } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(type()) switch self { case .ed25519 (let op): try container.encode(op) case .preAuthTx (let op): try container.encode(op) case .hashX (let op): try container.encode(op) } } } extension SignerKeyXDR: Equatable { public static func ==(lhs: SignerKeyXDR, rhs: SignerKeyXDR) -> Bool { switch (lhs, rhs) { case let (.ed25519(l), .ed25519(r)): return l == r case let (.preAuthTx(l), .preAuthTx(r)): return l == r case let (.hashX(l), .hashX(r)): return l == r default: return false } } }
28.173333
73
0.598675
2145fed531d3f2a52bdd6b45e711076eba340fc3
750
import XCTest import JTMiniProgram class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.862069
111
0.602667
4a202dbc86567f66e377d0ae200472cb01d663db
1,514
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation public class AKStringResonatorAudioUnit: AKAudioUnitBase { private(set) var fundamentalFrequency: AUParameter! private(set) var feedback: AUParameter! public override func createDSP() -> AKDSPRef { return createStringResonatorDSP() } public override init(componentDescription: AudioComponentDescription, options: AudioComponentInstantiationOptions = []) throws { try super.init(componentDescription: componentDescription, options: options) fundamentalFrequency = AUParameter( identifier: "fundamentalFrequency", name: "Fundamental Frequency (Hz)", address: AKStringResonatorParameter.fundamentalFrequency.rawValue, range: AKStringResonator.fundamentalFrequencyRange, unit: .hertz, flags: .default) feedback = AUParameter( identifier: "feedback", name: "Feedback (%)", address: AKStringResonatorParameter.feedback.rawValue, range: AKStringResonator.feedbackRange, unit: .generic, flags: .default) parameterTree = AUParameterTree.createTree(withChildren: [fundamentalFrequency, feedback]) fundamentalFrequency.value = AUValue(AKStringResonator.defaultFundamentalFrequency) feedback.value = AUValue(AKStringResonator.defaultFeedback) } }
37.85
100
0.690225
9b05209943e92ecf8ce6af4c1ae6af7084c94048
945
// // Copyright © 2022 Essential Developer. All rights reserved. // import Foundation import EssentialFeed import EssentialFeediOS import Combine extension ImageCommentsUIIntegrationTests { final class LoaderSpy { private var imageCommentsRequests = [PassthroughSubject<[ImageComment], Error>]() var loadCommentsCallCount: Int { return imageCommentsRequests.count } func loadPublisher() -> AnyPublisher<[ImageComment], Error> { let publisher = PassthroughSubject<[ImageComment], Error>() imageCommentsRequests.append(publisher) return publisher.eraseToAnyPublisher() } func completeImageCommentsLoading(with imageComments: [ImageComment] = [], at index: Int = 0) { imageCommentsRequests[index].send(imageComments) } func completeImageCommentsLoadingWithError(at index: Int = 0) { let error = NSError(domain: "an error", code: 0) imageCommentsRequests[index].send(completion: .failure(error)) } } }
27.794118
97
0.75873
fb87d34ea787de479236922cc66dc4677234d1de
2,201
// // AppDelegate.swift // RxKeychain // // Created by [email protected] on 05/13/2020. // Copyright (c) 2020 [email protected]. 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. 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.829787
285
0.754657
332a218783258016cec2bed2744721656a837fd0
2,097
// // ImageDownloader.swift // BrickKit // // Created by Ruben Cagnie on 9/15/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit private func _downloadImageAndSet(imageDownloader: ImageDownloader, on imageView: UIImageView, with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) { imageDownloader.downloadImage(with: imageURL) { (image, url) in guard imageURL == url else { return } NSOperationQueue.mainQueue().addOperationWithBlock { imageView.image = image completionHandler(image: image, url: url) } } } // Mark: - Image Downloader public protocol ImageDownloader: class { func downloadImage(with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) func downloadImageAndSet(on imageView: UIImageView, with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) } public extension ImageDownloader { func downloadImageAndSet(on imageView: UIImageView, with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) { _downloadImageAndSet(self, on: imageView, with: imageURL, onCompletion: completionHandler) } } public class NSURLSessionImageDownloader: ImageDownloader { public func downloadImageAndSet(on imageView: UIImageView, with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) { _downloadImageAndSet(self, on: imageView, with: imageURL, onCompletion: completionHandler) } public func downloadImage(with imageURL: NSURL, onCompletion completionHandler: ((image: UIImage, url: NSURL) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(imageURL, completionHandler: { (data, response, error) in guard let data = data where error == nil, let image = UIImage(data: data) else { return } completionHandler(image: image, url: imageURL) }).resume() } }
36.789474
190
0.687649
db942219f37cdfefaf5786f4bed048d2074d9d94
3,102
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import UIKit // MARK: CalendarViewDayMonthYearCell class CalendarViewDayMonthYearCell: CalendarViewDayMonthCell { override class var identifier: String { return "CalendarViewDayMonthYearCell" } override var isSelected: Bool { didSet { yearLabel.isHidden = isSelected } } override var isHighlighted: Bool { didSet { yearLabel.isHidden = isHighlighted } } let yearLabel: UILabel override init(frame: CGRect) { yearLabel = UILabel(frame: .zero) yearLabel.font = Fonts.caption1 yearLabel.textAlignment = .center yearLabel.textColor = Colors.Calendar.Day.textPrimary super.init(frame: frame) contentView.addSubview(yearLabel) } required init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } override func setup(textStyle: CalendarViewDayCellTextStyle, backgroundStyle: CalendarViewDayCellBackgroundStyle, selectionStyle: CalendarViewDayCellSelectionStyle, dateLabelText: String, indicatorLevel: Int) { preconditionFailure("Use setup(textStyle, backgroundStyle, selectionStyle, monthLabelText, dateLabelText, yearLabelText, indicatorLevel) instead") } override func setup(textStyle: CalendarViewDayCellTextStyle, backgroundStyle: CalendarViewDayCellBackgroundStyle, selectionStyle: CalendarViewDayCellSelectionStyle, monthLabelText: String, dateLabelText: String, indicatorLevel: Int) { preconditionFailure("Use setup(textStyle, backgroundStyle, selectionStyle, monthLabelText, dateLabelText, yearLabelText, indicatorLevel) instead") } // Only supports indicator levels from 0...4 func setup(textStyle: CalendarViewDayCellTextStyle, backgroundStyle: CalendarViewDayCellBackgroundStyle, selectionStyle: CalendarViewDayCellSelectionStyle, monthLabelText: String, dateLabelText: String, yearLabelText: String, indicatorLevel: Int) { super.setup(textStyle: textStyle, backgroundStyle: backgroundStyle, selectionStyle: selectionStyle, monthLabelText: monthLabelText, dateLabelText: dateLabelText, indicatorLevel: indicatorLevel) switch textStyle { case .primary: yearLabel.textColor = Colors.Calendar.Day.textPrimary case .secondary: yearLabel.textColor = Colors.Calendar.Day.textSecondary } yearLabel.text = yearLabelText } override func layoutSubviews() { super.layoutSubviews() let maxWidth = bounds.size.width let maxHeight = bounds.size.height monthLabel.frame = CGRect(x: 0.0, y: 0.0, width: maxWidth, height: maxHeight / 3.0) if !isSelected && !isHighlighted { dateLabel.frame = CGRect(x: 0.0, y: maxHeight / 3.0, width: maxWidth, height: maxHeight / 3.0) } yearLabel.frame = CGRect(x: 0.0, y: maxHeight * (2.0 / 3.0), width: maxWidth, height: maxHeight / 3.0) dotView.frame = .zero } }
38.296296
252
0.711799
9b875bdc6a0e84209d7028bfaee571ceec29cca4
1,129
// // ArrowNode.swift // Fenris // // Created by Wolfgang Schreurs on 13/06/2019. // Copyright © 2019 Wolftrail. All rights reserved. // import SpriteKit class ArrowNode: SKShapeNode { enum Direction { case left case right } init(size: CGSize, direction: Direction) { super.init() self.strokeColor = .white self.fillColor = .white self.lineWidth = 1 self.isAntialiased = true let path = CGMutablePath() switch direction { case .left: path.move(to: CGPoint(x: size.width, y: 0)) path.addLine(to: CGPoint(x: 0, y: size.height / 2)) path.addLine(to: CGPoint(x: size.width, y: size.height)) case .right: path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: size.width, y: size.height / 2)) path.addLine(to: CGPoint(x: 0, y: size.height)) } path.closeSubpath() self.path = path } required init?(coder aDecoder: NSCoder) { fatalError() } }
24.021277
72
0.531444
f7fc78b2027460e5c6331805822fdfa168cc6e5d
356
import UIKit import RxSwift import PlaygroundSupport // Necessary for asynchronous execution otherwise playground will terminate before they were finished. PlaygroundPage.current.needsIndefiniteExecution = true let bag = DisposeBag() Observable.from(["1", "2", "3"]) .debug("Foo") .subscribe(onNext: { element in print(element) }).disposed(by: bag)
25.428571
102
0.766854
791739e079372e785fd71d61a18f685640f689ad
2,109
import XCTest import CleanReversiAsync class CancellerTests: XCTestCase { func testCancel() { var count = 0 let canceller = Canceller { count += 1 } XCTAssertFalse(canceller.isCancelled) XCTAssertEqual(count, 0) canceller.cancel() XCTAssertTrue(canceller.isCancelled) XCTAssertEqual(count, 1) // Checks cancel operations are executed only once canceller.cancel() XCTAssertTrue(canceller.isCancelled) XCTAssertEqual(count, 1) } func testAddSubcanceller() { var count = 0 var subcount1 = 0 var subcount2 = 0 let canceller = Canceller { count += 1 } let subcanceller1 = Canceller { subcount1 += 10 } let subcanceller2 = Canceller { subcount2 += 100 } canceller.addSubcanceller(subcanceller1) canceller.addSubcanceller(subcanceller2) XCTAssertFalse(canceller.isCancelled) XCTAssertFalse(subcanceller1.isCancelled) XCTAssertFalse(subcanceller2.isCancelled) XCTAssertEqual(count, 0) XCTAssertEqual(subcount1, 0) XCTAssertEqual(subcount2, 0) canceller.cancel() XCTAssertTrue(canceller.isCancelled) XCTAssertTrue(subcanceller1.isCancelled) XCTAssertTrue(subcanceller2.isCancelled) XCTAssertEqual(count, 1) XCTAssertEqual(subcount1, 10) XCTAssertEqual(subcount2, 100) // Checks cancel operations are executed only once canceller.cancel() XCTAssertTrue(canceller.isCancelled) XCTAssertTrue(subcanceller1.isCancelled) XCTAssertTrue(subcanceller2.isCancelled) XCTAssertEqual(count, 1) XCTAssertEqual(subcount1, 10) XCTAssertEqual(subcount2, 100) // Adding after `canceller` is cancelled var subcount3 = 0 let subcanceller3 = Canceller { subcount3 += 1000 } canceller.addSubcanceller(subcanceller3) canceller.cancel() XCTAssertFalse(subcanceller3.isCancelled) XCTAssertEqual(subcount3, 0) } }
32.446154
59
0.65339
1c20c2f243f93119ad6ab8fc1de9cf39904f987e
200
// // RepoViewController.swift // iGithub // // Created by yfm on 2019/1/9. // Copyright © 2019年 com.yfm.www. All rights reserved. // import UIKit class RepoViewController: UIViewController { }
15.384615
55
0.7
099f1a794173a35b0a75401871d72a7362b59d76
123
main () { } // THIS-TEST-SHOULD-NOT-COMPILE // - no varargs in return value (int ...x) f(int x) "turbine" "0.0.2" "f";
12.3
42
0.569106
efd53fc73c37b94ac3349b1615b3fd29ea6a0c4d
1,559
// // BottomFadingPopupView.swift // FrontRow // // Created by WT-iOS on 3/9/19. // Copyright © 2019 WT-iOS. All rights reserved. // import Foundation import UIKit class BottomFadingPopupView: UIView { private struct Constants { static let bottomPopupFadeDuration = Double(1.5) } var popupViewModel: BottomFadingPopupViewModelProtocol? @IBOutlet weak var messageBoxParentView: UIView! @IBOutlet weak var messageLabel: UILabel! override func didMoveToSuperview() { super.didMoveToSuperview() bindViewModels() popupViewModel?.viewDidAppear() } // MARK: - Private private func bindViewModels() { messageLabel.text = popupViewModel?.customMessage messageBoxParentView.setNeedsLayout() messageBoxParentView.roundCorners() popupViewModel?.onAppearPopup = { [weak self] in DispatchQueue.main.async { self?.showPopup() } } popupViewModel?.onHidePopup = { [weak self] in DispatchQueue.main.async { self?.dismissPopup() } } } private func showPopup() { messageBoxParentView.fadeIn(duration: Constants.bottomPopupFadeDuration, delay: 0) } private func dismissPopup() { messageBoxParentView.fadeOut(duration: Constants.bottomPopupFadeDuration, delay: 0) { [weak self] (flag) in if flag { self?.removeFromSuperview() } } } }
25.557377
115
0.610006
48828b902cbbaf4056bb7d303cef5b10299e3749
799
// // EzsigntemplatepackageGetListV1ResponseAllOf.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif public struct EzsigntemplatepackageGetListV1ResponseAllOf: Codable, JSONEncodable, Hashable { public var mPayload: EzsigntemplatepackageGetListV1ResponseMPayload public init(mPayload: EzsigntemplatepackageGetListV1ResponseMPayload) { self.mPayload = mPayload } public enum CodingKeys: String, CodingKey, CaseIterable { case mPayload } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(mPayload, forKey: .mPayload) } }
24.212121
93
0.748436
211e632052c800907ffdb1938edff9c0dcaa2ee9
345
// // main.swift // algorithms // // Created by L on 2/15/18. // Copyright © 2018 Aleksey Egorov. All rights reserved. // import Foundation let sortAlgo = InsertionSort<Int>(); var a = Array<Int>(); for i in 1...10 { a.append(10 - i) } for i in 0...9 { print(a[i]); } sortAlgo.sort(a: &a) for i in 0...9 { print(a[i]); }
11.896552
57
0.571014
716793fba2ada896b9309b99898f22dc80280b7c
3,350
import Foundation import Quick import Nimble @testable import Kiosk import Moya import RxBlocking import RxSwift import Action private enum DefaultsKeys: String { case TokenKey = "TokenKey" case TokenExpiry = "TokenExpiry" } func clearDefaultsKeys(_ defaults: UserDefaults) { defaults.removeObject(forKey: DefaultsKeys.TokenKey.rawValue) defaults.removeObject(forKey: DefaultsKeys.TokenExpiry.rawValue) } func getDefaultsKeys(_ defaults: UserDefaults) -> (key: String?, expiry: Date?) { let key = defaults.object(forKey: DefaultsKeys.TokenKey.rawValue) as! String? let expiry = defaults.object(forKey: DefaultsKeys.TokenExpiry.rawValue) as! Date? return (key: key, expiry: expiry) } func setDefaultsKeys(_ defaults: UserDefaults, key: String?, expiry: Date?) { defaults.set(key, forKey: DefaultsKeys.TokenKey.rawValue) defaults.set(expiry, forKey: DefaultsKeys.TokenExpiry.rawValue) } func yearFromDate(_ date: Date) -> Int { let calendar = Calendar(identifier: Calendar.Identifier.gregorian) return (calendar as NSCalendar).components(.year, from: date).year! } @objc class TestClass: NSObject { } // Necessary since UIImage(named:) doesn't work correctly in the test bundle extension UIImage { class func testImage(named name: String, ofType type: String) -> UIImage! { let bundle = Bundle(for: Swift.type(of: TestClass())) let path = bundle.path(forResource: name, ofType: type) return UIImage(contentsOfFile: path!) } } func testArtwork() -> Artwork { return Artwork.fromJSON(["id": "red", "title" : "Rose Red", "date": "June 11th 2014", "blurb": "Pretty good", "artist": ["id" : "artistDee", "name": "Dee Emm"], "images": [ ["id" : "image_id", "image_url" : "http://example.com/:version.jpg", "image_versions" : ["large"], "aspect_ratio" : 1.508, "tile_base_url" : "http://example.com", "tile_size" : 1] ]]) } let testAuctionID = "AUCTION" func testSaleArtwork() -> SaleArtwork { let saleArtwork = SaleArtwork(id: "12312313", artwork: testArtwork(), currencySymbol: "£") saleArtwork.auctionID = testAuctionID return saleArtwork } func testBidDetails() -> BidDetails { return BidDetails(saleArtwork: testSaleArtwork(), paddleNumber: "1111", bidderPIN: "2222", bidAmountCents: 123456, auctionID: testAuctionID) } class StubFulfillmentController: FulfillmentController { lazy var bidDetails: BidDetails = { () -> BidDetails in let bidDetails = testBidDetails() bidDetails.setImage = { (_, imageView) -> () in imageView.image = loadingViewControllerTestImage } return bidDetails }() var auctionID: String! = "" var xAccessToken: String? } // TODO: Move into Action pod? enum TestError: String { case Default } extension TestError: Swift.Error { } func emptyAction() -> CocoaAction { return CocoaAction { _ in Observable.empty() } } func neverAction() -> CocoaAction { return CocoaAction { _ in Observable.never() } } func errorAction(_ error: Swift.Error = TestError.Default) -> CocoaAction { return CocoaAction { _ in Observable.error(error) } } func disabledAction() -> CocoaAction { return CocoaAction(enabledIf: Observable.just(false)) { _ in Observable.empty() } }
29.130435
144
0.686866
e50b4bb92a40bd2d388b1b523c1bac67926e690b
1,222
// // PreviewViewModel.swift // CardzApp // // Created by Антон Тимонин on 22.12.2021. // import Foundation import Erebor /// Представление экрана превьюшных слов слов. struct PreviewViewModel: Equatable { /// Заголовок уведомления. public let wordz: String public let wordzExamples: [String] public let transcription: String? public let translations: [String] public let type: ArkenstoneTypeWord public let languageVersion: SilverTypeTranslation public let displayedCount: Int64 /// Инициализирует вью модель. /// - Parameters: /// - title: Слово. /// - translations: Перевод слова. public init( wordz: String, wordzExamples: [String], transcription: String?, translations: [String], type: ArkenstoneTypeWord, languageVersion: SilverTypeTranslation, displayedCount: Int64 ) { self.wordz = wordz self.wordzExamples = wordzExamples self.transcription = transcription self.translations = translations self.type = type self.languageVersion = languageVersion self.displayedCount = displayedCount } }
23.5
53
0.641571
e8b1957bbbd983464bbedc335ae00bf666bc3fa5
3,662
import Foundation // Inspired by https://gist.github.com/mbuchetics/c9bc6c22033014aa0c550d3b4324411a public struct JSONCodingKeys: CodingKey { public var stringValue: String public init?(stringValue: String) { self.stringValue = stringValue } public var intValue: Int? public init?(intValue: Int) { self.init(stringValue: "\(intValue)") self.intValue = intValue } } public extension KeyedDecodingContainer { func decode(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any> { let container = try self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any>? { guard contains(key) else { return nil } return try decode(type, forKey: key) } func decode(_ type: Array<Any>.Type, forKey key: K) throws -> Array<Any> { var container = try self.nestedUnkeyedContainer(forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: Array<Any>.Type, forKey key: K) throws -> Array<Any>? { guard contains(key) else { return nil } return try decode(type, forKey: key) } func decode(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> { var dictionary = Dictionary<String, Any>() for key in allKeys { if let boolValue = try? decode(Bool.self, forKey: key) { dictionary[key.stringValue] = boolValue } else if let stringValue = try? decode(String.self, forKey: key) { dictionary[key.stringValue] = stringValue } else if let intValue = try? decode(Int.self, forKey: key) { dictionary[key.stringValue] = intValue } else if let doubleValue = try? decode(Double.self, forKey: key) { dictionary[key.stringValue] = doubleValue // } else if let fileMetaData = try? decode(Asset.FileMetadata.self, forKey: key) { // dictionary[key.stringValue] = fileMetaData // Custom contentful type. } else if let nestedDictionary = try? decode(Dictionary<String, Any>.self, forKey: key) { dictionary[key.stringValue] = nestedDictionary } else if let nestedArray = try? decode(Array<Any>.self, forKey: key) { dictionary[key.stringValue] = nestedArray } } return dictionary } } public extension UnkeyedDecodingContainer { mutating func decode(_ type: Array<Any>.Type) throws -> Array<Any> { var array: [Any] = [] while isAtEnd == false { if let value = try? decode(Bool.self) { array.append(value) } else if let value = try? decode(Double.self) { array.append(value) } else if let value = try? decode(String.self) { array.append(value) } else if let nestedDictionary = try? decode(Dictionary<String, Any>.self) { array.append(nestedDictionary) } else if let nestedArray = try? decode(Array<Any>.self) { array.append(nestedArray) } } return array } mutating func decode(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> { let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self) return try nestedContainer.decode(type) } }
37.752577
114
0.603495
690ebf1340812ae3a7443899e96b7c9c503ca017
1,985
// // SwifterTestsHttpResponseBody.swift // Swifter // import XCTest @testable import Swifter class SwifterTestsHttpResponseBody: XCTestCase { func testDictionaryAsJSONPayload() { verify(input: ["key": "value"], output: "{\"key\":\"value\"}") verify(input: ["key": ["value1", "value2", "value3"]], output: "{\"key\":[\"value1\",\"value2\",\"value3\"]}") } func testArrayAsJSONPayload() { verify(input: ["key", "value"], output: "[\"key\",\"value\"]") verify(input: ["value1", "value2", "value3"], output: "[\"value1\",\"value2\",\"value3\"]") } func testNSDictionaryAsJSONPayload() { verify(input: ["key": "value"] as NSDictionary, output: "{\"key\":\"value\"}") verify(input: ["key": ["value1", "value2", "value3"]] as NSDictionary, output: "{\"key\":[\"value1\",\"value2\",\"value3\"]}") } func testNSArrayAsJSONPayload() { verify(input: ["key", "value"] as NSArray, output: "[\"key\",\"value\"]") verify(input: ["value1", "value2", "value3"] as NSArray, output: "[\"value1\",\"value2\",\"value3\"]") } private func verify(input: Any, output expectedOutput: String, line: UInt = #line) { let response: HttpResponseBody = .json(input) guard let writer = response.content().1 else { XCTFail(line: line) return } do { let mockWriter = MockWriter() try writer(mockWriter) let output = String(decoding: mockWriter.data, as: UTF8.self) XCTAssertEqual(output, expectedOutput, line: line) } catch { XCTFail(line: line) } } } private class MockWriter: HttpResponseBodyWriter { var data = Data() func write(_ file: String.File) throws { } func write(_ data: [UInt8]) throws { } func write(_ data: ArraySlice<UInt8>) throws { } func write(_ data: NSData) throws { } func write(_ data: Data) throws { self.data = data } }
33.644068
134
0.579345
f906f6581d67493f00f50858cc5a1d3518432192
2,693
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore // ======================================================= internal final class LightTheme: NSObject, Themable { let name = "Light" internal func color(type type: ColorType) -> UIColor { switch type { case .CellBackgroundColor: return UIColor.whiteColor() case .PrimaryTextColor: return UIColor(white: 0.1, alpha: 1.0) case .SecondaryTextColor: return UIColor(white: 0.35, alpha: 1.0) case .DisabledTextColor: return UIColor(white: 0.75, alpha: 1.0) case .TintColor: return UIColor(red: 75.0/255.0, green: 133.0/255.0, blue: 17.0/255.0, alpha: 1.0) case .ViewBackgroundColor: return UIColor(white: 0.95, alpha: 1.0) case .DividerColor: return UIColor(white: 0.75, alpha: 1.0) } } internal func font(type type: FontType) -> UIFont { switch type { case .Bold(let size): return Font.bold(size: size) case .Regular(let size): return Font.regular(size: size) case .Italic(let size): return Font.italic(size: size) } } } internal final class DarkTheme: NSObject, Themable { let name = "Dark" internal func color(type type: ColorType) -> UIColor { switch type { case .CellBackgroundColor: return UIColor(white: 0.20, alpha: 1.0) case .PrimaryTextColor: return UIColor(white: 0.85, alpha: 1.0) case .SecondaryTextColor: return UIColor(white: 0.65, alpha: 1.0) case .DisabledTextColor: return UIColor(white: 0.40, alpha: 1.0) case .TintColor: return UIColor(red: 75.0/255.0, green: 133.0/255.0, blue: 17.0/255.0, alpha: 1.0) case .ViewBackgroundColor: return UIColor(white: 0.1, alpha: 1.0) case .DividerColor: return UIColor(white: 0.35, alpha: 1.0) } } internal func font(type type: FontType) -> UIFont { switch type { case .Bold(let size): return Font.bold(size: size) case .Regular(let size): return Font.regular(size: size) case .Italic(let size): return Font.italic(size: size) } } }
28.052083
93
0.484961
dbbdcecd241a3aee4cf359cc48f8aa52509b4070
12,692
// // HOOPLoginVC.swift // hoopeu // 登录 // Created by gouyz on 2019/2/18. // Copyright © 2019 gyz. All rights reserved. // import UIKit import MBProgressHUD import CocoaMQTT import SwiftyJSON class HOOPLoginVC: GYZBaseVC { /// 是否有网络 var isNetWork: Bool = false override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "登 录" self.view.backgroundColor = kWhiteColor let rightBtn = UIButton(type: .custom) rightBtn.setTitle("忘记密码", for: .normal) rightBtn.titleLabel?.font = k15Font rightBtn.setTitleColor(kBlueFontColor, for: .normal) rightBtn.frame = CGRect.init(x: 0, y: 0, width: kTitleHeight, height: kTitleHeight) rightBtn.addTarget(self, action: #selector(onClickRightBtn), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn) setupUI() phoneTxtFiled.text = userDefaults.string(forKey: "phone") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if mqtt == nil { mqttSetting() } } /// 创建UI func setupUI(){ view.addSubview(desLab) view.addSubview(codeLab) view.addSubview(phoneTxtFiled) view.addSubview(lineView) view.addSubview(pwdTxtFiled) view.addSubview(seePwdBtn) view.addSubview(lineView1) view.addSubview(registerBtn) view.addSubview(nextBtn) desLab.snp.makeConstraints { (make) in make.top.equalTo(kTitleAndStateHeight * 2) make.left.equalTo(kMargin) make.right.equalTo(-kMargin) make.height.equalTo(kTitleAndStateHeight) } phoneTxtFiled.snp.makeConstraints { (make) in make.right.equalTo(-kMargin) make.left.equalTo(codeLab.snp.right).offset(kMargin) make.top.equalTo(desLab.snp.bottom).offset(kTitleAndStateHeight) make.height.equalTo(50) } codeLab.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.centerY.equalTo(phoneTxtFiled) make.size.equalTo(CGSize.init(width: 60, height: 30)) } lineView.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.right.equalTo(phoneTxtFiled) make.top.equalTo(phoneTxtFiled.snp.bottom) make.height.equalTo(klineWidth) } pwdTxtFiled.snp.makeConstraints { (make) in make.left.height.equalTo(phoneTxtFiled) make.top.equalTo(lineView.snp.bottom) make.right.equalTo(seePwdBtn.snp.left).offset(-kMargin) } seePwdBtn.snp.makeConstraints { (make) in make.centerY.equalTo(pwdTxtFiled) make.right.equalTo(-kMargin) make.size.equalTo(CGSize.init(width: 20, height: 20)) } lineView1.snp.makeConstraints { (make) in make.left.right.height.equalTo(lineView) make.top.equalTo(pwdTxtFiled.snp.bottom) } registerBtn.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.bottom.equalTo(-kTitleHeight) make.size.equalTo(CGSize.init(width: kTitleHeight, height: kTitleHeight)) } nextBtn.snp.makeConstraints { (make) in make.right.equalTo(-kMargin) make.bottom.size.equalTo(registerBtn) } } /// lazy var desLab : UILabel = { let lab = UILabel() lab.textColor = kBlackFontColor lab.font = k18Font lab.textAlignment = .center lab.text = "\"欢迎回来\"" return lab }() /// 区号代码 lazy var codeLab : UILabel = { let lab = UILabel() lab.textColor = kWhiteColor lab.backgroundColor = kBlueFontColor lab.font = k15Font lab.cornerRadius = 15 lab.textAlignment = .center lab.text = "+86" lab.addOnClickListener(target: self, action: #selector(onClickedSelectCode)) return lab }() /// 手机号 lazy var phoneTxtFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.keyboardType = .numberPad textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "请输入手机号" return textFiled }() /// 分割线 lazy var lineView : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() /// 密码 lazy var pwdTxtFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.isSecureTextEntry = true textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "请输入密码" return textFiled }() /// 查看密码 lazy var seePwdBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.setImage(UIImage.init(named: "icon_no_see_pwd"), for: .normal) btn.setImage(UIImage.init(named: "icon_see_pwd"), for: .selected) btn.addTarget(self, action: #selector(clickedSeePwdBtn), for: .touchUpInside) return btn }() /// 分割线 lazy var lineView1 : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() /// 注册 lazy var registerBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.setTitleColor(kBlueFontColor, for: .normal) btn.setTitle("注册", for: .normal) btn.titleLabel?.font = k18Font btn.addTarget(self, action: #selector(clickedRegisterBtn), for: .touchUpInside) return btn }() /// 下一步 lazy var nextBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.setImage(UIImage.init(named: "icon_next_btn"), for: .normal) btn.addTarget(self, action: #selector(clickedNextBtn), for: .touchUpInside) return btn }() /// 忘记密码 @objc func onClickRightBtn(){ let vc = HOOPRegisterPhoneVC() vc.isModifyPwd = true navigationController?.pushViewController(vc, animated: true) } /// 显示密码 @objc func clickedSeePwdBtn(){ seePwdBtn.isSelected = !seePwdBtn.isSelected pwdTxtFiled.isSecureTextEntry = !seePwdBtn.isSelected } /// 注册 @objc func clickedRegisterBtn(){ let vc = HOOPRegisterPhoneVC() vc.isModifyPwd = false navigationController?.pushViewController(vc, animated: true) } /// 下一步 @objc func clickedNextBtn(){ // goLinkPower() hiddenKeyBoard() if !validPhoneNO() { return } if pwdTxtFiled.text!.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请输入密码") return } requestLogin() } /// 连接电源 func goLinkPower(){ // let vc = HOOPLinkPowerVC() let vc = HOOPPhoneNetWorkVC() navigationController?.pushViewController(vc, animated: true) } func goHomeVC(){ let menuContrainer = FWSideMenuContainerViewController.container(centerViewController: GYZMainTabBarVC(), centerLeftPanViewWidth: 20, centerRightPanViewWidth: 20, leftMenuViewController: HOOPLeftMenuVC(), rightMenuViewController: nil) menuContrainer.leftMenuWidth = kLeftMenuWidth KeyWindow.rootViewController = menuContrainer } /// 选择地区代码 @objc func onClickedSelectCode(){ UsefulPickerView.showSingleColPicker("选择地区代码", data: PHONECODE, defaultSelectedIndex: nil) {[weak self] (index, value) in self?.codeLab.text = value } } /// 判断手机号是否有效 /// /// - Returns: func validPhoneNO() -> Bool{ if phoneTxtFiled.text!.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请输入手机号") return false } if phoneTxtFiled.text!.isMobileNumber(){ return true }else{ MBProgressHUD.showAutoDismissHUD(message: "请输入正确的手机号") return false } } /// 隐藏键盘 func hiddenKeyBoard(){ phoneTxtFiled.resignFirstResponder() pwdTxtFiled.resignFirstResponder() } /// 登录 func requestLogin(){ if !GYZTool.checkNetWork() { return } weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("login/login", parameters: ["phone":phoneTxtFiled.text!,"password":pwdTxtFiled.text!], success: { (response) in weakSelf?.hud?.hide(animated: true) GYZLog(response) if response["code"].intValue == kQuestSuccessTag{//请求成功 userDefaults.set(true, forKey: kIsLoginTagKey)//是否登录标识 let data = response["data"] userDefaults.set((weakSelf?.phoneTxtFiled.text)!, forKey: "phone")//账号 userDefaults.set(data["token"].stringValue, forKey: "token") JPUSHService.setAlias(data["alias"].stringValue, completion: { (iResCode, iAlias, seq) in }, seq: 0) if !(data["devId"].string?.isEmpty)!{/// 设备不为空,检测网络 userDefaults.set(data["devId"].stringValue, forKey: "devId") // weakSelf?.sendMqttCmd() // weakSelf?.startSMSWithDuration(duration: 3) weakSelf?.goHomeVC() }else{ weakSelf?.goLinkPower() } }else{ MBProgressHUD.showAutoDismissHUD(message: response["msg"].stringValue) } }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } /// 倒计时 /// /// - Parameter duration: 倒计时时间 func startSMSWithDuration(duration:Int){ var times = duration let timer:DispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.global()) timer.setEventHandler { if times > 0{ DispatchQueue.main.async(execute: { times -= 1 }) } else{ DispatchQueue.main.async(execute: { if !self.isNetWork{// 没有网络,去配网 self.hud?.hide(animated: true) MBProgressHUD.showAutoDismissHUD(message: "网络未连接,请重新配置网络") self.goLinkPower() } timer.cancel() }) } } // timer.scheduleOneshot(deadline: .now()) timer.schedule(deadline: .now(), repeating: .seconds(1), leeway: .milliseconds(100)) timer.resume() // 在调用DispatchSourceTimer时, 无论设置timer.scheduleOneshot, 还是timer.scheduleRepeating代码 不调用cancel(), 系统会自动调用 // 另外需要设置全局变量引用, 否则不会调用事件 } /// 检测网络信息查询 func sendMqttCmd(){ createHUD(message: "检测网络中...") let paramDic:[String:Any] = ["device_id":userDefaults.string(forKey: "devId") ?? "","user_id":userDefaults.string(forKey: "phone") ?? "","msg_type":"room_list_query","app_interface_tag":""] mqtt?.publish("hoopeu_device", withString: GYZTool.getJSONStringFromDictionary(dictionary: paramDic), qos: .qos1) } /// 重载CocoaMQTTDelegate override func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) { if ack == .accept { mqtt.subscribe("hoopeu_app", qos: CocoaMQTTQOS.qos1) } } override func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) { super.mqtt(mqtt, didReceiveMessage: message, id: id) if let data = message.string { let result = JSON.init(parseJSON: data) let phone = result["user_id"].stringValue let type = result["msg_type"].stringValue if let tag = result["app_interface_tag"].string{ if tag.hasPrefix("system_"){ return } } if type == "room_list_query_re" && phone == userDefaults.string(forKey: "phone"){ self.isNetWork = true self.hud?.hide(animated: true) self.goHomeVC() } } } }
33.755319
242
0.575875
64b87fc9f74a812c5fbc137338857860409cb54c
408
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "Triff", products: [ .library( name: "Triff", targets: ["Triff"]), ], dependencies: [], targets: [ .target( name: "Triff", dependencies: []), .testTarget( name: "TriffTests", dependencies: ["Triff"]), ] )
19.428571
37
0.470588
d758ecedf9d0dfe4c58dafe1b83afce50633fcab
4,078
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit /// A generic protocol which exposes the properties used by Apple's CKQueryOperation. public protocol CKQueryOperationProtocol: CKDatabaseOperationProtocol, CKResultsLimit, CKDesiredKeys { /// - returns: the query to execute var query: Query? { get set } /// - returns: the query cursor var cursor: QueryCursor? { get set } /// - returns: the zone ID var zoneID: RecordZoneID? { get set } /// - returns: a record fetched block var recordFetchedBlock: ((Record) -> Void)? { get set } /// - returns: the query completion block var queryCompletionBlock: ((QueryCursor?, Error?) -> Void)? { get set } } public struct QueryError<QueryCursor>: CloudKitError { public let underlyingError: Error public let cursor: QueryCursor? } extension CKQueryOperation: CKQueryOperationProtocol, AssociatedErrorProtocol { // The associated error type public typealias AssociatedError = QueryError<QueryCursor> } extension CKProcedure where T: CKQueryOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { public var query: T.Query? { get { return operation.query } set { operation.query = newValue } } public var cursor: T.QueryCursor? { get { return operation.cursor } set { operation.cursor = newValue } } public var zoneID: T.RecordZoneID? { get { return operation.zoneID } set { operation.zoneID = newValue } } public var recordFetchedBlock: CloudKitProcedure<T>.QueryRecordFetchedBlock? { get { return operation.recordFetchedBlock } set { operation.recordFetchedBlock = newValue } } func setQueryCompletionBlock(_ block: @escaping CloudKitProcedure<T>.QueryCompletionBlock) { operation.queryCompletionBlock = { [weak self] cursor, error in if let strongSelf = self, let error = error { strongSelf.append(fatalError: QueryError(underlyingError: error, cursor: cursor)) } else { block(cursor) } } } } extension CloudKitProcedure where T: CKQueryOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { /// A typealias for the block types used by CloudKitOperation<CKQueryOperation> public typealias QueryRecordFetchedBlock = (T.Record) -> Void /// A typealias for the block types used by CloudKitOperation<CKQueryOperation> public typealias QueryCompletionBlock = (T.QueryCursor?) -> Void /// - returns: the query public var query: T.Query? { get { return current.query } set { current.query = newValue appendConfigureBlock { $0.query = newValue } } } /// - returns: the query cursor public var cursor: T.QueryCursor? { get { return current.cursor } set { current.cursor = newValue appendConfigureBlock { $0.cursor = newValue } } } /// - returns: the zone ID public var zoneID: T.RecordZoneID? { get { return current.zoneID } set { current.zoneID = newValue appendConfigureBlock { $0.zoneID = newValue } } } /// - returns: a block for each record fetched public var recordFetchedBlock: QueryRecordFetchedBlock? { get { return current.recordFetchedBlock } set { current.recordFetchedBlock = newValue appendConfigureBlock { $0.recordFetchedBlock = newValue } } } /** Before adding the CloudKitOperation instance to a queue, set a completion block to collect the results in the successful case. Setting this completion block also ensures that error handling gets triggered. - parameter block: a QueryCompletionBlock block */ public func setQueryCompletionBlock(block: @escaping QueryCompletionBlock) { appendConfigureBlock { $0.setQueryCompletionBlock(block) } } }
31.612403
125
0.660863
1c7a4f80fdf2e28ba994c92b815df674d3a26f65
9,454
// // Command.swift // CommandCougar // // Copyright (c) 2017 Surf & Neptune LLC (http://surfandneptune.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A struct used to describe a command entry for evaluation and help menu public struct Command: CommandIndexable { /// A callback type used to notify after evaluation public typealias Callback = ((CommandEvaluation) throws -> Void) /// The name of this command public var name: String /// The overview of this command used in the help menu public var overview: String /// The options this command is allowed to take in public var options: [Option] /// The parameters this command is allowd to take in public var parameters: [Parameter] /// The subCommands this parameter is allowd to take in public var subCommands: [Command] /// The callback used by PerformCallbacks when this command is evaulated public var callback: Callback? /// How much padding the help menu uses public var helpPadding: Int = 30 /// The minimum number of parameters allowed internal var minParameterCount: Int { return parameters.filter{ $0.isRequired }.count } /// The maximum number of parameters allowed internal var maxParameterCount: Int { return parameters.count } /// Command Init. This init allows for parameters and not /// subcommands since a command can not have both subcommands and parameters /// /// - Parameters: /// - name: The name of this command /// - overview: The overview used in the help menu /// - callback: The callback which is called when the command evaluates to true /// - options: Possible options this command is allow to take in /// - parameters: Possible parameters this command is allowed to take in public init( name: String, overview: String, callback: Callback?, options: [Option], parameters: [Parameter]) { self.name = name self.overview = overview self.callback = callback self.options = options + [Option.help] self.subCommands = [] self.parameters = parameters } /// Command Init. This init allows for subCommands and not /// parameters since a command can not have both subcommands and parameters /// /// - Parameters: /// - name: The name of this command /// - overview: The overview used in the help menu /// - callback: The callback which is called when the command evaluates to true /// - options: Possible options this command is allow to take in /// - subCommands: Possible subCommands this command is allowed to take in public init( name: String, overview: String, callback: Callback?, options: [Option], subCommands: [Command]) { self.name = name self.overview = overview self.callback = callback self.options = options + [Option.help] self.parameters = [] self.subCommands = subCommands } /// Creates the usage string for this command given an array of supercommands. A Command does not /// keep a link to its supercommands, so it is dynamically generated at run time. /// /// - Parameter superCommands: The array of super commands /// - Returns: The usage string for this command public func usage(superCommands: [Command] = []) -> String { let fullCommandName = superCommands.reduce("", { $0 + "\($1.name) " } ).appending(name) let optionString = options.isEmpty ? "" : " [options] " let parameterString = parameters.isEmpty ? "" : parameters.reduce("", { $0 + "\($1.formattedValue) " }) let subCommandString = subCommands.isEmpty ? "" : "subcommand" return "\(fullCommandName)\(optionString)\(parameterString)\(subCommandString)" } /// Creates the help text string for this command given an array of supercommands. The supercommands /// are used to dynamcially generate the usuage text. /// /// - Parameter superCommands: The array of super commands /// - Returns: The help text string for this command public func help(superCommands: [Command] = []) -> String { let commandHelp = subCommands.isEmpty ? "" : subCommands .map { "\($0.name.padding(toLength: helpPadding, withPad: " ", startingAt: 0))" + "\($0.overview)" } .reduce("SUBCOMMANDS:", { "\($0)\n \($1)" }) + "\n\n" let optionHelp = options.isEmpty ? "" : options .map { $0.helpText } .reduce("OPTIONS:", { "\($0)\n \($1)" }) return "OVERVIEW: \(overview)\n\nUSAGE: \(usage(superCommands: superCommands))\n\n\(commandHelp)\(optionHelp)" } /// Ensures that the Command structure is valid /// /// - Throws: Error if the Command structure is not valid public func validate() throws { // A command can not have both subcommands and parameters if parameters.count > 0 && subCommands.count > 0 { throw CommandCougar.Errors.validate("A command can not have both subcommands and parameters.") } // Subcommand names must be unique let subCommandNames = subCommands.map { $0.name } if subCommandNames.count != Set(subCommandNames).count { throw CommandCougar.Errors.validate("Duplicate subCommand(s) for command \(name). Subcommand names must be unique.") } // Option flags must be unique i.e. they can't have the same shortNames or longNames let shorts = options.compactMap ({ $0.flag.shortName }) let longs = options.compactMap ({ $0.flag.longName }) if shorts.count != Set(shorts).count, longs.count != Set(longs).count { throw CommandCougar.Errors.validate("Duplicate option flag(s) for command \(name). Option flags must be unique.") } } /// Strip the first arg and subevaluate. Prints help text if help option is present. /// /// - Parameter args: The command line arugments usually from CommandLine.arguments /// - Returns: An evaluated command. The evaluation contains a subevaluation for any subCommand parsed /// - Throws: Error if arguments are malformed or this command does not support option / parameter public func evaluate(arguments: [String]) throws -> CommandEvaluation { let commandEvaluation = try subEvaluate(arguments:arguments.dropFirst().map { $0 }) // If help option is present in the command evaluation, print help. if commandEvaluation.options.contains(where: { $0.flag == Option.help.flag }) { print(help(superCommands: [])) return commandEvaluation } // If help options is present in a subcommand evaluation, print help. Keep track of the supercommands // so that the usasge in the help text can be dynamically generated. var current = commandEvaluation var superCommands = [Command]() superCommands.append(current.describer) while let next = current.subEvaluation { current = next if current.options.contains(where: { $0.flag == Option.help.flag }) { print(current.describer.help(superCommands: superCommands)) } superCommands.append(current.describer) } return commandEvaluation } /// Evaluates this command and all subcommands againts a set of arguments. /// This will generate a evaluation filled out with the options and parameters /// passed into each /// /// - Parameter args: The command line arugments usually from CommandLine.arguments /// - Returns: A evaulated command. The evaluation contains a subevaluation for any subCommand parsed /// - Throws: Error if arguments is malformed or this command does not support option / parameter private func subEvaluate(arguments: [String]) throws -> CommandEvaluation { try validate() var evaluation = CommandEvaluation(describer: self) var argsList = arguments while !argsList.isEmpty { let next = argsList.removeFirst() if let subCommand = subCommands.first(where: { $0.name == next }) { evaluation.subEvaluation = try subCommand.subEvaluate(arguments: argsList) try evaluation.validate() return evaluation } else if let option = OptionEvaluation(string: next) { // If option is help, stop evaluating if option.flag == Option.help.flag { evaluation.options.append(option) return evaluation } evaluation.options.append(option) } else { evaluation.parameters.append(next) } } try evaluation.validate() return evaluation } /// A subscript to access this commands subcommand by name /// /// - Parameter commandName: The name of the subcommand public subscript(subCommand: String) -> Command? { get { return subCommands[subCommand] } set { subCommands[subCommand] = newValue } } }
36.361538
119
0.709224
e2bebb67ff8ab3fa51357bd1b7c76f4b893add95
529
// // ViewController.swift // BlinkingLabel // // Created by Gagan Vishal Mishra on 08/14/2019. // Copyright (c) 2019 Gagan Vishal Mishra. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
21.16
80
0.678639
38cf9c2aee591bb3461944597e822c13104c5782
2,822
// // AppDelegate.swift // OBInjectorSwiftDemo // // Created by Rene Pirringer on 26.01.16. // Copyright © 2016 Rene Pirringer. 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. OBInjectorController.configureInjector({ (injector:OBPropertyInjector!) -> Void in let service = MyService() injector.registerProperty("myService", withInstance:service) injector.registerProperty("currentDate", withBlock:{ return NSDate(); }); let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle; dateFormatter.timeStyle = .MediumStyle; injector.registerProperty("dateFormatter", withInstance:dateFormatter) }) NSLog("rootViewController: \(window?.rootViewController)") let navigationController:UINavigationController = window?.rootViewController as! UINavigationController OBInjectorController.injectDependenciesTo(navigationController.topViewController) 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:. } }
38.657534
279
0.779589
4653be238dd8ee125e9cbbe455989514465cf838
392
import UIKit import Foundation class InteractionsDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } }
24.5
100
0.706633
796e02c4dcfb1cd00b5ad664b748cd413da266de
546
// Copyright 2018 ProximaX Limited. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. import Foundation /// An abstract message class that serves as the base class of all message types. public class Message { // MARK: Properties /// Message type. public let type: MessageType /// Returns message payload. public let payload: [UInt8] init(type: MessageType, payload: [UInt8]) { self.type = type self.payload = payload } }
27.3
81
0.68315
feaf573bffa6c2268d6ee57d99884e21e93b4a6f
494
// // TransaksiLayanan.swift // Kouvee // // Created by Ryan Octavius on 24/04/20. // Copyright © 2020 Ryan. All rights reserved. // import Foundation import UIKit class TransaksiLayananCollection: UICollectionViewCell{ @IBOutlet weak var labelID: UILabel! @IBOutlet weak var labelTanggal: UILabel! @IBOutlet weak var labelDiskon: UILabel! @IBOutlet weak var labelTotal: UILabel! @IBOutlet weak var labelStatus: UILabel! @IBOutlet weak var labelProgres: UILabel! }
26
55
0.734818
e057342b4cd0066fbecc30ee9bf90361426fa335
1,222
// // DestinationReviewRatingCell.swift // CascadingTableDelegate // // Created by Ricardo Pramana Suranta on 11/1/16. // Copyright © 2016 Ricardo Pramana Suranta. All rights reserved. // import UIKit class DestinationReviewRatingCell: UITableViewCell { @IBOutlet fileprivate var starImageViews: [UIImageView]? override func awakeFromNib() { super.awakeFromNib() configure(rating: 0) } override func prepareForReuse() { super.prepareForReuse() configure(rating: 0) } static func preferredHeight() -> CGFloat { return CGFloat(39) } /// Configures this instance with passed `rating`. Valid values are between 0 - 5. Behaviour for invalid values is undefined. func configure(rating: Int) { guard let starImageViews = starImageViews else { return } starImageViews.enumerated() .forEach { index, imageView in let insideRating = index < rating let starImage = insideRating ? UIImage.yellowStar() : UIImage.greyStar() imageView.image = starImage } } } extension UIImage { static func greyStar() -> UIImage? { return UIImage(named: "icoStarGrey") } static func yellowStar() -> UIImage? { return UIImage(named: "icoStarYellow") } }
21.068966
126
0.702946
d57b610e4d10f02d2eace4892a6d55eda8f2c9b9
326
// // ViewController.swift // paddle-mobile-unit-test // // Created by liuRuiLong on 2018/8/10. // Copyright © 2018年 orange. All rights reserved. // import UIKit import paddle_mobile class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print(" done ") } }
16.3
50
0.665644
09e42b25f0b8a71c510633d3b4200c8ff6c19f3e
5,496
// // UIViewController.swift // // Created by Sereivoan Yong on 1/24/20. // #if canImport(UIKit) import UIKit extension UIViewController { @IBAction open func dismiss(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction open func endEditing(_ sender: Any) { if isViewLoaded { view.endEditing(true) } } /// Check if ViewController is onscreen and not hidden. final public var isVisible: Bool { // @see: http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible return isViewLoaded && view.window != nil } /// Adds the specified view controller including its view as a child of the current view controller final public func addChildIncludingView(_ childViewController: UIViewController, addHandler: (_ view: UIView, _ childView: UIView) -> Void) { addChild(childViewController) addHandler(view, childViewController.view) childViewController.didMove(toParent: self) } /// Removes the view controller including its view from its parent final public func removeFromParentIncludingView() { willMove(toParent: nil) view.removeFromSuperview() removeFromParent() } @discardableResult final public func enableEndEditingOnTap(on view: UIView? = nil) -> UITapGestureRecognizer { let view = view ?? self.view! view.isUserInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEditing)) tapGestureRecognizer.cancelsTouchesInView = false view.addGestureRecognizer(tapGestureRecognizer) return tapGestureRecognizer } final public var topMostViewController: UIViewController? { if let navigationController = self as? UINavigationController, let visibleViewController = navigationController.visibleViewController { return visibleViewController.topMostViewController } else if let tabBarController = self as? UITabBarController, let selectedViewController = tabBarController.selectedViewController { return selectedViewController.topMostViewController } else if let presentedViewController = presentedViewController { return presentedViewController.topMostViewController } return self } @available(iOSApplicationExtension, unavailable) final public func show(animated: Bool, completion: (() -> Void)?) { UIApplication.shared.keyTopMostViewController?.present(self, animated: animated, completion: completion) } @inlinable final public func showDetail(_ detailViewController: UIViewController, sender: Any?) { showDetailViewController(detailViewController, sender: sender) } open func embeddingInNavigationController(configurationHandler: ((UINavigationController) -> Void)? = nil) -> UINavigationController { let navigationController = UINavigationController(rootViewController: self) configurationHandler?(navigationController) return navigationController } // MARK: - Layout Convenience private static var safeAreaLayoutGuide: Void? final public var safeAreaLayoutGuide: UILayoutGuide { if #available(iOS 11.0, *) { return view.safeAreaLayoutGuide } else { return associatedObject(forKey: &UIViewController.safeAreaLayoutGuide, default: { let layoutGuide = UILayoutGuide() view.addLayoutGuide(layoutGuide) NSLayoutConstraint.activate([ layoutGuide.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor), layoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), bottomLayoutGuide.topAnchor.constraint(equalTo: layoutGuide.bottomAnchor), view.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor), ]) return layoutGuide }()) } } final public var safeAreaTopAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return view.safeAreaLayoutGuide.topAnchor } else { return topLayoutGuide.bottomAnchor } } final public var safeAreaBottomAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return view.safeAreaLayoutGuide.bottomAnchor } else { return bottomLayoutGuide.topAnchor } } final public var safeAreaTopInset: CGFloat { if #available(iOS 11.0, *) { return view.safeAreaInsets.top } else { return topLayoutGuide.length } } final public var safeAreaBottomInset: CGFloat { if #available(iOS 11.0, *) { return view.safeAreaInsets.bottom } else { return bottomLayoutGuide.length } } final public var safeAreaFrame: CGRect { if #available(iOS 11.0, *) { return view.bounds.inset(by: view.safeAreaInsets) } else { return CGRect(x: 0, y: topLayoutGuide.length, width: view.bounds.width, height: bottomLayoutGuide.length) } } // MARK: - Others final public func present(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?, in queue: DispatchQueue) { queue.async { [unowned self] in self.present(viewController, animated: animated, completion: completion) } } final public var topPresentedViewController: UIViewController? { var currentPresentedViewController = presentedViewController while let presentedViewController = currentPresentedViewController?.presentedViewController { currentPresentedViewController = presentedViewController } return currentPresentedViewController } } #endif
34.35
143
0.72853
ccebae1e40bb095d18779e8829078a575aec6932
1,128
// // UIView+Store.swift // XCoordinator // // Created by Stefan Kofler on 19.07.18. // Copyright © 2018 QuickBird Studios. All rights reserved. // private var associatedObjectHandle: UInt8 = 0 extension UIView { var strongReferences: [Any] { get { return objc_getAssociatedObject(self, &associatedObjectHandle) as? [Any] ?? [] } set { objc_setAssociatedObject(self, &associatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } extension UIView { @discardableResult func removePreviewingContext<TransitionType: TransitionProtocol>(for _: TransitionType.Type) -> UIViewControllerPreviewing? { guard let existingContextIndex = strongReferences .index(where: { $0 is CoordinatorPreviewingDelegateObject<TransitionType> }), let contextDelegate = strongReferences .remove(at: existingContextIndex) as? CoordinatorPreviewingDelegateObject<TransitionType>, let context = contextDelegate.context else { return nil } return context } }
29.684211
113
0.666667