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
ab641dfe7bcffa39cc8fe05b7f45497fc504e962
2,821
//----------------------------------------------------------------- // File: CustomTextField.swift // // Team: ParkinSense - PDD Inc. // // Programmer(s): Hamlet Jiang Su // // Description: Custom class to add some padding between the actual text and the text field in the storyboard // // Changes: // - Added UIEdgeInsets to create padding within text fields // // Known Bugs: // - None // //----------------------------------------------------------------- import UIKit @IBDesignable class CustomTextField: UITextField { /** Adds padding the the right of the text field - Returns: UIEdgeInsets **/ var padding: UIEdgeInsets { get { return UIEdgeInsets(top: paddingValue/2, left: paddingValue, bottom: paddingValue/2, right: paddingValue) } } /** Adds padding the the right of the text within a text field - Returns: CGRect with new bounds determined by the padding **/ override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } /** Adds padding the the right of any placeholder text within a text field - Returns: CGRect with new bounds determined by the padding **/ override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } /** Adds padding the the right of the text within a text field when editing - Returns: CGRect with new bounds determined by the padding **/ override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: padding) } var bottomBorder = UIView() override func awakeFromNib() { // Setup Bottom-Border self.translatesAutoresizingMaskIntoConstraints = false bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bottomBorder.backgroundColor = UIColor(red:0.89, green:0.86, blue:0.82, alpha:1.0) // Set Border-Color bottomBorder.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomBorder) bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength } @IBInspectable var paddingValue: CGFloat = 0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } }
28.21
117
0.602269
26dfde6c0d5ef2c712cd8bb5cf1eecc95298024c
12,186
// // AAPlotOptions.swift // AAInfographicsDemo // // Created by AnAn on 2019/8/31. // Copyright © 2019 An An. All rights reserved. //*************** ...... SOURCE CODE ...... *************** //***...................................................*** //*** https://github.com/AAChartModel/AAChartKit *** //*** https://github.com/AAChartModel/AAChartKit-Swift *** //***...................................................*** //*************** ...... SOURCE CODE ...... *************** /* * ------------------------------------------------------------------------------- * * 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔 * * Please contact me on GitHub,if there are any problems encountered in use. * GitHub Issues : https://github.com/AAChartModel/AAChartKit-Swift/issues * ------------------------------------------------------------------------------- * And if you want to contribute for this project, please contact me as well * GitHub : https://github.com/AAChartModel * StackOverflow : https://stackoverflow.com/users/7842508/codeforu * JianShu : https://www.jianshu.com/u/f1e6753d4254 * SegmentFault : https://segmentfault.com/u/huanghunbieguan * * ------------------------------------------------------------------------------- */ import UIKit public class AAPlotOptions: AAObject { public var column: AAColumn? public var bar: AABar? public var line: AALine? public var spline: AASpline? public var area: AAArea? public var areaspline: AAAreaspline? public var pie: AAPie? public var columnrange: AAColumnrange? public var arearange: AAArearange? public var series: AASeries? @discardableResult public func column(_ prop: AAColumn) -> AAPlotOptions { column = prop return self } @discardableResult public func line(_ prop: AALine) -> AAPlotOptions { line = prop return self } @discardableResult public func pie(_ prop: AAPie) -> AAPlotOptions { pie = prop return self } @discardableResult public func bar(_ prop: AABar) -> AAPlotOptions { bar = prop return self } @discardableResult public func spline(_ prop: AASpline) -> AAPlotOptions { spline = prop return self } @discardableResult public func area(_ prop: AAArea) -> AAPlotOptions { area = prop return self } @discardableResult public func areaspline(_ prop: AAAreaspline) -> AAPlotOptions { areaspline = prop return self } @discardableResult public func columnrange(_ prop: AAColumnrange) -> AAPlotOptions { columnrange = prop return self } @discardableResult public func arearange(_ prop: AAArearange) -> AAPlotOptions { arearange = prop return self } @discardableResult public func series(_ prop: AASeries) -> AAPlotOptions { series = prop return self } public override init() { } } public class AAColumn: AAObject { public var name: String? public var data: [Any]? public var color: String? public var grouping: Bool?//Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be laid out individually and overlap each other. 默认是:true. public var pointPadding: Float?//Padding between each column or bar, in x axis units. 默认是:0.1. public var pointPlacement: Float?//Padding between each column or bar, in x axis units. 默认是:0.1. public var groupPadding: Float?//Padding between each value groups, in x axis units. 默认是:0.2. public var borderWidth: Float? public var colorByPoint: Bool?//对每个不同的点设置颜色(当图表类型为 AAColumn 时,设置为 AAColumn 对象的属性,当图表类型为 bar 时,应该设置为 bar 对象的属性才有效) public var dataLabels: AADataLabels? public var stacking: String? public var borderRadius: Int? public var yAxis: Float? @discardableResult public func name(_ prop: String) -> AAColumn { name = prop return self } @discardableResult public func data(_ prop: [Any]) -> AAColumn { data = prop return self } @discardableResult public func color(_ prop: String) -> AAColumn { color = prop return self } @discardableResult public func grouping(_ prop: Bool?) -> AAColumn { grouping = prop return self } @discardableResult public func pointPadding(_ prop: Float?) -> AAColumn { pointPadding = prop return self } @discardableResult public func pointPlacement(_ prop: Float?) -> AAColumn { pointPlacement = prop return self } @discardableResult public func groupPadding(_ prop: Float?) -> AAColumn { groupPadding = prop return self } @discardableResult public func borderWidth(_ prop: Float?) -> AAColumn { borderWidth = prop return self } @discardableResult public func colorByPoint(_ prop: Bool?) -> AAColumn { colorByPoint = prop return self } @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAColumn { dataLabels = prop return self } @discardableResult public func stacking(_ prop: String) -> AAColumn { stacking = prop return self } @discardableResult public func borderRadius(_ prop: Int?) -> AAColumn { borderRadius = prop return self } @discardableResult public func yAxis(_ prop: Float?) -> AAColumn { yAxis = prop return self } public override init() { } } public class AABar: AAObject { public var name: String? public var data: [Any]? public var color: String? public var grouping: Bool?//Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be laid out individually and overlap each other. 默认是:true. public var pointPadding: Float?//Padding between each column or bar, in x axis units. 默认是:0.1. public var pointPlacement: Float?//Padding between each column or bar, in x axis units. 默认是:0.1. public var groupPadding: Float?//Padding between each value groups, in x axis units. 默认是:0.2. public var borderWidth: Float? public var colorByPoint: Bool?//对每个不同的点设置颜色(当图表类型为 AABar 时,设置为 AABar 对象的属性,当图表类型为 bar 时,应该设置为 bar 对象的属性才有效) public var dataLabels: AADataLabels? public var stacking: String? public var borderRadius: Int? public var yAxis: Float? @discardableResult public func name(_ prop: String) -> AABar { name = prop return self } @discardableResult public func data(_ prop: [Any]) -> AABar { data = prop return self } @discardableResult public func color(_ prop: String) -> AABar { color = prop return self } @discardableResult public func grouping(_ prop: Bool?) -> AABar { grouping = prop return self } @discardableResult public func pointPadding(_ prop: Float?) -> AABar { pointPadding = prop return self } @discardableResult public func pointPlacement(_ prop: Float?) -> AABar { pointPlacement = prop return self } @discardableResult public func groupPadding(_ prop: Float?) -> AABar { groupPadding = prop return self } @discardableResult public func borderWidth(_ prop: Float?) -> AABar { borderWidth = prop return self } @discardableResult public func colorByPoint(_ prop: Bool?) -> AABar { colorByPoint = prop return self } @discardableResult public func dataLabels(_ prop: AADataLabels) -> AABar { dataLabels = prop return self } @discardableResult public func stacking(_ prop: String) -> AABar { stacking = prop return self } @discardableResult public func borderRadius(_ prop: Int?) -> AABar { borderRadius = prop return self } @discardableResult public func yAxis(_ prop: Float?) -> AABar { yAxis = prop return self } public override init() { } } public class AALine: AAObject { public var dataLabels: AADataLabels? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AALine { dataLabels = prop return self } public override init() { } } public class AASpline: AAObject { public var dataLabels: AADataLabels? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AASpline { dataLabels = prop return self } public override init() { } } public class AAArea: AAObject { public var dataLabels: AADataLabels? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAArea { dataLabels = prop return self } public override init() { } } public class AAAreaspline: AAObject { public var dataLabels: AADataLabels? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAAreaspline { dataLabels = prop return self } public override init() { } } public class AAPie: AAObject { public var dataLabels:AADataLabels? public var size: Float? public var allowPointSelect: Bool? public var cursor: String? public var showInLegend: Bool? public var startAngle: Float? public var endAngle: Float? public var depth: Float? public var center: [Int]? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAPie { dataLabels = prop return self } @discardableResult public func size(_ prop: Float?) -> AAPie { size = prop return self } @discardableResult public func allowPointSelect(_ prop: Bool?) -> AAPie { allowPointSelect = prop return self } @discardableResult public func cursor(_ prop: String) -> AAPie { cursor = prop return self } @discardableResult public func showInLegend(_ prop: Bool?) -> AAPie { showInLegend = prop return self } @discardableResult public func startAngle(_ prop: Float?) -> AAPie { startAngle = prop return self } @discardableResult public func endAngle(_ prop: Float?) -> AAPie { endAngle = prop return self } @discardableResult public func depth(_ prop: Float?) -> AAPie { depth = prop return self } @discardableResult public func center(_ prop: [Int]?) -> AAPie { center = prop return self } public override init() { } } public class AAColumnrange: AAObject { public var borderRadius: Float?//The color of the border surrounding each column or bar public var borderWidth: Float?//The corner radius of the border surrounding each column or bar. default:0 public var dataLabels: AADataLabels? @discardableResult public func borderRadius(_ prop: Float) -> AAColumnrange { borderRadius = prop return self } @discardableResult public func borderWidth(_ prop: Float) -> AAColumnrange { borderWidth = prop return self } @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAColumnrange { dataLabels = prop return self } public override init() { } } public class AAArearange: AAObject { public var dataLabels: AADataLabels? @discardableResult public func dataLabels(_ prop: AADataLabels) -> AAArearange { dataLabels = prop return self } public override init() { } }
25.229814
201
0.591909
9ca501f408990db4629a8cdf7df1887fcdd55ffb
8,068
// // HomeViewController.swift // SpaceX // // Created by Pushpinder Pal Singh on 24/06/20. // Copyright © 2020 Pushpinder Pal Singh. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var upcomingView: UpcomingView! @IBOutlet weak var upcomingPanel: NSLayoutConstraint! @IBOutlet var panelConstraints: [NSLayoutConstraint]! @IBOutlet weak var launchDate: UILabel! @IBOutlet weak var launchSite: UILabel! @IBOutlet weak var payloadAndType: UILabel! @IBOutlet weak var watchNowButton: WatchNowButton! @IBOutlet weak var isTentative: UILabel! @IBOutlet weak var rocketImage: RocketImageView! let networkObject = NetworkManager(Constants.NetworkManager.baseURL) let upcomingLaunch = UpcomingLaunchModel() let cache = NSCache<NSString, DetailsViewModel>() var watchURL : URL? = nil let smallDeviceHeight: CGFloat = 896 override func viewDidLoad() { super.viewDidLoad() networkObject.performRequest(key: Constants.NetworkManager.upcomingLaunchURL) { [weak self] (result: Result<[UpcomingLaunchData],Error>) in guard let self = self else { return } switch result { case .success(let launches): let launch = self.upcomingLaunch.cleanData(launches) self.updateModel(launch) self.updateUI() break case .failure(let error): print(error) } } adjustUpcomingSize() //tap gesture for tentative label self.isTentative.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tentativeClicked(_:)))) self.isTentative.isUserInteractionEnabled = true } override var preferredStatusBarStyle: UIStatusBarStyle { return .darkContent } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: true) } /// Update the model with new data that has just arrived from API func updateModel(_ launch : UpcomingLaunchData){ self.upcomingLaunch.launchSite = launch.launch_site.site_name_long self.upcomingLaunch.payloadAndType = "\(launch.rocket.second_stage.payloads[0].payload_id), \(launch.rocket.second_stage.payloads[0].payload_type)" self.upcomingLaunch.launchDate = launch.launch_date_unix.getDate() self.upcomingLaunch.isTentative = launch.is_tentative self.upcomingLaunch.rocket = launch.rocket.rocket_id self.upcomingLaunch.watchNow = launch.links.video_link_url print(launch.rocket.rocket_id) } @IBAction func buttonPressed(_ sender: UIButton) { performSegue(withIdentifier: Constants.SegueManager.detailViewSegue, sender: sender.titleLabel?.text) } @IBAction func watchNowButton(_ sender: UIButton) { UIApplication.shared.open(watchURL!) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let target = segue.destination as? DetailsViewController { let key = sender as! String print("Sender: \(key)") switch key { case Constants.SegueManager.SenderValues.rocket: target.callAPI(withEndpoint: key, decode: [RocketData](), cachedData: cache) break case Constants.SegueManager.SenderValues.launches: target.callAPI(withEndpoint: key, decode: [LaunchesData](), cachedData: cache) break case Constants.SegueManager.SenderValues.launchSite: target.callAPI(withEndpoint: key, decode: [LaunchPadData](), cachedData: cache) break case Constants.SegueManager.SenderValues.ships: target.callAPI(withEndpoint: key, decode: [ShipsData](), cachedData: cache) break case Constants.SegueManager.SenderValues.capsules: target.callAPI(withEndpoint: key, decode: [CapsulesData](), cachedData: cache) break case Constants.SegueManager.SenderValues.landpads: target.callAPI(withEndpoint: key, decode: [LandpadsData](), cachedData: cache) break default: print("error") } } } } //MARK: - UI extension HomeViewController: UIPopoverPresentationControllerDelegate { /// Making the Height of Upcoming Panel and View Dynamic func adjustUpcomingSize() { if UIScreen.main.bounds.height<smallDeviceHeight || !watchNowButton.isHidden { upcomingPanel.constant = UIScreen.main.bounds.height*0.04 for panels in panelConstraints{ panels.constant = UIScreen.main.bounds.height*0.025 } } if UIScreen.main.bounds.height<smallDeviceHeight && !watchNowButton.isHidden { upcomingView.setupSmallHeight() } } /// This function will update the UI once updateFromAPI updates the data for HomeViewController func updateUI(){ DispatchQueue.main.async { self.launchSite.text = self.upcomingLaunch.launchSite self.payloadAndType.text = self.upcomingLaunch.payloadAndType self.launchDate.text = self.upcomingLaunch.launchDate self.isTentative.isHidden = !(self.upcomingLaunch.isTentative!) self.rocketImage.image = UIImage(named: self.upcomingLaunch.rocket!) self.checkWatchButton() self.adjustUpcomingSize() } } /// This function will assign the video URL of the upcoming launch and display the "Watch Now" button if the URL available func checkWatchButton() { guard let safeWatchURL = upcomingLaunch.watchNow, UIApplication.shared.canOpenURL(safeWatchURL) else { return } self.watchURL = safeWatchURL watchNowButton.isHidden = false } @objc func tentativeClicked(_ sender: UITapGestureRecognizer){ // we dont want to fill the popover to full width of the screen let standardWidth = self.view.frame.width - 60 //to dynamically resize the popover, we premature-ly calculate the height of the label using the text content let estimatedHeight = Constants.HomeView.tentativeDetail.height(ConstrainedWidth: standardWidth - 24) let tentativeDetailsVC = TentativeDetailsViewController() tentativeDetailsVC.lblTentativeDetail.text = Constants.HomeView.tentativeDetail tentativeDetailsVC.modalPresentationStyle = .popover //this tells that the presenting viewcontroller is an popover style tentativeDetailsVC.preferredContentSize = CGSize.init(width: standardWidth, height: estimatedHeight + 40) //40 is vertical padding tentativeDetailsVC.overrideUserInterfaceStyle = .light //disabling dark mode if let popoverPresentationController = tentativeDetailsVC.popoverPresentationController { //this option makes popover to preview below the "T" sign popoverPresentationController.permittedArrowDirections = .up //source view and source rect is used by popover controller to determine where the triangle should be placed and present the popover relative to the source view popoverPresentationController.sourceView = self.isTentative popoverPresentationController.sourceRect = self.isTentative.bounds popoverPresentationController.delegate = self } self.present(tentativeDetailsVC, animated: true, completion: nil) } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // .none makes the viewcontroller to be present as popover always, no matter what trait changes return .none } }
42.687831
172
0.666708
fe0b6a72c0d9d0507aedfac119b1cc7f0676bae6
570
// // ViewController.swift // WLTranslateKitDemo // // Created by three stone 王 on 2019/5/21. // Copyright © 2019 three stone 王. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let vc = WLTranslateBaseViewController.createTranslate(.ko, config: WLCCCCC()) view.addSubview(vc.view) addChild(vc) vc.view.frame = view.bounds } }
20.357143
86
0.607018
9174dba2fc6365535a5749f4e757ba71eb9930fd
3,723
// // ShowInfoViewController.swift // IAME_ImageProcesse // // Created by Hassaniiii on 11/25/18. // Copyright © 2018 Hassan Shahbazi. All rights reserved. // import UIKit class ShowInfoViewController: UIViewController { public var textBlocks: [String]! public var capturedImage: UIImage! public var capturedFace: UIImage! private var textBlocksExtracted: Dictionary<String,String> = [:] private var sectionHeaders: [String] { return ["Surname", "First Name", "Surname at Birth", "ID Number", "Date of Birth", "Gender", "Signature", "Nationality"] } private var sectionHeadersCopy: [String]! private let viewModel = HistoryViewModel() @IBOutlet weak var table: UITableView! @IBOutlet weak var saveBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() initiateData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initiateView() } private func initiateView() { self.navigationController?.setNavigationBarHidden(true, animated: true) self.table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 70, right: 0) } private func initiateData() { sectionHeadersCopy = sectionHeaders for counter in 0..<textBlocks.count { let text = textBlocks[counter] if let relatedSection = getRelatedSection(text) { let value = text.components(separatedBy: relatedSection) textBlocksExtracted[relatedSection.lowercased()] = value[1] } else if text.lowercased().contains("republic") { sectionHeadersCopy.removeAll(where: { $0 == "Nationality" }) textBlocksExtracted["Nationality".lowercased()] = text } } self.table.reloadData() } private func getRelatedSection(_ blockText: String) -> String? { for section in sectionHeadersCopy { if blockText.contains(section) { sectionHeadersCopy.removeAll(where: { $0 == section }) return section } } return nil } @IBAction func dismissVC(_ sender: UIButton) { self.navigationController?.popToRootViewController(animated: true) } @IBAction func saveContinue(_ sender: UIButton) { viewModel.saveNewPerson(data: textBlocksExtracted, image: capturedImage, faceImage: capturedFace) { (succeed: Bool?) in if let _ = succeed { self.navigationController?.popToRootViewController(animated: true) return } self.saveBtn.backgroundColor = #colorLiteral(red: 0.8823529412, green: 0.2980392157, blue: 0.2745098039, alpha: 1) self.saveBtn.setTitle("Save failed", for: .normal) } } } extension ShowInfoViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return sectionHeaders.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = table.dequeueReusableCell(withIdentifier: "result_cell") else { return UITableViewCell() } let currentSection = sectionHeaders[indexPath.section].lowercased() cell.textLabel?.text = textBlocksExtracted[currentSection] return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionHeaders[section] } }
35.122642
128
0.640075
e5f3dce75da1f4d2e7ca124bbb3b9cfcef97277d
1,275
/* MIT License Copyright (c) 2021 Michal Fousek 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 Bool: BitStreamEncodable { public func encode(with encoder: BitStreamEncoder) { encoder.write(byte: self ? 1 : 0, useBitsCount: 1) } }
39.84375
79
0.774118
1d4ce7149d48dc933095b1be687dd386d12d725d
5,857
/* Copyright 2018 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit import DesignKit /// Color constants for the dark theme @objcMembers class DarkTheme: NSObject, Theme { var identifier: String = ThemeIdentifier.dark.rawValue var backgroundColor: UIColor = UIColor(rgb: 0x15191E) var baseColor: UIColor = UIColor(rgb: 0x21262C) var baseIconPrimaryColor: UIColor = UIColor(rgb: 0xEDF3FF) var baseTextPrimaryColor: UIColor = UIColor(rgb: 0xFFFFFF) var baseTextSecondaryColor: UIColor = UIColor(rgb: 0xA9B2BC) var searchBackgroundColor: UIColor = UIColor(rgb: 0x15191E) var searchPlaceholderColor: UIColor = UIColor(rgb: 0xA9B2BC) var headerBackgroundColor: UIColor = UIColor(rgb: 0x21262C) var headerBorderColor: UIColor = UIColor(rgb: 0x15191E) var headerTextPrimaryColor: UIColor = UIColor(rgb: 0xFFFFFF) var headerTextSecondaryColor: UIColor = UIColor(rgb: 0xA9B2BC) var textPrimaryColor: UIColor = UIColor(rgb: 0xFFFFFF) var textSecondaryColor: UIColor = UIColor(rgb: 0xA9B2BC) var textTertiaryColor: UIColor = UIColor(rgb: 0x8E99A4) var tintColor: UIColor = UIColor(displayP3Red: 0.05098039216, green: 0.7450980392, blue: 0.5450980392, alpha: 1.0) var tintBackgroundColor: UIColor = UIColor(rgb: 0x1F6954) var tabBarUnselectedItemTintColor: UIColor = UIColor(rgb: 0x8E99A4) var unreadRoomIndentColor: UIColor = UIColor(rgb: 0x2E3648) var lineBreakColor: UIColor = UIColor(rgb: 0x363D49) var noticeColor: UIColor = UIColor(rgb: 0xFF4B55) var noticeSecondaryColor: UIColor = UIColor(rgb: 0x61708B) var warningColor: UIColor = UIColor(rgb: 0xFF4B55) var roomInputTextBorder: UIColor = UIColor(rgb: 0x8D97A5).withAlphaComponent(0.2) var avatarColors: [UIColor] = [ UIColor(rgb: 0x03B381), UIColor(rgb: 0x368BD6), UIColor(rgb: 0xAC3BA8)] var userNameColors: [UIColor] = [ UIColor(rgb: 0x368BD6), UIColor(rgb: 0xAC3BA8), UIColor(rgb: 0x03B381), UIColor(rgb: 0xE64F7A), UIColor(rgb: 0xFF812D), UIColor(rgb: 0x2DC2C5), UIColor(rgb: 0x5C56F5), UIColor(rgb: 0x74D12C) ] var statusBarStyle: UIStatusBarStyle = .lightContent var scrollBarStyle: UIScrollView.IndicatorStyle = .white var keyboardAppearance: UIKeyboardAppearance = .dark var userInterfaceStyle: UIUserInterfaceStyle { return .dark } var placeholderTextColor: UIColor = UIColor(rgb: 0xA1B2D1) // Use secondary text color var selectedBackgroundColor: UIColor = UIColor(rgb: 0x040506) var callScreenButtonTintColor: UIColor = UIColor(rgb: 0xFFFFFF) var overlayBackgroundColor: UIColor = UIColor(white: 0.7, alpha: 0.5) var matrixSearchBackgroundImageTintColor: UIColor = UIColor(rgb: 0x7E7E7E) var secondaryCircleButtonBackgroundColor: UIColor = UIColor(rgb: 0xE3E8F0) var shadowColor: UIColor = UIColor(rgb: 0xFFFFFF) var messageTickColor: UIColor = .white func applyStyle(onTabBar tabBar: UITabBar) { tabBar.unselectedItemTintColor = self.tabBarUnselectedItemTintColor tabBar.tintColor = self.tintColor tabBar.barTintColor = self.baseColor tabBar.isTranslucent = false } // Note: We are not using UINavigationBarAppearance on iOS 13+ atm because of UINavigationBar directly include UISearchBar on their titleView that cause crop issues with UINavigationController pop. func applyStyle(onNavigationBar navigationBar: UINavigationBar) { navigationBar.tintColor = self.tintColor navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: self.textPrimaryColor ] navigationBar.barTintColor = self.baseColor navigationBar.shadowImage = UIImage() // Remove bottom shadow // The navigation bar needs to be opaque so that its background color is the expected one navigationBar.isTranslucent = false } func applyStyle(onSearchBar searchBar: UISearchBar) { searchBar.searchBarStyle = .default searchBar.barStyle = .black searchBar.barTintColor = self.baseColor searchBar.isTranslucent = false searchBar.backgroundImage = UIImage() // Remove top and bottom shadow searchBar.tintColor = self.tintColor if #available(iOS 13.0, *) { searchBar.searchTextField.backgroundColor = self.searchBackgroundColor searchBar.searchTextField.textColor = self.searchPlaceholderColor } else { if let searchBarTextField = searchBar.vc_searchTextField { searchBarTextField.textColor = self.searchPlaceholderColor } } } func applyStyle(onTextField texField: UITextField) { texField.textColor = self.textPrimaryColor texField.tintColor = self.tintColor } func applyStyle(onButton button: UIButton) { // NOTE: Tint color does nothing by default on button type `UIButtonType.custom` button.tintColor = self.tintColor button.setTitleColor(self.tintColor, for: .normal) } /// MARK: - Theme v2 var colors: ColorsUIKit = DarkColors.uiKit var fonts: FontsUIKit = FontsUIKit(values: ElementFonts()) }
39.308725
201
0.710944
14781e45546b08b984873e4b04ca4121e6c57ca6
2,223
// // DemoBaseTableViewController.swift // Moya-Argo // // Created by Sam Watts on 23/01/2016. // Copyright © 2016 Sam Watts. All rights reserved. // import UIKit protocol UserType { var id: Int { get } var name: String { get } var birthdate: String? { get } } class DemoBaseTableViewController: UITableViewController { var users:[UserType] = [] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "DemoUserCellReuseIdentifier") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.fetchUsers() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DemoUserCellReuseIdentifier", for: indexPath) let user = users[indexPath.row] cell.textLabel?.text = user.name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let alertClosure = { (user:UserType) in let alertController = UIAlertController(title: "User", message: "ID: \(user.id)\nBirthdate: \(user.birthdate!)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in alertController.dismiss(animated: true, completion: nil) })) self.present(alertController, animated: true, completion: nil) } self.fetchUserDetail(users[indexPath.row], showAlertClosure: alertClosure) } //MARK: methods which subclasses should override func fetchUsers() { } func fetchUserDetail(_ user: UserType, showAlertClosure: @escaping (UserType) -> ()) { } }
29.25
158
0.638776
6931ab2f35ad0e46d6f29e8e0d398fad241b750c
14,147
// // VDStockDataHandle.swift // VDStockChartDemo // // Created by Harwyn T'an on 2018/5/28. // Copyright © 2018年 vvard3n. All rights reserved. // import UIKit public class VDStockDataHandle { /// 统计节点信息 public static func calculate(_ nodes: [KlineNode]) -> KlineCalculateResult { var minPrice = Float.greatestFiniteMagnitude var maxPrice = -Float.greatestFiniteMagnitude var maxHigh = -Float.greatestFiniteMagnitude var minLow = Float.greatestFiniteMagnitude var maxBusinessAmount = -Float.greatestFiniteMagnitude var minBusinessAmount = Float.greatestFiniteMagnitude var maxMACD = -Double.greatestFiniteMagnitude var minMACD = Double.greatestFiniteMagnitude var minKDJ = Double.greatestFiniteMagnitude var maxKDJ = -Double.greatestFiniteMagnitude var maxWR = -Double.greatestFiniteMagnitude var minWR = Double.greatestFiniteMagnitude var minRSI = Double.greatestFiniteMagnitude var maxRSI = -Double.greatestFiniteMagnitude nodes.forEach { minLow = Swift.min(minLow, $0.low) maxHigh = Swift.max(maxHigh, $0.high) minPrice = min(minPrice, $0.low, $0.MA5, $0.MA10, $0.MA30) maxPrice = max(maxPrice, $0.high, $0.MA5, $0.MA10, $0.MA30) minBusinessAmount = Swift.min(minBusinessAmount, $0.businessAmount) maxBusinessAmount = Swift.max(maxBusinessAmount, $0.businessAmount) minMACD = min(minMACD, $0.DIFF, $0.DEA, $0.MACD) maxMACD = max(maxMACD, $0.DIFF, $0.DEA, $0.MACD) minKDJ = min(minKDJ, $0.K, $0.D, $0.J) maxKDJ = max(maxKDJ, $0.K, $0.D, $0.J) minWR = Swift.min(minWR, $0.WR) maxWR = Swift.max(maxWR, $0.WR) minRSI = min(minRSI, $0.RSI6, $0.RSI12, $0.RSI24) maxRSI = max(maxRSI, $0.RSI6, $0.RSI12, $0.RSI24) } if maxPrice == minPrice { maxPrice += 1 } return KlineCalculateResult(minPrice: minPrice, maxPrice: maxPrice, minLow: minLow, maxHigh: maxHigh, maxBusinessAmount: maxBusinessAmount, minBusinessAmount: minBusinessAmount, minMACD: minMACD, maxMACD: maxMACD, minKDJ: minKDJ, maxKDJ: maxKDJ, minWR: minWR, maxWR: maxWR, minRSI: minRSI, maxRSI: maxRSI) } public static func calculate(_ nodes: [TimeLineNode]) -> TimeLineCalculateResult { var minPrice = Float.greatestFiniteMagnitude var maxPrice = -Float.greatestFiniteMagnitude var minBusinessAmount = Float.greatestFiniteMagnitude var maxBusinessAmount = -Float.greatestFiniteMagnitude nodes.forEach { minPrice = Swift.min(minPrice, $0.price) maxPrice = Swift.max(maxPrice, $0.price) minBusinessAmount = Swift.min(minBusinessAmount, $0.businessAmount) maxBusinessAmount = Swift.max(maxBusinessAmount, $0.businessAmount) } return TimeLineCalculateResult(minPrice: minPrice, maxPrice: maxPrice, maxBusinessAmount: maxBusinessAmount, minBusinessAmount: minBusinessAmount) } public static func calculateIndicator(_ nodes: [KlineNode]) { nodes.enumerated().forEach { index, node in node.MA5 = MA(5, currentIndex: index, in: nodes) node.MA10 = MA(10, currentIndex: index, in: nodes) node.MA30 = MA(30, currentIndex: index, in: nodes) if index > 0 { let yesterdayEMA1 = nodes[index - 1].EMA1 == 0 ? Double(nodes[index - 1].close) : nodes[index - 1].EMA1 let yesterdayEMA2 = nodes[index - 1].EMA2 == 0 ? Double(nodes[index - 1].close) : nodes[index - 1].EMA2 node.EMA1 = EMA(12, close: node.close, yesterdayEMA: yesterdayEMA1) node.EMA2 = EMA(26, close: node.close, yesterdayEMA: yesterdayEMA2) node.DIFF = node.EMA1 - node.EMA2 node.DEA = nodes[index - 1].DEA * 8 / 10 + node.DIFF * 2 / 10 node.MACD = (node.DIFF - node.DEA) * 2 // (今收盘-昨收盘)/昨收盘*100% node.changeRate = (node.close - nodes[index - 1].close) / nodes[index - 1].close * 100 node.yesterdayClose = nodes[index - 1].close if node.open == node.close && node.high == node.low && node.open == node.high { if node.open >= node.yesterdayClose { node.isIncrease = true } else { node.isIncrease = false } } else { node.isIncrease = node.close >= node.open } } else { //首个节点(非精确计算) node.changeRate = (node.close - node.open) / node.open * 100 node.yesterdayClose = node.open if node.open == node.close && node.high == node.low && node.open == node.high { node.isIncrease = true } else { node.isIncrease = node.close >= node.open } } (node.K, node.D, node.J) = KDJ(currentIndex: index, in: nodes) node.WR = WR(14, currentIndex: index, in: nodes) node.RSI6 = RSI(6, currentIndex: index, in: nodes) // node.RSI12 = RSI(12, currentIndex: index, in: nodes) // node.RSI24 = RSI(24, currentIndex: index, in: nodes) } } public static func calculateAvgTimeLine(_ nodes: [TimeLineNode]) { var priceSum: Float = 0 var volumeSum: Float = 0 nodes.enumerated().forEach { index, node in priceSum += node.price * node.businessAmount volumeSum += node.businessAmount node.avgPrice = priceSum / volumeSum print("priceSum: \(priceSum) volumeSum:\(volumeSum) avgPrice:\(node.avgPrice)") } } static func converNumberToString(number: Float, decimal: Bool) -> String { if number >= 10000 && number < 100000000 { return String(format: "%.2f万", number / 10000) } if number >= 100000000 && number < 1000000000000 { return String(format: "%.2f亿", number / 100000000) } if Double(number) >= Double(1000000000000) { return String(format: "%.2f万亿", Float(Double(number) / Double(1000000000000))) } return decimal ? String(format: "%.2f", number) : String(format: "%ld", lroundf(number)) } private static func KDJ(currentIndex: Int, in nodes: [KlineNode]) -> (K: Double, D: Double, J: Double) { if currentIndex == 0 { return (K: 100, D: 100, J: 100) } let startIndex = Swift.max(currentIndex - 9 + 1, 0) var maxHigh = -Float.greatestFiniteMagnitude var minLow = Float.greatestFiniteMagnitude for i in startIndex...currentIndex { maxHigh = Swift.max(maxHigh, nodes[i].high) minLow = Swift.min(minLow, nodes[i].low) } let rsv = Double(nodes[currentIndex].close - minLow) / Double(maxHigh - minLow) * 100 let K = 2 / 3 * nodes[currentIndex - 1].K + 1 / 3 * rsv let D = 2 / 3 * nodes[currentIndex - 1].D + 1 / 3 * K let J = 3 * K - 2 * D return (K, D, J) } private static func RSI(_ days: Int, currentIndex: Int, in nodes: [KlineNode]) -> Double { if currentIndex + 1 - days < 0 { return 100 } let startIndex = currentIndex - days + 1 var sumIncrease: Double = 0 var sumDecrease: Double = 0 for i in (startIndex + 1)...currentIndex { // sumIncrease += Double(nodes[i].close - nodes[i - 1].close) // sumDecrease += Double(abs(nodes[i].close - nodes[i - 1].close)) if nodes[i].close >= nodes[i - 1].close { sumIncrease += Double(nodes[i].close - nodes[i - 1].close) } else { sumDecrease += Double(nodes[i - 1].close - nodes[i].close) } } //// sumDecrease += 20.56 // //// if nodes[currentIndex].close >= nodes[currentIndex - 1].close { //// sumIncrease = sumIncrease * 5 / 6 + Double(nodes[currentIndex].close - nodes[currentIndex - 1].close) / 6 //// } else { //// sumDecrease = sumDecrease * 5 / 6 + Double(nodes[currentIndex - 1].close - nodes[currentIndex].close) / 6 //// } //// // //// print(sumIncrease, sumDecrease) //// sumIncrease = sumIncrease / Double(days) //// sumDecrease = sumDecrease / Double(days) // sumIncrease += -20.56 sumDecrease += 20.56 // print(sumIncrease, sumDecrease) // let rs = sumDecrease == 0 ? 0 : sumIncrease / sumDecrease return sumIncrease / (sumIncrease + sumDecrease) * 100 //100 - 100 / (1 + rs) //rs / (1 + rs) * 100 } private static func WR(_ days: Int, currentIndex: Int, in nodes: [KlineNode]) -> Double { if currentIndex + 1 - days < 0 { return 0 } let startIndex = currentIndex - days + 1 var maxHigh = -Float.greatestFiniteMagnitude var minLow = Float.greatestFiniteMagnitude for i in startIndex...currentIndex { maxHigh = Swift.max(maxHigh, nodes[i].high) minLow = Swift.min(minLow, nodes[i].low) } return Double(maxHigh - nodes[currentIndex].close) / Double(maxHigh - minLow) * 100 } private static func min(_ numbers: Float...) -> Float { var number = Float.greatestFiniteMagnitude numbers.forEach { if $0 > 0 && number > $0 { number = $0 } } return number } private static func max(_ numbers: Float...) -> Float { var number = -Float.greatestFiniteMagnitude numbers.forEach { if number < $0 { number = $0 } } return number } private static func min(_ numbers: Double...) -> Double { var number = Double.greatestFiniteMagnitude numbers.forEach { if number > $0 { number = $0 } } return number } private static func max(_ numbers: Double...) -> Double { var number = -Double.greatestFiniteMagnitude numbers.forEach { if number < $0 { number = $0 } } return number } private static func MA(_ days: Int, currentIndex: Int, in nodes: [KlineNode]) -> Float { if currentIndex < days - 1 { return 0 } let sum = ((currentIndex + 1 - days)...currentIndex).reduce(0) { return $0 + nodes[$1].close } return sum / Float(days) } private static func EMA(_ days: Int, close: Float, yesterdayEMA: Double) -> Double { let a = 2 / Double(days + 1) return a * Double(close) + (1 - a) * yesterdayEMA } } public struct KlineCalculateResult { /// 节点中最低价格 let minPrice: Float /// 节点中最高价格 let maxPrice: Float let minLow: Float let maxHigh: Float /// 最高成交量 let maxBusinessAmount: Float let minBusinessAmount: Float /// MACD指标最小值 let minMACD: Double /// MACD指标最大值 let maxMACD: Double /// KDJ指标 let minKDJ: Double let maxKDJ: Double /// WR指标 let minWR: Double let maxWR: Double let minRSI: Double let maxRSI: Double } public struct TimeLineCalculateResult { /// 节点中最低价格 let minPrice: Float /// 节点中最高价格 let maxPrice: Float /// 最高成交量 let maxBusinessAmount: Float let minBusinessAmount: Float } public class KlineNode { /// 时间 public var time = "" /// 最高价格 public var high: Float = 0 /// 最低价格 public var low: Float = 0 /// 开盘价 public var open: Float = 0 /// 收盘价 public var close: Float = 0 /// 昨收价 public var yesterdayClose: Float = 0 /// 成交量 public var businessAmount: Float = 0 /// 成交额 public var businessBalance: Float = 0 /// 振幅 public var amplitude: Float = -Float.greatestFiniteMagnitude /// 换手率 public var turnoverRate: Float = -Float.greatestFiniteMagnitude /// 涨跌幅 (今收盘-昨收盘)/昨收盘*100% public var changeRate: Float = 0 /// 五日均价 public var MA5: Float = 0 /// 十日均价 public var MA10: Float = 0 /// 三十日均价 public var MA30: Float = 0 /// EMA12 public var EMA1: Double = 0 /// EMA26 public var EMA2: Double = 0 public var DIFF: Double = 0 public var DEA: Double = 0 public var MACD: Double = 0 /// KDJ public var K: Double = 0 public var D: Double = 0 public var J: Double = 0 /// WR public var WR: Double = 0 /// RSI指标 public var RSI6: Double = 0 public var RSI12: Double = 0 public var RSI24: Double = 0 public var isIncrease: Bool = false//? { // if close > open { // return true // } // else if close < open { // return false // } // else { return nil } //// return close >= open // } public init() { } } public class TimeLineNode { /// 昨收 public var closePrice: Float = 0 /// 前一个节点的价格(如果是第一个节点,使用昨收价) public var beforeNode: TimeLineNode? /// 时间 public var time = "" /// 分时均价 public var avgPrice: Float = 0 /// 价格 public var price: Float = 0 /// 成交量 public var businessAmount: Float = 0 /// 总成交量 public var sumBusinessAmount: Float = 0 /// 涨 跌 public var isIncrease: Bool { if let beforeNode = beforeNode { if price > beforeNode.price { return true } else if price == beforeNode.price { return beforeNode.isIncrease } else { return false } } else { return price >= closePrice } } public init() { } }
37.034031
313
0.556938
71d19291ef70f861db577f4b5a2cb4841285e5d5
38,538
// // JulianDate.swift // CesiumKit // // Created by Ryan Walklin on 19/12/2015. // Copyright © 2015 Test Toast. All rights reserved. // import Foundation /** * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC). * For increased precision, this class stores the whole number part of the date and the seconds * part of the date in separate components. In order to be safe for arithmetic and represent * leap seconds, the date is always stored in the International Atomic Time standard * {@link TimeStandard.TAI}. * @alias JulianDate * @constructor * * @param {Number} julianDayNumber The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly. * @param {Number} secondsOfDay The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined. */ public struct JulianDate { /** * Gets or sets the number of whole days. * @type {Number} */ public fileprivate (set) var dayNumber: Int = -1 /** * Gets or sets the number of seconds into the current day. * @type {Number} */ public fileprivate (set) var secondsOfDay: Double = Double.nan public init (julianDayNumber: Double = 0.0, secondsOfDay: Double = 0.0, timeStandard: TimeStandard = .utc) { //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented. let wholeDays = julianDayNumber.wholeComponent let secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SecondsPerDay setComponents(Int(wholeDays), secondsOfDay: secondsOfDay) if timeStandard == .utc { convertUtcToTai() } } public init (fromNSDate date: Date) { let components = date.computeJulianDateComponents() self.init(julianDayNumber: Double(components.dayNumber), secondsOfDay: components.secondsOfDay, timeStandard: .utc) } /* var gregorianDateScratch = new GregorianDate(); var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var daysInLeapFeburary = 29; */ fileprivate func compareLeapSecondDates (_ leapSecond: LeapSecond, dateToFind: LeapSecond) -> Int { return Int(leapSecond.julianDate.compare(dateToFind.julianDate)) } func convertUtcToTai() -> JulianDate { //Even though julianDate is in UTC, we'll treat it as TAI and //search the leap second table for it. // we don't really need a leap second instance, anything with a julianDate property will do let binarySearchScratchLeapSecond = LeapSecond(julianDate: self, offset: 0) var index = JulianDate._leapSeconds.binarySearch(binarySearchScratchLeapSecond, comparator: compareLeapSecondDates) if (index < 0) { index = ~index } if index >= JulianDate._leapSeconds.count { index = JulianDate._leapSeconds.count - 1 } var offset = Double(JulianDate._leapSeconds[index].offset) if index > 0 { //Now we have the index of the closest leap second that comes on or after our UTC time. //However, if the difference between the UTC date being converted and the TAI //defined leap second is greater than the offset, we are off by one and need to use //the previous leap second. let difference = JulianDate._leapSeconds[index].julianDate.secondsDifference(self) if difference > offset { index -= 1 offset = Double(JulianDate._leapSeconds[index].offset) } } return self.addSeconds(offset) } /* function convertTaiToUtc(julianDate, result) { binarySearchScratchLeapSecond.julianDate = julianDate; var leapSeconds = JulianDate.leapSeconds; var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates); if (index < 0) { index = ~index; } //All times before our first leap second get the first offset. if (index === 0) { return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result); } //All times after our leap second get the last offset. if (index >= leapSeconds.length) { return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result); } //Compute the difference between the found leap second and the time we are converting. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate); if (difference === 0) { //The date is in our leap second table. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result); } if (difference <= 1.0) { //The requested date is during the moment of a leap second, then we cannot convert to UTC return undefined; } //The time is in between two leap seconds, index is the leap second after the date //we're converting, so we subtract one to get the correct LeapSecond instance. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result); } */ mutating func setComponents(_ wholeDays: Int, secondsOfDay: Double) { let extraDays = Int(trunc(secondsOfDay / TimeConstants.SecondsPerDay)) var wholeDays = wholeDays + extraDays var secondsOfDay = secondsOfDay - TimeConstants.SecondsPerDay * Double(extraDays) if secondsOfDay < 0 { wholeDays -= 1 secondsOfDay += TimeConstants.SecondsPerDay } self.dayNumber = wholeDays self.secondsOfDay = secondsOfDay } /* //Regular expressions used for ISO8601 date parsing. //YYYY var matchCalendarYear = /^(\d{4})$/; //YYYY-MM (YYYYMM is invalid) var matchCalendarMonth = /^(\d{4})-(\d{2})$/; //YYYY-DDD or YYYYDDD var matchOrdinalDate = /^(\d{4})-?(\d{3})$/; //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/; //YYYY-MM-DD or YYYYMMDD var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/; // Match utc offset var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/; // Match hours HH or HH.xxxxx var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source; // Match hours/minutes HH:MM HHMM.xxxxx var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source; // Match hours/minutes HH:MM:SS HHMMSS.xxxxx var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source; var iso8601ErrorMessage = 'Invalid ISO 8601 date.'; /** * Creates a new instance from a JavaScript Date. * * @param {Date} date A JavaScript Date. * @param {JulianDate} [result] An existing instance to use for the result. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. * * @exception {DeveloperError} date must be a valid JavaScript Date. */ JulianDate.fromDate = function(date, result) { //>>includeStart('debug', pragmas.debug); if (!(date instanceof Date) || isNaN(date.getTime())) { throw new DeveloperError('date must be a valid JavaScript Date.'); } //>>includeEnd('debug'); var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); if (!defined(result)) { return new JulianDate(components[0], components[1], TimeStandard.UTC); } setComponents(components[0], components[1], result); convertUtcToTai(result); return result; }; /** * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601 * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations. * * @param {String} iso8601String An ISO 8601 date. * @param {JulianDate} [result] An existing instance to use for the result. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. * * @exception {DeveloperError} Invalid ISO 8601 date. */ JulianDate.fromIso8601 = function(iso8601String, result) { //>>includeStart('debug', pragmas.debug); if (typeof iso8601String !== 'string') { throw new DeveloperError(iso8601ErrorMessage); } //>>includeEnd('debug'); //Comma and decimal point both indicate a fractional number according to ISO 8601, //start out by blanket replacing , with . which is the only valid such symbol in JS. iso8601String = iso8601String.replace(',', '.'); //Split the string into its date and time components, denoted by a mandatory T var tokens = iso8601String.split('T'); var year; var month = 1; var day = 1; var hour = 0; var minute = 0; var second = 0; var millisecond = 0; //Lacking a time is okay, but a missing date is illegal. var date = tokens[0]; var time = tokens[1]; var tmp; var inLeapYear; if (!defined(date)) { throw new DeveloperError(iso8601ErrorMessage); } var dashCount; //First match the date against possible regular expressions. tokens = date.match(matchCalendarDate); if (tokens !== null) { dashCount = date.split('-').length - 1; if (dashCount > 0 && dashCount !== 2) { throw new DeveloperError(iso8601ErrorMessage); } year = +tokens[1]; month = +tokens[2]; day = +tokens[3]; } else { tokens = date.match(matchCalendarMonth); if (tokens !== null) { year = +tokens[1]; month = +tokens[2]; } else { tokens = date.match(matchCalendarYear); if (tokens !== null) { year = +tokens[1]; } else { //Not a year/month/day so it must be an ordinal date. var dayOfYear; tokens = date.match(matchOrdinalDate); if (tokens !== null) { year = +tokens[1]; dayOfYear = +tokens[2]; inLeapYear = isLeapYear(year); //This validation is only applicable for this format. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) { throw new DeveloperError(iso8601ErrorMessage); } } else { tokens = date.match(matchWeekDate); if (tokens !== null) { //ISO week date to ordinal date from //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775 year = +tokens[1]; var weekNumber = +tokens[2]; var dayOfWeek = +tokens[3] || 0; dashCount = date.split('-').length - 1; if (dashCount > 0 && ((!defined(tokens[3]) && dashCount !== 1) || (defined(tokens[3]) && dashCount !== 2))) { throw new DeveloperError(iso8601ErrorMessage); } var january4 = new Date(Date.UTC(year, 0, 4)); dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3; } else { //None of our regular expressions succeeded in parsing the date properly. throw new DeveloperError(iso8601ErrorMessage); } } //Split an ordinal date into month/day. tmp = new Date(Date.UTC(year, 0, 1)); tmp.setUTCDate(dayOfYear); month = tmp.getUTCMonth() + 1; day = tmp.getUTCDate(); } } } //Now that we have all of the date components, validate them to make sure nothing is out of range. inLeapYear = isLeapYear(year); if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) { throw new DeveloperError(iso8601ErrorMessage); } //Not move onto the time string, which is much simpler. var offsetIndex; if (defined(time)) { tokens = time.match(matchHoursMinutesSeconds); if (tokens !== null) { dashCount = time.split(':').length - 1; if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) { throw new DeveloperError(iso8601ErrorMessage); } hour = +tokens[1]; minute = +tokens[2]; second = +tokens[3]; millisecond = +(tokens[4] || 0) * 1000.0; offsetIndex = 5; } else { tokens = time.match(matchHoursMinutes); if (tokens !== null) { dashCount = time.split(':').length - 1; if (dashCount > 0 && dashCount !== 1) { throw new DeveloperError(iso8601ErrorMessage); } hour = +tokens[1]; minute = +tokens[2]; second = +(tokens[3] || 0) * 60.0; offsetIndex = 4; } else { tokens = time.match(matchHours); if (tokens !== null) { hour = +tokens[1]; minute = +(tokens[2] || 0) * 60.0; offsetIndex = 3; } else { throw new DeveloperError(iso8601ErrorMessage); } } } //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) { throw new DeveloperError(iso8601ErrorMessage); } //Check the UTC offset value, if no value exists, use local time //a Z indicates UTC, + or - are offsets. var offset = tokens[offsetIndex]; var offsetHours = +(tokens[offsetIndex + 1]); var offsetMinutes = +(tokens[offsetIndex + 2] || 0); switch (offset) { case '+': hour = hour - offsetHours; minute = minute - offsetMinutes; break; case '-': hour = hour + offsetHours; minute = minute + offsetMinutes; break; case 'Z': break; default: minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset(); break; } } else { //If no time is specified, it is considered the beginning of the day, local time. minute = minute + new Date(year, month - 1, day).getTimezoneOffset(); } //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds. //If that's the case, we need to temporarily subtract a second in order to build a UTC date. //Then we add it back in after converting to TAI. var isLeapSecond = second === 60; if (isLeapSecond) { second--; } //Even if we successfully parsed the string into its components, after applying UTC offset or //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes while (minute >= 60) { minute -= 60; hour++; } while (hour >= 24) { hour -= 24; day++; } tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1]; while (day > tmp) { day -= tmp; month++; if (month > 12) { month -= 12; year++; } tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1]; } //If UTC offset is at the beginning/end of the day, minutes can be negative. while (minute < 0) { minute += 60; hour--; } while (hour < 0) { hour += 24; day--; } while (day < 1) { month--; if (month < 1) { month += 12; year--; } tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1]; day += tmp; } //Now create the JulianDate components from the Gregorian date and actually create our instance. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond); if (!defined(result)) { result = new JulianDate(components[0], components[1], TimeStandard.UTC); } else { setComponents(components[0], components[1], result); convertUtcToTai(result); } //If we were on a leap second, add it back. if (isLeapSecond) { JulianDate.addSeconds(result, 1, result); } return result; }; */ /** * Creates a new instance that represents the current system time. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>. * * @param {JulianDate} [result] An existing instance to use for the result. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. */ static func now () -> JulianDate { return JulianDate(fromNSDate: Date()) } /* var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI); /** * Creates a {@link GregorianDate} from the provided instance. * * @param {JulianDate} julianDate The date to be converted. * @param {GregorianDate} [result] An existing instance to use for the result. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided. */ JulianDate.toGregorianDate = function(julianDate, result) { //>>includeStart('debug', pragmas.debug); if (!defined(julianDate)) { throw new DeveloperError('julianDate is required.'); } //>>includeEnd('debug'); var isLeapSecond = false; var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch); if (!defined(thisUtc)) { //Conversion to UTC will fail if we are during a leap second. //If that's the case, subtract a second and convert again. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch); thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch); isLeapSecond = true; } var julianDayNumber = thisUtc.dayNumber; var secondsOfDay = thisUtc.secondsOfDay; if (secondsOfDay >= 43200.0) { julianDayNumber += 1; } // Algorithm from page 604 of the Explanatory Supplement to the // Astronomical Almanac (Seidelmann 1992). var L = (julianDayNumber + 68569) | 0; var N = (4 * L / 146097) | 0; L = (L - (((146097 * N + 3) / 4) | 0)) | 0; var I = ((4000 * (L + 1)) / 1461001) | 0; L = (L - (((1461 * I) / 4) | 0) + 31) | 0; var J = ((80 * L) / 2447) | 0; var day = (L - (((2447 * J) / 80) | 0)) | 0; L = (J / 11) | 0; var month = (J + 2 - 12 * L) | 0; var year = (100 * (N - 49) + I + L) | 0; var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0; var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR); var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0; remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE); var second = remainingSeconds | 0; var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND); // JulianDates are noon-based hour += 12; if (hour > 23) { hour -= 24; } //If we were on a leap second, add it back. if (isLeapSecond) { second += 1; } if (!defined(result)) { return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond); } result.year = year; result.month = month; result.day = day; result.hour = hour; result.minute = minute; result.second = second; result.millisecond = millisecond; result.isLeapSecond = isLeapSecond; return result; }; /** * Creates a JavaScript Date from the provided instance. * Since JavaScript dates are only accurate to the nearest millisecond and * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead. * If the provided JulianDate is during a leap second, the previous second is used. * * @param {JulianDate} julianDate The date to be converted. * @returns {Date} A new instance representing the provided date. */ JulianDate.toDate = function(julianDate) { //>>includeStart('debug', pragmas.debug); if (!defined(julianDate)) { throw new DeveloperError('julianDate is required.'); } //>>includeEnd('debug'); var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch); var second = gDate.second; if (gDate.isLeapSecond) { second -= 1; } return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond)); }; /** * Creates an ISO8601 representation of the provided date. * * @param {JulianDate} julianDate The date to be converted. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used. * @returns {String} The ISO8601 representation of the provided date. */ JulianDate.toIso8601 = function(julianDate, precision) { //>>includeStart('debug', pragmas.debug); if (!defined(julianDate)) { throw new DeveloperError('julianDate is required.'); } //>>includeEnd('debug'); var gDate = JulianDate.toGregorianDate(julianDate, gDate); var millisecondStr; if (!defined(precision) && gDate.millisecond !== 0) { //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', ''); return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr); } //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely if (!defined(precision) || precision === 0) { return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second); } //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision); return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr); }; /** * Duplicates a JulianDate instance. * * @param {JulianDate} julianDate The date to duplicate. * @param {JulianDate} [result] An existing instance to use for the result. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined. */ JulianDate.clone = function(julianDate, result) { if (!defined(julianDate)) { return undefined; } if (!defined(result)) { return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI); } result.dayNumber = julianDate.dayNumber; result.secondsOfDay = julianDate.secondsOfDay; return result; }; */ /** * Compares two instances. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal. */ func compare (_ other: JulianDate) -> Int { let julianDayNumberDifference = self.dayNumber - other.dayNumber if (julianDayNumberDifference != 0) { return julianDayNumberDifference } return Int(trunc(self.secondsOfDay - other.secondsOfDay)) } /* /** * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {JulianDate} [left] The first instance. * @param {JulianDate} [right] The second instance. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>. */ JulianDate.equals = function(left, right) { return (left === right) || (defined(left) && defined(right) && left.dayNumber === right.dayNumber && left.secondsOfDay === right.secondsOfDay); }; /** * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of * each other. That is, in order for the dates to be considered equal (and for * this function to return <code>true</code>), the absolute value of the difference between them, in * seconds, must be less than <code>epsilon</code>. * * @param {JulianDate} [left] The first instance. * @param {JulianDate} [right] The second instance. * @param {Number} epsilon The maximum number of seconds that should separate the two instances. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>. */ JulianDate.equalsEpsilon = function(left, right, epsilon) { //>>includeStart('debug', pragmas.debug); if (!defined(epsilon)) { throw new DeveloperError('epsilon is required.'); } //>>includeEnd('debug'); return (left === right) || (defined(left) && defined(right) && Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon); }; */ /** * Computes the total number of whole and fractional days represented by the provided instance. * * @param {JulianDate} julianDate The date. * @returns {Number} The Julian date as single floating point number. */ func totalDays () -> Double { return Double(dayNumber) + (secondsOfDay / TimeConstants.SecondsPerDay) } /** * Computes the difference in seconds between the provided instance. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>. */ func secondsDifference (_ other: JulianDate) -> Double { let dayDifference = Double(self.dayNumber - other.dayNumber) * TimeConstants.SecondsPerDay return dayDifference + (self.secondsOfDay - other.secondsOfDay) } /* /** * Computes the difference in days between the provided instance. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>. */ JulianDate.daysDifference = function(left, right) { //>>includeStart('debug', pragmas.debug); if (!defined(left)) { throw new DeveloperError('left is required.'); } if (!defined(right)) { throw new DeveloperError('right is required.'); } //>>includeEnd('debug'); var dayDifference = (left.dayNumber - right.dayNumber); var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY; return dayDifference + secondDifference; }; */ /** * Computes the number of seconds the provided instance is ahead of UTC. * * @param {JulianDate} julianDate The date. * @returns {Number} The number of seconds the provided instance is ahead of UTC */ func computeTaiMinusUtc () -> Int { let binarySearchScratchLeapSecond = LeapSecond(julianDate: self, offset: 0) var index = JulianDate._leapSeconds.binarySearch(binarySearchScratchLeapSecond, comparator: compareLeapSecondDates) if index < 0 { index = ~index index -= 1 if (index < 0) { index = 0 } } return JulianDate._leapSeconds[index].offset } /** * Adds the provided number of seconds to the provided date instance. * * @param {JulianDate} julianDate The date. * @param {Number} seconds The number of seconds to add or subtract. * @param {JulianDate} result An existing instance to use for the result. * @returns {JulianDate} The modified result parameter. */ func addSeconds (_ seconds: Double) -> JulianDate { return JulianDate(julianDayNumber: Double(self.dayNumber), secondsOfDay: secondsOfDay + seconds, timeStandard: .tai) } /* /** * Adds the provided number of minutes to the provided date instance. * * @param {JulianDate} julianDate The date. * @param {Number} minutes The number of minutes to add or subtract. * @param {JulianDate} result An existing instance to use for the result. * @returns {JulianDate} The modified result parameter. */ JulianDate.addMinutes = function(julianDate, minutes, result) { //>>includeStart('debug', pragmas.debug); if (!defined(julianDate)) { throw new DeveloperError('julianDate is required.'); } if (!defined(minutes)) { throw new DeveloperError('minutes is required.'); } if (!defined(result)) { throw new DeveloperError('result is required.'); } //>>includeEnd('debug'); var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE); return setComponents(julianDate.dayNumber, newSecondsOfDay, result); }; /** * Adds the provided number of hours to the provided date instance. * * @param {JulianDate} julianDate The date. * @param {Number} hours The number of hours to add or subtract. * @param {JulianDate} result An existing instance to use for the result. * @returns {JulianDate} The modified result parameter. */ JulianDate.addHours = function(julianDate, hours, result) { //>>includeStart('debug', pragmas.debug); if (!defined(julianDate)) { throw new DeveloperError('julianDate is required.'); } if (!defined(hours)) { throw new DeveloperError('hours is required.'); } if (!defined(result)) { throw new DeveloperError('result is required.'); } //>>includeEnd('debug'); var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR); return setComponents(julianDate.dayNumber, newSecondsOfDay, result); }; */ /** * Adds the provided number of days to the provided date instance. * * @param {JulianDate} julianDate The date. * @param {Number} days The number of days to add or subtract. * @param {JulianDate} result An existing instance to use for the result. * @returns {JulianDate} The modified result parameter. */ func addDays (_ days: Double) -> JulianDate { return JulianDate(julianDayNumber: Double(self.dayNumber) + days, secondsOfDay: self.secondsOfDay) } /** * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise. */ func lessThan (_ other: JulianDate) -> Bool { return self.compare(other) < 0 } /** * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise. */ func lessThanOrEquals (_ other: JulianDate) -> Bool { return self.compare(other) <= 0 } /** * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise. */ func greaterThan (_ other: JulianDate) -> Bool { return self.compare(other) > 0 } /** * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise. * * @param {JulianDate} left The first instance. * @param {JulianDate} right The second instance. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise. */ func greaterThanOrEquals (_ other: JulianDate) -> Bool { return self.compare(other) >= 0 } /* /** * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {JulianDate} [right] The second instance. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>. */ JulianDate.prototype.equals = function(right) { return JulianDate.equals(this, right); }; /** * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of * each other. That is, in order for the dates to be considered equal (and for * this function to return <code>true</code>), the absolute value of the difference between them, in * seconds, must be less than <code>epsilon</code>. * * @param {JulianDate} [right] The second instance. * @param {Number} epsilon The maximum number of seconds that should separate the two instances. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>. */ JulianDate.prototype.equalsEpsilon = function(right, epsilon) { return JulianDate.equalsEpsilon(this, right, epsilon); }; /** * Creates a string representing this date in ISO8601 format. * * @returns {String} A string representing this date in ISO8601 format. */ JulianDate.prototype.toString = function() { return JulianDate.toIso8601(this); }; */ /** * Gets or sets the list of leap seconds used throughout Cesium. * @memberof JulianDate * @type {LeapSecond[]} */ static fileprivate let _leapSeconds = [ LeapSecond(julianDate: JulianDate(julianDayNumber: 2441317, secondsOfDay: 43210.0, timeStandard: .tai), offset: 10), // January 1, 1972 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2441499, secondsOfDay: 43211.0, timeStandard: .tai), offset: 11), // July 1, 1972 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2441683, secondsOfDay: 43212.0, timeStandard: .tai), offset: 12), // January 1, 1973 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2442048, secondsOfDay: 43213.0, timeStandard: .tai), offset: 13), // January 1, 1974 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2442413, secondsOfDay: 43214.0, timeStandard: .tai), offset: 14), // January 1, 1975 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2442778, secondsOfDay: 43215.0, timeStandard: .tai), offset: 15), // January 1, 1976 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2443144, secondsOfDay: 43216.0, timeStandard: .tai), offset: 16), // January 1, 1977 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2443509, secondsOfDay: 43217.0, timeStandard: .tai), offset: 17), // January 1, 1978 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2443874, secondsOfDay: 43218.0, timeStandard: .tai), offset: 18), // January 1, 1979 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2444239, secondsOfDay: 43219.0, timeStandard: .tai), offset: 19), // January 1, 1980 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2444786, secondsOfDay: 43220.0, timeStandard: .tai), offset: 20), // July 1, 1981 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2445151, secondsOfDay: 43221.0, timeStandard: .tai), offset: 21), // July 1, 1982 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2445516, secondsOfDay: 43222.0, timeStandard: .tai), offset: 22), // July 1, 1983 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2446247, secondsOfDay: 43223.0, timeStandard: .tai), offset: 23), // July 1, 1985 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2447161, secondsOfDay: 43224.0, timeStandard: .tai), offset: 24), // January 1, 1988 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2447892, secondsOfDay: 43225.0, timeStandard: .tai), offset: 25), // January 1, 1990 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2448257, secondsOfDay: 43226.0, timeStandard: .tai), offset: 26), // January 1, 1991 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2448804, secondsOfDay: 43227.0, timeStandard: .tai), offset: 27), // July 1, 1992 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2449169, secondsOfDay: 43228.0, timeStandard: .tai), offset: 28), // July 1, 1993 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2449534, secondsOfDay: 43229.0, timeStandard: .tai), offset: 29), // July 1, 1994 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2450083, secondsOfDay: 43230.0, timeStandard: .tai), offset: 30), // January 1, 1996 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2450630, secondsOfDay: 43231.0, timeStandard: .tai), offset: 31), // July 1, 1997 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2451179, secondsOfDay: 43232.0, timeStandard: .tai), offset: 32), // January 1, 1999 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2453736, secondsOfDay: 43233.0, timeStandard: .tai), offset: 33), // January 1, 2006 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2454832, secondsOfDay: 43234.0, timeStandard: .tai), offset: 34), // January 1, 2009 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2456109, secondsOfDay: 43235.0, timeStandard: .tai), offset: 35), // July 1, 2012 00:00:00 UTC LeapSecond(julianDate: JulianDate(julianDayNumber: 2457204, secondsOfDay: 43236.0, timeStandard: .tai), offset: 36) // July 1, 2015 00:00:00 UTC ] }
41.3942
206
0.660128
bbdeb9132bfe2baf7ed2f41de45290ba7b6aedbf
996
// // File.swift // // // Created by Grady Zhuo on 2020/3/22. // import Foundation extension String { public func effect(textColor: TextColor? = nil, backgroundColor:BackgroundColor? = nil, styles: Style...)->ShellText{ var shellText = ShellText(self) if let textColor = textColor{ shellText.textColor = textColor } if let backgroundColor = backgroundColor{ shellText.backgroundColor = backgroundColor } shellText.styles = styles return shellText } } extension ShellText { public func effect(textColor: TextColor? = nil, backgroundColor:BackgroundColor? = nil, styles: Style...)->ShellText{ var shellText = self if let textColor = textColor{ shellText.textColor = textColor } if let backgroundColor = backgroundColor{ shellText.backgroundColor = backgroundColor } shellText.styles = styles return shellText } }
25.538462
121
0.628514
33bf7890c9a8889ac1855357139983386ddad1f7
5,167
import Cartography import Nimble import Quick class DimensionSpec: QuickSpec { override func spec() { var window: TestWindow! var view: TestView! beforeEach { window = TestWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) view = TestView(frame: CGRect.zero) window.addSubview(view) } describe("LayoutProxy.width") { it("should support relative equalities") { cg_constrain(view) { view in view.width == view.superview!.width } window.layoutIfNeeded() expect(view.frame.width).to(equal(400)) } it("should support relative inequalities") { cg_constrain(view) { view in view.width <= view.superview!.width view.width >= view.superview!.width } window.layoutIfNeeded() expect(view.frame.width).to(equal(400)) } it("should support addition") { cg_constrain(view) { view in view.width == view.superview!.width + 100 } window.layoutIfNeeded() expect(view.frame.width).to(equal(500)) } it("should support subtraction") { cg_constrain(view) { view in view.width == view.superview!.width - 100 } window.layoutIfNeeded() expect(view.frame.width).to(equal(300)) } it("should support multiplication") { cg_constrain(view) { view in view.width == view.superview!.width * 2 } window.layoutIfNeeded() expect(view.frame.width).to(equal(800)) } it("should support division") { cg_constrain(view) { view in view.width == view.superview!.width / 2 } window.layoutIfNeeded() expect(view.frame.width).to(equal(200)) } it("should support complex expressions") { cg_constrain(view) { view in view.width == view.superview!.width / 2 + 100 } window.layoutIfNeeded() expect(view.frame.width).to(equal(300)) } it("should support numerical equalities") { cg_constrain(view) { view in view.width == 200 } window.layoutIfNeeded() expect(view.frame.width).to(equal(200)) } } describe("LayoutProxy.height") { it("should support relative equalities") { cg_constrain(view) { view in view.height == view.superview!.height } window.layoutIfNeeded() expect(view.frame.height).to(equal(400)) } it("should support relative inequalities") { cg_constrain(view) { view in view.height <= view.superview!.height view.height >= view.superview!.height } window.layoutIfNeeded() expect(view.frame.height).to(equal(400)) } it("should support addition") { cg_constrain(view) { view in view.height == view.superview!.height + 100 } window.layoutIfNeeded() expect(view.frame.height).to(equal(500)) } it("should support subtraction") { cg_constrain(view) { view in view.height == view.superview!.height - 100 } window.layoutIfNeeded() expect(view.frame.height).to(equal(300)) } it("should support multiplication") { cg_constrain(view) { view in view.height == view.superview!.height * 2 } window.layoutIfNeeded() expect(view.frame.height).to(equal(800)) } it("should support division") { cg_constrain(view) { view in view.height == view.superview!.height / 2 } window.layoutIfNeeded() expect(view.frame.height).to(equal(200)) } it("should support complex expressions") { cg_constrain(view) { view in view.height == view.superview!.height / 2 + 100 } window.layoutIfNeeded() expect(view.frame.height).to(equal(300)) } it("should support numerical equalities") { cg_constrain(view) { view in view.height == 200 } window.layoutIfNeeded() expect(view.frame.height).to(equal(200)) } } } }
27.92973
83
0.464486
16142e09d6dd83a217b23011455c04ca427cfc3f
1,010
// // PlaceCommentsRouterTests.swift // Travelling // // Created by Dimitri Strauneanu on 12/10/2020. // Copyright (c) 2020 Travelling. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // @testable import Travelling import XCTest class PlaceCommentsRouterTests: XCTestCase { var sut: PlaceCommentsRouter! var viewController: PlaceCommentsViewController! // MARK: - Test lifecycle override func setUp() { super.setUp() self.setupPlaceCommentsRouter() } override func tearDown() { super.tearDown() } // MARK: - Test setup func setupPlaceCommentsRouter() { self.sut = PlaceCommentsRouter() self.viewController = PlaceCommentsViewController(placeId: "placeId") self.sut.viewController = self.viewController } // MARK: - Tests }
22.954545
77
0.654455
dd4ff02fdc8880781d7594f0d0d835dc31f23503
667
// // ConsoleLogger.swift // AlamofireNetworkActivityLogger // // Created by Sohayb Hassoun on 4/14/17. // Copyright © 2017 RKT Studio. All rights reserved. // import Foundation internal class ConsoleLogger: GenericLogger { func log(_ value: Any) -> Void { print(value) } func logDebug(_ value: Any) -> Void { print(value) } func logInfo(_ value: Any) -> Void { print(value) } func logWarning(_ value: Any) -> Void { print(value) } func logError(_ value: Any) -> Void { print(value) } func logFatal(_ value: Any) -> Void { print(value) } }
18.527778
53
0.565217
6706975b18f25cfcfde8e2c94c2287f1ef9d41b4
2,466
// // Copyright (c) 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import FirebaseCore import FirebaseDynamicLinks import FirebaseInAppMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Uncomment the following line to disable In-App Messaging auto-startup. // InAppMessaging.inAppMessaging().disable() FirebaseOptions.defaultOptions()?.deepLinkURLScheme = "com.google.InAppMessagingExampleSwiftiOS" FirebaseApp.configure() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation] as Any) } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) if dynamicLink != nil { if dynamicLink?.url != nil { // Handle the deep link. For example, show the deep-linked content, // apply a promotional offer to the user's account or show customized onboarding view. // ... } else { // Dynamic link has empty deep link. This situation will happens if // Firebase Dynamic Links iOS SDK tried to retrieve pending dynamic link, // but pending link is not available for this device/App combination. // At this point you may display default onboarding view. } return true } return false } }
36.264706
142
0.675588
5d083a3680ff323b20df6212df635e7957cdf734
1,855
// // ApiError.swift // DFApi // // Created by ihoudf on 2021/4/28. // import Foundation public enum ApiError: Swift.Error, CaseIterable { // *** 本地错误码 *** case ApiLocalErrorUnknown case ApiLocalErrorIllegalParams case ApiLocalErrorDataFormat case ApiLocalErrorNoLinkToNet case ApiLocalErrorTimedOut // *** 服务端错误码 *** case ApiServerErrorUnknown // 未知错误 // case ApiServerErrorCustom1 // case ApiServerErrorCustom2 } extension ApiError: CustomNSError { public static var errorDomain: String { return "ApiErrorDomain" } public var errorUserInfo: [String: Any] { var userInfo: [String: Any] = [:] userInfo[NSLocalizedDescriptionKey] = errorDescription return userInfo } public var errorCode: Int { switch self { // case .ApiLocalErrorUnknown: return -10000 case .ApiLocalErrorIllegalParams: return -10001 case .ApiLocalErrorDataFormat: return -10002 case .ApiLocalErrorNoLinkToNet: return -10003 case .ApiLocalErrorTimedOut: return -10004 // case .ApiServerErrorUnknown: return 1000 // case .ApiServerErrorCustom1: return 4001 // case .ApiServerErrorCustom2: return 4002 } } } extension ApiError: LocalizedError { public var errorDescription: String? { switch self { // case .ApiLocalErrorUnknown: return "未知错误" case .ApiLocalErrorIllegalParams: return "非法参数" case .ApiLocalErrorDataFormat: return "数据格式错误" case .ApiLocalErrorNoLinkToNet: return "没有网络连接" case .ApiLocalErrorTimedOut: return "请求超时" // case .ApiServerErrorUnknown: return "服务器异常,请稍后再试" // case .ApiServerErrorCustom1: return "错误1" // case .ApiServerErrorCustom2: return "错误2" } } }
26.884058
69
0.653369
39c811a0cc1ed5083369ce957000295cd8342b26
331
// // TransportLayer.swift // apduKit // // Created by Iain Munro on 04/09/2018. // Copyright © 2018 UL-TS. All rights reserved. // import Foundation protocol TransportLayer { func write(data: [byte]) throws func close() throws func set(delegate: TransportLayerDelegate) func onReceive(data: [byte]) throws }
19.470588
48
0.688822
4b3d4b7fe64f5a827ea49b9ab869fa34a82a72b0
1,574
// // MPBI_NEQ.swift // pbc // // Created by Scott Rong on 2018/7/22. // Copyright © 2018年 jadestudio. All rights reserved. // import Foundation class MPBI_NEQ: PBI { init(opercode: Int8) { super.init(catecode: 0, opercode: opercode) } static func create(operand1: Operand, operand2: Operand) -> MPBI_NEQ? { let type = Type.mixType(type1: operand1.type.type, type2: operand2.type.type) if (type == BOOLEANType) { return MPBI_NEQ_B() } else if (type == SHORTType) { return MPBI_NEQ_S() } else if (type == INTEGERType) { return MPBI_NEQ_I() } else if (type == LONGType) { return MPBI_NEQ_L() } else if (type == SINGLEType) { return MPBI_NEQ_F() } else if (type == DOUBLEType) { return MPBI_NEQ_D() } else if (type == STRINGType) { return MPBI_NEQ_T() } return nil } } class MPBI_NEQ_B: MPBI_NEQ { init() { super.init(opercode: 0xE) } } class MPBI_NEQ_S: MPBI_NEQ { init() { super.init(opercode: 0xF) } } class MPBI_NEQ_I: MPBI_NEQ { init() { super.init(opercode: 0x10) } } class MPBI_NEQ_L: MPBI_NEQ { init() { super.init(opercode: 0x11) } } class MPBI_NEQ_F: MPBI_NEQ { init() { super.init(opercode: 0x12) } } class MPBI_NEQ_D: MPBI_NEQ { init() { super.init(opercode: 0x13) } } class MPBI_NEQ_T: MPBI_NEQ { init() { super.init(opercode: 0x14) } }
19.924051
85
0.552732
87cb73eddbd5b9adee24348a1f8d1df19f2f8977
2,435
// // MIT License // // Copyright (c) 2018 Wojciech Nagrodzki // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import SwiftLogger class AgregateLoggerTests: XCTestCase { func testCallForwarding() { let loggerA = LoggerMock() let loggerB = LoggerMock() let agregateLogger = AgregateLogger(loggers: [loggerA, loggerB]) agregateLogger.log("0", level: .emergency) agregateLogger.log("1", level: .alert) agregateLogger.log("2", level: .critical) agregateLogger.log("3", level: .error) agregateLogger.log("4", level: .warning) agregateLogger.log("5", level: .notice) agregateLogger.log("6", level: .informational) agregateLogger.log("7", level: .debug) XCTAssertEqual(loggerA, loggerB) } } private class LoggerMock: Logger { struct Log: Equatable { let time: Date let level: LogLevel let location: String let message: String } private var logs = [Log]() func log(time: Date, level: LogLevel, location: String, message: @autoclosure () -> String) { let log = Log(time: time, level: level, location: location, message: message()) logs.append(log) } } extension LoggerMock: Equatable { static func == (lhs: LoggerMock, rhs: LoggerMock) -> Bool { return lhs.logs == rhs.logs } }
35.289855
97
0.685421
1e11a98c6562d780c7bd99260dff7caa6851fbec
183
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation protocol ___FILEBASENAMEASIDENTIFIER___ { }
14.076923
48
0.759563
209891f4833ea52dff4b06d2220a52ef831b0a8d
4,500
// // ABIRawType+Static.swift // web3swift // // Created by Matt Marshall on 10/04/2018. // Copyright © 2018 Argent Labs Limited. All rights reserved. // import Foundation import BigInt import EthereumAddress public protocol ABIType { } extension String: ABIType { } extension Bool: ABIType { } extension EthereumAddress: ABIType { } extension BigInt: ABIType { } extension BigUInt: ABIType { } extension Data: ABIType { } // TODO (U)Double. Function. Array. Other Int sizes extension Array: ABIType { } extension UInt8: ABIType { } extension UInt16: ABIType { } extension UInt32: ABIType { } extension UInt64: ABIType { } public protocol ABIFixedSizeDataType: ABIType { static var fixedSize: Int { get } } public struct Data1: ABIFixedSizeDataType { public static let fixedSize: Int = 1 } public struct Data2: ABIFixedSizeDataType { public static let fixedSize: Int = 2 } public struct Data3: ABIFixedSizeDataType { public static let fixedSize: Int = 3 } public struct Data4: ABIFixedSizeDataType { public static let fixedSize: Int = 4 } public struct Data5: ABIFixedSizeDataType { public static let fixedSize: Int = 5 } public struct Data6: ABIFixedSizeDataType { public static let fixedSize: Int = 6 } public struct Data7: ABIFixedSizeDataType { public static let fixedSize: Int = 7 } public struct Data8: ABIFixedSizeDataType { public static let fixedSize: Int = 8 } public struct Data9: ABIFixedSizeDataType { public static let fixedSize: Int = 9 } public struct Data10: ABIFixedSizeDataType { public static let fixedSize: Int = 10 } public struct Data11: ABIFixedSizeDataType { public static let fixedSize: Int = 11 } public struct Data12: ABIFixedSizeDataType { public static let fixedSize: Int = 12 } public struct Data13: ABIFixedSizeDataType { public static let fixedSize: Int = 13 } public struct Data14: ABIFixedSizeDataType { public static let fixedSize: Int = 14 } public struct Data15: ABIFixedSizeDataType { public static let fixedSize: Int = 15 } public struct Data16: ABIFixedSizeDataType { public static let fixedSize: Int = 16 } public struct Data17: ABIFixedSizeDataType { public static let fixedSize: Int = 17 } public struct Data18: ABIFixedSizeDataType { public static let fixedSize: Int = 18 } public struct Data19: ABIFixedSizeDataType { public static let fixedSize: Int = 19 } public struct Data20: ABIFixedSizeDataType { public static let fixedSize: Int = 20 } public struct Data21: ABIFixedSizeDataType { public static let fixedSize: Int = 21 } public struct Data22: ABIFixedSizeDataType { public static let fixedSize: Int = 22 } public struct Data23: ABIFixedSizeDataType { public static let fixedSize: Int = 23 } public struct Data24: ABIFixedSizeDataType { public static let fixedSize: Int = 24 } public struct Data25: ABIFixedSizeDataType { public static let fixedSize: Int = 25 } public struct Data26: ABIFixedSizeDataType { public static let fixedSize: Int = 26 } public struct Data27: ABIFixedSizeDataType { public static let fixedSize: Int = 27 } public struct Data28: ABIFixedSizeDataType { public static let fixedSize: Int = 28 } public struct Data29: ABIFixedSizeDataType { public static let fixedSize: Int = 29 } public struct Data30: ABIFixedSizeDataType { public static let fixedSize: Int = 30 } public struct Data31: ABIFixedSizeDataType { public static let fixedSize: Int = 31 } public struct Data32: ABIFixedSizeDataType { public static let fixedSize: Int = 32 } extension ABIRawType { init?(type: ABIType.Type) { switch type { case is String.Type: self = ABIRawType.DynamicString case is Bool.Type: self = ABIRawType.FixedBool case is EthereumAddress.Type: self = ABIRawType.FixedAddress case is BigInt.Type: self = ABIRawType.FixedInt(256) case is BigUInt.Type: self = ABIRawType.FixedUInt(256) case is UInt8.Type: self = ABIRawType.FixedUInt(8) case is UInt16.Type: self = ABIRawType.FixedUInt(16) case is UInt32.Type: self = ABIRawType.FixedUInt(32) case is UInt64.Type: self = ABIRawType.FixedUInt(64) case is Data.Type: self = ABIRawType.DynamicBytes case is ABIFixedSizeDataType.Type: guard let fixed = type as? ABIFixedSizeDataType.Type else { return nil } self = ABIRawType.FixedBytes(fixed.fixedSize) default: return nil } } }
25
84
0.723778
b9c499e042effb63ea0bb39adf3271cea28f9445
982
// // CalibraTests.swift // CalibraTests // // Created by Alexander Kolov on 11/15/15. // Copyright © 2015 Alexander Kolov. All rights reserved. // import XCTest @testable import Calibra class CalibraTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.540541
111
0.636456
ed5f55402e15d2ad9833a6b1afd541095f7de11a
610
// // TabBarView.swift // Planets // // Created by Ujjwal on 19/02/2021. // import SwiftUI struct TabBarView: View { var body: some View { TabView(selection: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Selection@*/.constant(1)/*@END_MENU_TOKEN@*/) { VStack{ PlanetList() } .tabItem { Text("Planets") }.tag(1) VStack{ PeopleList() }.tabItem { Text("People") }.tag(2) } } func myParents(){ } } struct TestSwiftUIView_Previews: PreviewProvider { static var previews: some View { TabBarView() } }
17.428571
109
0.554098
6a7ef7de87a4a359dd264fd11b7d935eaf27999c
497
// // ViewController.swift // FirstApp // // Created by MAC on 27/01/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.115385
80
0.665996
7af04a9dda00e7dfc40bb6ae23fc511773b54896
12,867
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPNativeTableViewController: SPBaseTableViewController { let labelTableViewCellIdentifier: String = "labelTableViewCellIdentifier" let textFieldTableViewCellIdentifier: String = "textFieldTableViewCellIdentifier" let buttonTableViewCellIdentifier: String = "buttonTableViewCellIdentifier" let textTableViewCellIdentifier: String = "textTableViewCellIdentifier" let textInputTableViewCellIdentifier: String = "textInputTableViewCellIdentifier" let promoTableViewCellIdentifier: String = "promoTableViewCellIdentifier" let featuredTitleTableViewCellIdentifier: String = "featuredTitleTableViewCellIdentifier" let mailTableViewCellIdentifier: String = "mailTableViewCellIdentifier" let collectionImagesTableViewCellIdentifier: String = "collectionImagesTableViewCellIdentifier" let imageTableViewCellIdentifier: String = "imageTableViewCellIdentifier" let proposeTableViewCellIdentifier: String = "proposeTableViewCellIdentifier" let mengTransformTableViewCell = "mengTransformTableViewCell" var showTopInsets: Bool = true var showBottomInsets: Bool = true var autoTopSpace: Bool = true var autoBottomSpace: Bool = true private var autoSpaceHeight: CGFloat = 35 init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.statusBar = .dark self.tableView = UITableView.init(frame: self.view.bounds, style: UITableView.Style.grouped) self.setPrefersLargeNavigationTitle("Title") if #available(iOS 11.0, *) { self.tableView.contentInsetAdjustmentBehavior = .always } self.tableView.backgroundColor = SPNativeStyleKit.Colors.customGray self.tableView.delaysContentTouches = false self.tableView.allowsSelection = false self.tableView.rowHeight = UITableView.automaticDimension self.tableView.sectionFooterHeight = UITableView.automaticDimension self.tableView.sectionHeaderHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 44 self.tableView.register(SPFormTextFiledTableViewCell.self, forCellReuseIdentifier: self.textFieldTableViewCellIdentifier) self.tableView.register(SPFormLabelTableViewCell.self, forCellReuseIdentifier: self.labelTableViewCellIdentifier) self.tableView.register(SPFormButtonTableViewCell.self, forCellReuseIdentifier: self.buttonTableViewCellIdentifier) self.tableView.register(SPFormTextTableViewCell.self, forCellReuseIdentifier: self.textTableViewCellIdentifier) self.tableView.register(SPFormTextInputTableViewCell.self, forCellReuseIdentifier: self.textInputTableViewCellIdentifier) self.tableView.register(SPPromoTableViewCell.self, forCellReuseIdentifier: self.promoTableViewCellIdentifier) self.tableView.register(SPFormFeaturedTitleTableViewCell.self, forCellReuseIdentifier: self.featuredTitleTableViewCellIdentifier) self.tableView.register(SPFormMailTableViewCell.self, forCellReuseIdentifier: self.mailTableViewCellIdentifier) self.tableView.register(SPCollectionImagesTableViewCell.self, forCellReuseIdentifier: self.collectionImagesTableViewCellIdentifier) self.tableView.register(SPImageTableViewCell.self, forCellReuseIdentifier: self.imageTableViewCellIdentifier) self.tableView.register(SPProposeTableViewCell.self, forCellReuseIdentifier: self.proposeTableViewCellIdentifier) self.tableView.register(SPMengTransformTableViewCell.self, forCellReuseIdentifier: self.mengTransformTableViewCell) self.activityIndicatorView.stopAnimating() self.activityIndicatorView.color = SPNativeStyleKit.Colors.gray self.view.addSubview(self.activityIndicatorView) self.updateLayout(with: self.view.frame.size) } override func numberOfSections(in tableView: UITableView) -> Int { return super.numberOfSections(in: tableView) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return super.tableView(tableView, numberOfRowsInSection: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError("SPNativeTableViewController - need ivveride cellForRowAt") } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return nil } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return nil } func dequeueTextFiledTableViewCell(indexPath: IndexPath) -> SPFormTextFiledTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.textFieldTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormTextFiledTableViewCell } func dequeueLabelTableViewCell(indexPath: IndexPath) -> SPFormLabelTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.labelTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormLabelTableViewCell } func dequeueButtonTableViewCell(indexPath: IndexPath) -> SPFormButtonTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.buttonTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormButtonTableViewCell } func dequeueTextTableViewCell(indexPath: IndexPath) -> SPFormTextTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.textTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormTextTableViewCell } func dequeueTextInputTableViewCell(indexPath: IndexPath) -> SPFormTextInputTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.textInputTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormTextInputTableViewCell cell.currentIndexPath = indexPath return cell } func dequeuePromoTableViewCell(indexPath: IndexPath? = nil) -> SPPromoTableViewCell { if indexPath == nil { return tableView.dequeueReusableCell(withIdentifier: self.promoTableViewCellIdentifier) as! SPPromoTableViewCell } else { return tableView.dequeueReusableCell(withIdentifier: self.promoTableViewCellIdentifier, for: indexPath! as IndexPath) as! SPPromoTableViewCell } } func dequeueFeaturedTitleTableViewCell(indexPath: IndexPath) -> SPFormFeaturedTitleTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.featuredTitleTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormFeaturedTitleTableViewCell } func dequeueMailTableViewCell(indexPath: IndexPath) -> SPFormMailTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.mailTableViewCellIdentifier, for: indexPath as IndexPath) as! SPFormMailTableViewCell cell.currentIndexPath = indexPath return cell } func dequeueCollectionImagesTableViewCell(indexPath: IndexPath) -> SPCollectionImagesTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.collectionImagesTableViewCellIdentifier, for: indexPath as IndexPath) as! SPCollectionImagesTableViewCell } func dequeueImageTableViewCell(indexPath: IndexPath) -> SPImageTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.imageTableViewCellIdentifier, for: indexPath as IndexPath) as! SPImageTableViewCell cell.currentIndexPath = indexPath return cell } func dequeueProposeTableViewCell(indexPath: IndexPath) -> SPProposeTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.proposeTableViewCellIdentifier, for: indexPath as IndexPath) as! SPProposeTableViewCell } func dequeueMengTransformTableViewCell(indexPath: IndexPath) -> SPMengTransformTableViewCell { return tableView.dequeueReusableCell(withIdentifier: self.mengTransformTableViewCell, for: indexPath as IndexPath) as! SPMengTransformTableViewCell } } //MARK: - manage selection extension SPNativeTableViewController { override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { if let _ = tableView.cellForRow(at: indexPath) as? SPFormFeaturedTitleTableViewCell { return false } return true } } //MARK: - manage spaces extension SPNativeTableViewController { override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return self.showTopInsets ? super.tableView(tableView, viewForHeaderInSection: section) : nil } else { return super.tableView(tableView, viewForHeaderInSection: section) } } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == self.tableView.lastSection { return self.showBottomInsets ? super.tableView(tableView, viewForFooterInSection: section) : nil } else { return super.tableView(tableView, viewForFooterInSection: section) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let firstSection = self.tableView.firstSectionWithRows if section == firstSection { if self.showTopInsets { if self.autoTopSpace { if self.tableView(self.tableView, viewForHeaderInSection: firstSection!) != nil { return UITableView.automaticDimension } if self.tableView(self.tableView, titleForHeaderInSection: firstSection!) != nil { return UITableView.automaticDimension } return self.autoSpaceHeight } else { return UITableView.automaticDimension } } else { return 0 } } else { if self.tableView.numberOfRows(inSection: section) == 0 { return 0 } else { return UITableView.automaticDimension } } } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == self.tableView.lastSectionWithRows { if self.showBottomInsets { if self.autoBottomSpace { if self.tableView(self.tableView, viewForFooterInSection: self.tableView.lastSectionWithRows!) != nil { return UITableView.automaticDimension } if self.tableView(self.tableView, titleForFooterInSection: self.tableView.lastSectionWithRows!) != nil { return UITableView.automaticDimension } return self.autoSpaceHeight } else { return UITableView.automaticDimension } } else { return 0 } } else { if self.tableView.numberOfRows(inSection: section) == 0 { return 0 } else { return UITableView.automaticDimension } } } }
49.679537
171
0.71765
e945714a7e0932d8c70c528a406ab5534ee34e97
991
// Playground - noun: a place where people can play import UIKit func generateParentheses(n: Int) -> [String] { var result = [String]() var path = [String]() helper(n, 0, 0, &path, &result) return result } func helper(n: Int, numLeft: Int, numRight: Int, inout path: [String], inout result: [String]) { if numLeft == n && numRight == n { result.append("".join(path)) } else { path if numLeft < n { path.append("(") helper(n, numLeft+1, numRight, &path, &result) path.removeLast() } if numRight < n && numRight < numLeft { path.append(")") helper(n, numLeft, numRight+1, &path, &result) path.removeLast() } } } generateParentheses(3) /*: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" */
30.030303
202
0.546922
4b08785cad9c6fa27bc35c7c6c264f565ed09063
8,320
// // PZSwipedCollectionViewCell.swift // PZSwipedCollectionViewCell // // Created by Pace.Z on 2017/7/18. // Copyright © 2017年 Pace.Z. All rights reserved. // import UIKit fileprivate extension UIView { func superView<T>(of type: T.Type) -> T? { return superview as? T ?? superview.flatMap { $0.superView(of: T.self) } } } // MARK: - fileprivate extension UICollectionView { struct AssociatedKeys { static var currentcell = "pz_currentCell" } var openingCell: PZSwipedCollectionViewCell? { get { return objc_getAssociatedObject(self, &AssociatedKeys.currentcell) as? PZSwipedCollectionViewCell } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.currentcell, newValue as PZSwipedCollectionViewCell?, .OBJC_ASSOCIATION_ASSIGN ) } } } } // MARK: - class PZSwipedCollectionViewCell: UICollectionViewCell,UIGestureRecognizerDelegate { typealias delete = (_ sender: UIButton) -> () // MARK: - public var revealView: UIView? func hideRevealView(withAnimated isAnimated:Bool) { UIView.animate(withDuration: isAnimated ? 0.1 : 0 , delay: 0, options: .curveEaseOut, animations: { self.snapShotView?.center = CGPoint(x: self.frame.width / 2, y: self.snapShotView!.center.y) }, completion: { (finished: Bool) in self.snapShotView?.removeFromSuperview() self.snapShotView = nil self.revealView?.removeFromSuperview() }) } /// only when you use the default reveal, you can use this method var delete: delete? // MARK: - private private var panGesture:UIPanGestureRecognizer! fileprivate var snapShotView:UIView? // MARK: life cycle override init(frame: CGRect) { super.init(frame: frame) configureGestureRecognizer() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureGestureRecognizer() } override func prepareForReuse() { super.prepareForReuse() self.snapShotView?.removeFromSuperview() self.snapShotView = nil self.revealView?.removeFromSuperview() } override func layoutSubviews() { super.layoutSubviews() guard let revealView = revealView else { return } revealView.frame = CGRect(origin: CGPoint(x: self.frame.width - revealView.frame.width, y: 0) , size: revealView.frame.size) } private func configureGestureRecognizer() { panGesture = UIPanGestureRecognizer(target: self, action: #selector(pzPanAction(panGestureRecognizer:))) panGesture.delegate = self self.addGestureRecognizer(panGesture) } // MARK: - UIGestureRecognizerDelegate override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isMember(of: UIPanGestureRecognizer.self) { let gesture:UIPanGestureRecognizer = gestureRecognizer as! UIPanGestureRecognizer let velocity = gesture.velocity(in: self) if abs(velocity.x) > abs(velocity.y) { return true } } return false } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return otherGestureRecognizer != self.superView(of: UICollectionView.self) } // MARK: - event response @objc private func pzPanAction(panGestureRecognizer: UIPanGestureRecognizer) { switch panGestureRecognizer.state { case .began: if self.revealView == nil { self._createDefaultRevealView() } if self.snapShotView == nil { self.snapShotView = self.snapshotView(afterScreenUpdates: false) if self.snapShotView?.backgroundColor == UIColor.clear || self.snapShotView?.backgroundColor == nil { self.snapShotView?.backgroundColor = UIColor.white } } guard let snapShotView = self.snapShotView else { return } self._closeOtherOpeningCell() self.addSubview(self.revealView!) self.addSubview(snapShotView) case .changed: let translationPoint = panGestureRecognizer.translation(in: self) var centerPoint = CGPoint(x: 0, y: self.snapShotView!.center.y) centerPoint.x = min( self.frame.width / 2, max(self.snapShotView!.center.x + translationPoint.x, self.frame.width/2 - self.revealView!.frame.width)) panGestureRecognizer.setTranslation(CGPoint.zero, in: self) self.snapShotView!.center = centerPoint case .ended, .cancelled: let velocity = panGestureRecognizer.velocity(in: self) if _bigThenRevealViewHalfWidth() || _shouldShowRevealView(forVelocity: velocity) { showRevealView(withAnimated: true) } if _lessThenRevealViewHalfWidth() || _shouldHideRevealView(forVelocity: velocity) { hideRevealView(withAnimated: true) } default: break } } private func _shouldHideRevealView(forVelocity velocity: CGPoint) -> Bool { guard let revealView = self.revealView else { return false } return abs(velocity.x) > revealView.frame.width / 2 && velocity.x > 0 } private func _shouldShowRevealView(forVelocity velocity: CGPoint) -> Bool { guard let revealView = self.revealView else { return false } return abs(velocity.x) > revealView.frame.width / 2 && velocity.x < 0; } private func _bigThenRevealViewHalfWidth() -> Bool { guard let revealView = self.revealView, let snapShotView = self.snapShotView else { return false } return abs(snapShotView.frame.width) >= revealView.frame.width / 2 } private func _lessThenRevealViewHalfWidth() -> Bool { guard let revealView = self.revealView, let snapShotView = self.snapShotView else { return false } return abs(snapShotView.frame.width) < revealView.frame.width / 2 } private func _closeOtherOpeningCell() { guard let superCollectionView = self.superView(of: UICollectionView.self) else { return } if superCollectionView.openingCell != self { if superCollectionView.openingCell != nil { superCollectionView.openingCell!.hideRevealView(withAnimated: true) } superCollectionView.openingCell = self } } private func _createDefaultRevealView() { let deleteButton = UIButton(frame: CGRect(x: self.bounds.height - 55, y: 0, width: 55, height: self.bounds.height)) deleteButton.backgroundColor = UIColor.init(red: 255/255.0, green: 58/255.0, blue: 58/255.0, alpha: 1) deleteButton.setTitle("delete", for: .normal) deleteButton.setTitleColor(UIColor.white, for: .normal) deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) deleteButton.addTarget(self, action: #selector(_deleteButtonTapped(sender:)), for: .touchUpInside) self.revealView = deleteButton } @objc private func _deleteButtonTapped(sender: UIButton) { self.hideRevealView(withAnimated: true) self.delete?(sender) } func showRevealView(withAnimated isAnimated:Bool) { UIView.animate(withDuration: isAnimated ? 0.1 : 0 , delay: 0, options: .curveEaseOut, animations: { self.snapShotView?.center = CGPoint(x: self.frame.width / 2 - self.revealView!.frame.width , y: self.snapShotView!.center.y) }, completion: { (finished: Bool) in }) } }
37.647059
160
0.615505
29ebac2cc2b247f256137ef52b25b8de35eae24d
17,152
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List<T>` is the container type in Realm used to define to-many relationships. Lists hold a single `Object` subclass (`T`) which defines the "type" of the List. Lists can be filtered and sorted with the same predicates as `Results<T>`. When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// Element type contained in this collection. public typealias Element = T // MARK: Properties /// The Realm the objects in this List belong to, or `nil` if the List's /// owning object does not belong to a Realm (the List is standalone). public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the List can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds objects of type `T`. public override init() { super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the List. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the List. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given `index` on get. Replaces the object at the given `index` on set. - warning: You can only set an object during a write transaction. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = unsafeBitCast(newValue, RLMObject.self) } } /// Returns the first object in the List, or `nil` if empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the List, or `nil` if empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. - parameter keyPath: The key path to the property. - returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. */ public override func valueForKeyPath(keyPath: String) -> AnyObject? { return _rlmArray.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns `Results` containing elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns `Results` containing elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` containing elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing elements sorted by the given property. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).max(property) } /** Returns the sum of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the List. */ public func sum<U: AddableType>(property: String) -> U { return filter(NSPredicate(value: true)).sum(property) } /** Returns the average of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the List, or `nil` if the List is empty. */ public func average<U: AddableType>(property: String) -> U? { return filter(NSPredicate(value: true)).average(property) } // MARK: Mutation /** Appends the given object to the end of the List. If the object is from a different Realm it is copied to the List's Realm. - warning: This method can only be called during a write transaction. - parameter object: An object. */ public func append(object: T) { _rlmArray.addObject(unsafeBitCast(object, RLMObject.self)) } /** Appends the objects in the given sequence to the end of the List. - warning: This method can only be called during a write transaction. - parameter objects: A sequence of objects. */ public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in objects { _rlmArray.addObject(unsafeBitCast(obj, RLMObject.self)) } } /** Inserts the given object at the given index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index)) } /** Removes the object at the given index from the List. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter index: The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the List. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the List. Does not remove the objects from the Realm. - warning: This method can only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter index: The index of the object to be replaced. - parameter object: An object to replace at the specified index. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self)) } /** Moves the object at the given source index to the given destination index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from from: Int, to: Int) { // swiftlint:disable:this variable_name throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the List at given indexes. - warning: Throws an exception when either index exceeds the bounds of the List. - warning: This method can only be called during a write transaction. - parameter index1: The index of the object with which to replace the object at index `index2`. - parameter index2: The index of the object with which to replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } // MARK: Notifications /** Register a block to be called each time the List changes. The block will be asynchronously called with the initial list, and then called again after each write transaction which changes the list or any of the items in the list. You must retain the returned token for as long as you want the results to continue to be sent to the block. To stop receiving updates, call stop() on the token. - parameter block: The block to be called each time the list changes. - returns: A token which must be held for as long as you want notifications to be delivered. */ public func addNotificationBlock(block: (List<T>) -> ()) -> NotificationToken { return _rlmArray.addNotificationBlock { _, _ in block(self) } } } extension List: RealmCollectionType, RangeReplaceableCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the List. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>, with newElements: C) { for _ in subRange { removeAtIndex(subRange.startIndex) } for x in newElements.reverse() { insert(x, atIndex: subRange.startIndex) } } /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } /// :nodoc: public func _addNotificationBlock(block: (AnyRealmCollection<T>?, NSError?) -> ()) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, _ in block(anyCollection, nil) } } }
37.045356
120
0.675315
f5a01b8c88091bd78392a01cf59b2dcedd44ef5c
323
// // ViewController.swift // ${POD_NAME} // // Created by ${USER_NAME} on ${DATE}. // Copyright © ${YEAR} ${USER_NAME}. All rights reserved. // import UIKit import Test1 class ViewController: UIViewController { @IBOutlet var theView: Test1! override func viewDidLoad() { super.viewDidLoad() } }
17
58
0.647059
870145765888706e696b42e9edab11e8d79cfb09
4,268
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** **Concept** A tagged concept extracted from a document. The concept may or may not have been explicitly mentioned. For example if an article mentions CERN and the Higgs boson, it will tag Large Hadron Collider as a concept even if the term is not mentioned explicitly in the page. */ public struct Concept: JSONDecodable { /** detected concept tag*/ public let text: String? /** relevance score for a detected concept tag. Possible values: (0.0 - 1.0) [1.0 = most relevant] */ public let relevance: Double? /** The path through the knowledge graph to the appropriate keyword. Only returned when request parameter is provided: knowledgeGraph=1 */ public let knowledgeGraph: KnowledgeGraph? /** the website associated with this concept tag */ public let website: String? /** latitude longitude - the geographic coordinates associated with this concept tag */ public let geo: String? /** sameAs link to DBpedia for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let dbpedia: String? /** sameAs link to YAGO for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let yago: String? /** sameAs link to OpenCyc for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let opencyc: String? /** sameAs link to Freebase for this concept tag. Note: Provided only for entities that exist in this linked data-set */ public let freebase: String? /** sameAs link to the CIA World Factbook for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let ciaFactbook: String? /** sameAs link to the US Census for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let census: String? /** sameAs link to Geonames for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let geonames: String? /** sameAs link to MusicBrainz for this concept tag Note: Provided only for entities that exist in this linked data-set */ public let musicBrainz: String? /** website link to CrunchBase for this concept tag. Note: Provided only for entities that exist in CrunchBase. */ public let crunchbase: String? /// Used internally to initialize a Concept object public init(json: JSON) throws { text = try? json.getString(at: "text") if let relevanceString = try? json.getString(at: "relevance") { relevance = Double(relevanceString) } else { relevance = nil } knowledgeGraph = try? json.decode(at: "knowledgeGraph", type: KnowledgeGraph.self) website = try? json.getString(at: "website") geo = try? json.getString(at: "geo") dbpedia = try? json.getString(at: "dbpedia") yago = try? json.getString(at: "yago") opencyc = try? json.getString(at: "opencyc") freebase = try? json.getString(at: "freebase") ciaFactbook = try? json.getString(at: "ciaFactbook") census = try? json.getString(at: "census") geonames = try? json.getString(at: "geonames") musicBrainz = try? json.getString(at: "musicBrainz") crunchbase = try? json.getString(at: "crunchbase") } }
31.850746
98
0.656982
8ab4790fba1eedb526708ac1154065da3b3a9922
1,177
// // ArrayAppendingTests.swift // Token // // Created by A.C. Wright Design on 4/19/18. // Copyright © 2018 Aaron Wright. All rights reserved. // import XCTest @testable import Token class ArrayAppendingTests: XCTestCase { func testCanAppendSingleElement() { let array = [1, 2, 3] XCTAssertEqual(array.count, 3) let newArray = array.appending(4) XCTAssertEqual(newArray.count, 4) } func testCanAppendMultipleElements() { let array = [1, 2, 3] XCTAssertEqual(array.count, 3) let newArray = array.appending([4, 5]) XCTAssertEqual(newArray.count, 5) } func testCanAppendSingleElementUsingPlus() { let array = [1, 2, 3] XCTAssertEqual(array.count, 3) let newArray = array + 4 XCTAssertEqual(newArray.count, 4) } func testCanAppendMultipleElementsUsingPlus() { let array = [1, 2, 3] XCTAssertEqual(array.count, 3) let newArray = array + [4, 5] XCTAssertEqual(newArray.count, 5) } }
21.4
55
0.5548
91f83bccfe240122c775ad42f5578647fe40d378
91
import XCTest @testable import XCFitTests XCTMain([ testCase(XCFitTests.allTests), ])
13
34
0.758242
22a6d909db14284c35ffc158f269c063615d00d3
420
// // ILogWriter.swift // LoginPicture // // Created by Michael Wright on 19/03/2017. // Copyright © 2017 [email protected]. All rights reserved. // import Foundation /** Contract for a log writer. Implement for `Logger` class. */ public protocol ILogWriter { /** Writes a message to the log. - parameter message: Message to write to log. */ func log(_ message: String) }
16.153846
58
0.628571
08fd03fb088bee2994025c838c06c86831e9960f
751
import UIKit import Flutter import DP3TSDK @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Initialize DP3T: do { try DP3TTracing.initialize(with: .manual(.init( appId: "dummy", bucketBaseUrl: URL(string: "https://example.com")!, reportBaseUrl: URL(string: "https://example.com")!, jwtPublicKey: nil ))) } catch { // do nothing } // Do the rest.. GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
24.225806
87
0.679095
f5ca6f3f117451f8dac09dce1c42b4099b3f59a0
1,845
// // UIFont.swift // Turbo // // Created by Roossin, Chase on 11/21/17. // Copyright © 2017 Intuit, Inc. All rights reserved. // import UIKit enum FontSize: Int { case ultrabig = 48, header = 36, xx_Large = 28, x_Large = 24, large = 17, medium = 16, normal = 14, small = 12, x_Small = 10 } extension UIFont { class func turboGenericFont(_ fontSize: FontSize) -> UIFont { return UIFont.systemFont(ofSize: CGFloat(fontSize.rawValue), weight: UIFont.Weight.regular) } class func turboGenericFontBlack(_ fontSize: FontSize) -> UIFont { return UIFont.systemFont(ofSize: CGFloat(fontSize.rawValue), weight: UIFont.Weight.black) } class func turboGenericFontBold(_ fontSize: FontSize) -> UIFont { return UIFont.systemFont(ofSize: CGFloat(fontSize.rawValue), weight: UIFont.Weight.bold) } class func turboGenericMediumFont(_ fontSize: FontSize) -> UIFont { return UIFont.systemFont(ofSize: CGFloat(fontSize.rawValue), weight: UIFont.Weight.medium) } class func turboGenericLightFont(_ fontSize: FontSize) -> UIFont { return UIFont.systemFont(ofSize: CGFloat(fontSize.rawValue), weight: UIFont.Weight.light) } class func turboGenericFontWithSize(_ size: CGFloat) -> UIFont { return UIFont.systemFont(ofSize: size, weight: UIFont.Weight.regular) } class func turboGenericMediumFontWithSize(_ size: CGFloat) -> UIFont { return UIFont.systemFont(ofSize: size, weight: UIFont.Weight.medium) } class func turboGenericLightFontWithSize(_ size: CGFloat) -> UIFont { return UIFont.systemFont(ofSize: size, weight: UIFont.Weight.light) } static var titleTextMedium : UIFont {get{return UIFont.systemFont(ofSize: CGFloat(FontSize.x_Large.rawValue), weight: UIFont.Weight.medium)}} }
36.176471
145
0.695935
ed9d74394511c4a45d5ca41356a699e3951cc812
438
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let a{class B:A protocol A{func b<T:T.c
39.818182
79
0.751142
3983dc0545154c67065e6e0892f42a670d580bac
3,856
import Foundation class RESTActionableInsightService: ActionableInsightService { private let client: RESTClient init(client: RESTClient) { self.client = client } @discardableResult public func insights( completion: @escaping (Result<[ActionableInsight], Error>) -> Void ) -> RetryCancellable? { let request = RESTResourceRequest<[RESTActionableInsight]>(path: "/api/v1/insights", method: .get, contentType: .json) { result in completion(result.map { $0.compactMap(ActionableInsight.init) }) } return client.performRequest(request) } /// Lists all archived insights for the user. /// /// - Parameter completion: Completion handler with a result of archived insights if successful or an error if request failed. @discardableResult public func archivedInsights( completion: @escaping (Result<[ActionableInsight], Error>) -> Void ) -> RetryCancellable? { let request = RESTResourceRequest<[RESTArchivedInsight]>(path: "/api/v1/insights/archived", method: .get, contentType: .json) { result in completion(result.map { $0.compactMap(ActionableInsight.init) }) } return client.performRequest(request) } @discardableResult public func select( _ insightAction: ActionableInsight.InsightAction, forInsightWithID insightID: ActionableInsight.ID, completion: @escaping (Result<Void, Error>) -> Void ) -> RetryCancellable? { let body = [ "insightAction": insightAction.data?.type ?? "", "insightId": insightID.value ] let request = RESTSimpleRequest(path: "/api/v1/insights/action", method: .post, body: body, contentType: .json) { result in completion(result.flatMap { response in guard let response = response as? HTTPURLResponse else { return .failure(URLError(.cannotParseResponse)) } guard response.statusCode == 204 else { return .failure(URLError(.cannotParseResponse)) } return .success }) } return client.performRequest(request) } @available(*, deprecated, message: "Use select(_:forInsightWithID:completion:) method instead.") @discardableResult public func selectAction( insightAction: String, insightID: ActionableInsight.ID, completion: @escaping (Result<Void, Error>) -> Void ) -> RetryCancellable? { let body = [ "insightAction": insightAction, "insightId": insightID.value ] let request = RESTSimpleRequest(path: "/api/v1/insights/action", method: .post, body: body, contentType: .json) { result in completion(result.flatMap { response in guard let response = response as? HTTPURLResponse else { return .failure(URLError(.cannotParseResponse)) } guard response.statusCode == 204 else { return .failure(URLError(.cannotParseResponse)) } return .success }) } return client.performRequest(request) } @available(*, deprecated, message: "Use select(_:forInsightWithID:completion:) method instead.") @discardableResult public func archive( id: ActionableInsight.ID, completion: @escaping (Result<Void, Error>) -> Void ) -> RetryCancellable? { let request = RESTSimpleRequest(path: "/api/v1/insights/\(id)/archive", method: .put, contentType: .json, completion: { result in let mapped = result.map { response in () } completion(mapped) }) return client.performRequest(request) } }
36.72381
145
0.61333
c196fe00e65a90d0997d67b9dfe0db8c52ec60af
480
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "HTMLString", products: [ .library(name: "HTMLString", targets: ["HTMLString"]) ], targets: [ .target(name: "HTMLString"), .testTarget( name: "HTMLStringTests", dependencies: ["HTMLString"], exclude: ["HTMLStringObjcTests.m"], resources: [ .process("Fixtures") ] ) ] )
22.857143
61
0.51875
0ea2cd1ad1bcce6d81ba1c4be7a91b437bb53e48
283
// // ViewModelMockType+Void.swift // DcMVVMTest // // Created by Siarhei Bykau on 10.01.20. // import Foundation import DcMVVM public extension ViewModelMockType where ViewModel.Dependencies == Void { typealias VoidDependencies = VoidViewModelDependenciesMock<ViewModel> }
20.214286
73
0.770318
de8a5ea929877c12497f1718cccc9b40bc5b3395
1,232
// // AppDelegate.swift // WDemo // // Created by etiantian on 2020/4/16. // Copyright © 2020 etiantian. All rights reserved. // import Cocoa import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: contentView) window.makeKeyAndOrderFront(nil) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } struct AppDelegate_Previews: PreviewProvider { static var previews: some View { /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/ } }
26.782609
95
0.67289
76d6d54a188b314b5f3a49670f9a92199f2db9b1
332
// // Array+RandomItem.swift // ARKitPlaytime // // Created by Stephanie Guevara on 6/21/17. // Copyright © 2017 Stephanie Guevara. All rights reserved. // import Foundation extension Array { func randomItem() -> Element { let index = Int(arc4random_uniform(UInt32(self.count))) return self[index] } }
19.529412
63
0.665663
ff3724dcb800a382a86597b69227ce0234ecefee
18,821
// // SwipeViewController.swift // SwipeBetweenViewControllers // // Created by Marek Fořt on 11.03.16. // Copyright © 2016 Marek Fořt. All rights reserved. // import UIKit public enum Side { case left, right } open class SwipeViewController: UINavigationController, UIPageViewControllerDelegate, UIScrollViewDelegate { public private(set) var pages: [UIViewController] = [] public var startIndex: Int = 0 { didSet { guard pages.count > startIndex else { return } currentPageIndex = startIndex view.backgroundColor = pages[startIndex].view.backgroundColor } } public var selectionBarHeight: CGFloat = 0 { didSet { selectionBar.frame.size.height = selectionBarHeight } } public var selectionBarWidth: CGFloat = 0 { didSet { selectionBar.frame.size.width = selectionBarWidth } } public var selectionBarColor: UIColor = .black { didSet { selectionBar.backgroundColor = selectionBarColor } } public var buttonFont = UIFont.systemFont(ofSize: 18) { didSet { buttons.forEach { $0.titleLabel?.font = buttonFont } } } public var buttonColor: UIColor = .black { didSet { buttons.enumerated().filter { key, _ in currentPageIndex != key }.forEach { _, element in element.titleLabel?.textColor = buttonColor } } } public var buttonLrPadding: (CGFloat, CGFloat) = (0, 0) { didSet { buttons.forEach { $0.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonLrPadding.0, bottom: 0, right: buttonLrPadding.1) } } } public var selectedButtonColor: UIColor = .green { didSet { guard !buttons.isEmpty else { return } buttons[currentPageIndex].titleLabel?.textColor = selectedButtonColor } } public var navigationBarColor: UIColor = .white { didSet { navigationBar.barTintColor = navigationBarColor } } public var leftBarButtonItem: UIBarButtonItem? { didSet { pageController.navigationItem.leftBarButtonItem = leftBarButtonItem } } public var rightBarButtonItem: UIBarButtonItem? { didSet { pageController.navigationItem.rightBarButtonItem = rightBarButtonItem } } public var bottomOffset: CGFloat = 0 public var equalSpaces: Bool = true public var buttonsWithImages: [SwipeButtonWithImage] = [] public var offset: CGFloat = 40 public let pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) public var currentPageIndex = 0 public private(set) var buttons: [UIButton] = [] private var barButtonItemWidth: CGFloat = 0 private var navigationBarHeight: CGFloat = 0 private weak var selectionBar: UIView! private var totalButtonWidth: CGFloat = 0 private var finalPageIndex = -1 private var indexNotIncremented = true private var pageScrollView = UIScrollView() private var animationFinished = true private var leftSubtract: CGFloat = 0 private var firstWillAppearOccured = false private var spaces: [CGFloat] = [] private var x: CGFloat = 0 private var selectionBarOriginX: CGFloat = 0 private weak var navigationView: UIView! public init(pages: [UIViewController]) { super.init(nibName: nil, bundle: nil) self.pages = pages setViewControllers([pageController], animated: false) pageController.navigationController?.navigationItem.leftBarButtonItem = leftBarButtonItem pageController.delegate = self pageController.dataSource = self if let scrollView = pageController.view.subviews.compactMap({ $0 as? UIScrollView }).first { scrollView.delegate = self } barButtonItemWidth = pageController.navigationController?.navigationBar.topItem?.titleView?.layoutMargins.left ?? 0 navigationBar.isTranslucent = false let navigationView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: navigationBar.frame.height)) navigationView.backgroundColor = navigationBarColor pageController.navigationController?.navigationBar.topItem?.titleView = navigationView self.navigationView = navigationView barButtonItemWidth = navigationBar.topItem?.titleView?.layoutMargins.left ?? 0 addPages() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Method is called when `viewWillAppear(_:)` is called for the first time func viewWillFirstAppear(_: Bool) { updateButtonsAppearance() updateButtonsLayout() updateSelectionBarFrame() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !firstWillAppearOccured { viewWillFirstAppear(animated) firstWillAppearOccured = true } } private func setTitleLabel(_ page: UIViewController, font: UIFont, color: UIColor, button: UIButton) { // Title font and color guard let pageTitle = page.title else { return } let attributes: [NSAttributedString.Key: Any] = [.font: font] let attributedTitle = NSAttributedString(string: pageTitle, attributes: attributes) button.setAttributedTitle(attributedTitle, for: UIControl.State()) guard let titleLabel = button.titleLabel else { return } titleLabel.textColor = color titleLabel.sizeToFit() button.frame.size.width = titleLabel.frame.width + button.titleEdgeInsets.left + button.titleEdgeInsets.right button.frame.size.height = navigationBar.frame.height } private func createSelectionBar() { let selectionBar = UIView() self.selectionBar = selectionBar // SelectionBar updateSelectionBarFrame() selectionBar.backgroundColor = selectionBarColor navigationView.addSubview(selectionBar) } private func updateSelectionBarFrame() { let originY = navigationView.frame.height - selectionBarHeight - bottomOffset selectionBar.frame = CGRect(x: selectionBarOriginX, y: originY, width: selectionBarWidth, height: selectionBarHeight) selectionBar.frame.origin.x -= leftSubtract } private func addPages() { view.backgroundColor = pages[currentPageIndex].view.backgroundColor createButtons() createSelectionBar() // Init of initial view controller guard currentPageIndex >= 0 else { return } let initialViewController = pages[currentPageIndex] pageController.setViewControllers([initialViewController], direction: .forward, animated: true, completion: nil) // Select button of initial view controller - change to selected image buttons[currentPageIndex].isSelected = true } private func createButtons() { buttons = (1 ... pages.count).map { let button = UIButton() button.tag = $0 navigationView.addSubview(button) return button } } private func updateButtonsAppearance() { totalButtonWidth = 0 buttons.enumerated().forEach { tag, button in if buttonsWithImages.isEmpty { setTitleLabel(pages[tag], font: buttonFont, color: buttonColor, button: button) } else { // Getting buttnWithImage struct from array let buttonWithImage = buttonsWithImages[tag] // Normal image button.setImage(buttonWithImage.image, for: UIControl.State()) // Selected image button.setImage(buttonWithImage.selectedImage, for: .selected) // Button tint color button.tintColor = buttonColor // Button size if let size = buttonWithImage.size { button.frame.size = size } } totalButtonWidth += button.frame.width } } private func updateButtonsLayout() { let totalButtonWidth = buttons.reduce(0) { $0 + $1.frame.width } var space: CGFloat = 0 var width: CGFloat = 0 if equalSpaces { // Space between buttons x = (view.frame.width - 2 * offset - totalButtonWidth) / CGFloat(buttons.count + 1) } else { // Space reserved for one button (with label and spaces around it) space = (view.frame.width - 2 * offset) / CGFloat(buttons.count) } for button in buttons { let buttonHeight = button.frame.height let buttonWidth = button.frame.width // let originY = navigationView.frame.height - selectionBarHeight - bottomOffset - buttonHeight - 3 let originY = navigationView.frame.height - bottomOffset - buttonHeight var originX: CGFloat = 0 if equalSpaces { originX = x * CGFloat(button.tag) + width + offset - barButtonItemWidth width += buttonWidth } else { let buttonSpace = space - buttonWidth originX = buttonSpace / 2 + width + offset - barButtonItemWidth width += buttonWidth + space - buttonWidth spaces.append(buttonSpace) } if button.tag == currentPageIndex + 1 { guard let titleLabel = button.titleLabel else { continue } selectionBarOriginX = originX - (selectionBarWidth - buttonWidth) / 2 titleLabel.textColor = selectedButtonColor } button.frame = CGRect(x: originX, y: originY, width: buttonWidth, height: buttonHeight) addFunction(button) } updateLeftSubtract() buttons.forEach { $0.frame.origin.x -= leftSubtract } } private func updateLeftSubtract() { guard let firstButton = buttons.first else { return } let convertedXOrigin = firstButton.convert(firstButton.frame.origin, to: view).x let barButtonWidth: CGFloat = equalSpaces ? 0 : barButtonItemWidth let leftSubtract: CGFloat = (convertedXOrigin - offset + barButtonWidth) / 2 - x / 2 self.leftSubtract = leftSubtract } open func scrollViewDidScroll(_ scrollView: UIScrollView) { let xFromCenter = view.frame.width - scrollView.contentOffset.x var width: CGFloat = 0 let border = view.frame.width - 1 guard currentPageIndex >= 0, currentPageIndex < buttons.endIndex else { return } // Ensuring currentPageIndex is not changed twice if -border ... border ~= xFromCenter { indexNotIncremented = true } // Resetting finalPageIndex for switching tabs if xFromCenter == 0 { finalPageIndex = -1 animationFinished = true } // Going right if xFromCenter <= -view.frame.width, indexNotIncremented, currentPageIndex < buttons.endIndex - 1 { view.backgroundColor = pages[currentPageIndex + 1].view.backgroundColor currentPageIndex += 1 indexNotIncremented = false } // Going left else if xFromCenter >= view.frame.width, indexNotIncremented, currentPageIndex >= 1 { view.backgroundColor = pages[currentPageIndex - 1].view.backgroundColor currentPageIndex -= 1 indexNotIncremented = false } if buttonColor != selectedButtonColor { changeButtonColor(xFromCenter) } for button in buttons { var originX: CGFloat = 0 var space: CGFloat = 0 if equalSpaces { originX = x * CGFloat(button.tag) + width width += button.frame.width } else { space = spaces[button.tag - 1] originX = space / 2 + width width += button.frame.width + space } let selectionBarOriginX = originX - (selectionBarWidth - button.frame.width) / 2 + offset - barButtonItemWidth - leftSubtract // Get button with current index guard button.tag == currentPageIndex + 1 else { continue } var nextButton = UIButton() var nextSpace: CGFloat = 0 if xFromCenter < 0, button.tag < buttons.count { nextButton = buttons[button.tag] if equalSpaces == false { nextSpace = spaces[button.tag] } } else if xFromCenter > 0, button.tag != 1 { nextButton = buttons[button.tag - 2] if equalSpaces == false { nextSpace = spaces[button.tag - 2] } } var newRatio: CGFloat = 0 if equalSpaces { let expression = 2 * x + button.frame.width - (selectionBarWidth - nextButton.frame.width) / 2 newRatio = view.frame.width / (expression - (x - (selectionBarWidth - button.frame.width) / 2)) } else { let expression = button.frame.width + space / 2 + (selectionBarWidth - button.frame.width) / 2 newRatio = view.frame.width / (expression + nextSpace / 2 - (selectionBarWidth - nextButton.frame.width) / 2) } selectionBar.frame = CGRect(x: selectionBarOriginX - (xFromCenter / newRatio), y: selectionBar.frame.origin.y, width: selectionBarWidth, height: selectionBarHeight) return } } // Triggered when selected button in navigation view is changed func scrollToNextViewController(_ index: Int) { let currentViewControllerIndex = currentPageIndex // Comparing index (i.e. tab where user is going to) and when compared, we can now know what direction we should go // Index is on the right if index > currentViewControllerIndex { // loop - if user goes from tab 1 to tab 3 we want to have tab 2 in animation for viewControllerIndex in currentViewControllerIndex ... index { let destinationViewController = pages[viewControllerIndex] pageController.setViewControllers([destinationViewController], direction: .forward, animated: true, completion: nil) } } // Index is on the left else { for viewControllerIndex in (index ... currentViewControllerIndex).reversed() { let destinationViewController = pages[viewControllerIndex] pageController.setViewControllers([destinationViewController], direction: .reverse, animated: true, completion: nil) } } } @objc func switchTabs(_ sender: UIButton) { let index = sender.tag - 1 // Can't animate twice to the same controller (otherwise weird stuff happens) guard index != finalPageIndex, index != currentPageIndex, animationFinished else { return } animationFinished = false finalPageIndex = index scrollToNextViewController(index) } func addFunction(_ button: UIButton) { button.addTarget(self, action: #selector(switchTabs(_:)), for: .touchUpInside) } func changeButtonColor(_ xFromCenter: CGFloat) { // Change color of button before animation finished (i.e. colour changes even when the user is between buttons let viewWidthHalf = view.frame.width / 2 let border = view.frame.width - 1 let halfBorder = view.frame.width / 2 - 1 // Going left, next button selected if viewWidthHalf ... border ~= xFromCenter, currentPageIndex > 0 { let button = buttons[currentPageIndex - 1] let previousButton = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going right, current button selected else if 0 ... halfBorder ~= xFromCenter, currentPageIndex > 1 { let button = buttons[currentPageIndex] let previousButton = buttons[currentPageIndex - 1] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going left, current button selected else if -halfBorder ... 0 ~= xFromCenter, currentPageIndex < buttons.endIndex - 1 { let previousButton = buttons[currentPageIndex + 1] let button = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } // Going right, next button selected else if -border ... -viewWidthHalf ~= xFromCenter, currentPageIndex < buttons.endIndex - 1 { let button = buttons[currentPageIndex + 1] let previousButton = buttons[currentPageIndex] button.titleLabel?.textColor = selectedButtonColor previousButton.titleLabel?.textColor = buttonColor button.isSelected = true previousButton.isSelected = false } } } extension SwipeViewController: UIPageViewControllerDataSource { // Swiping left public func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { // Get current view controller index guard let viewControllerIndex = pages.firstIndex(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 // Making sure the index doesn't get bigger than the array of view controllers guard previousIndex >= 0, pages.count > previousIndex else { return nil } return pages[previousIndex] } // Swiping right public func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { // Get current view controller index guard let viewControllerIndex = pages.firstIndex(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 // Making sure the index doesn't get bigger than the array of view controllers guard pages.count > nextIndex else { return nil } return pages[nextIndex] } }
37.945565
176
0.632219
623b384b32a6b5fa26753f6dfe73dc0c61b58848
1,030
// // CircularView.swift // CircularView // // Created by Suraj Bastola on 7/23/18. // import UIKit public class CircularView: UIView { public var radius: CGFloat = 0.0 public var imageSize: CGSize = CGSize.zero public var startAngle: CGFloat = 0.0 public var images = [UIImage]() fileprivate let π = CGFloat(Double.pi) override public func draw(_ rect: CGRect) { drawImages() } public func refreshCircularView() { setNeedsDisplay() } fileprivate func drawImages() { let angleOfImage = 2 * Double(π)/Double(images.count) var radian: CGFloat = startAngle for image in images { let x = radius * CGFloat(cos(Double(angleOfImage))) + center.x let y = radius * CGFloat(sin(Double(angleOfImage))) + center.y let frame = CGRect(x: x - imageSize.width/CGFloat(2.0), y: y - imageSize.height/CGFloat(2.0), width: imageSize.width, height: imageSize.height) let imageView = UIImageView(image: image) imageView.frame = frame addSubview(imageView) radian += CGFloat(angleOfImage) } } }
25.75
146
0.699029
722bfe2a62c00ab2f270d7d9ede3ac4791a2ce23
1,550
// // ListViewController+Repos.swift // SWHub // // Created by 杨建祥 on 2021/5/30. // import UIKit extension ListViewController { @objc func tapCellWhenReposTrending(_ data: Any!) { guard let sectionItem = data as? SectionItem else { return } self.tapCellWhenRepos(sectionItem) } @objc func tapCellWhenReposStars(_ data: Any!) { guard let sectionItem = data as? SectionItem else { return } self.tapCellWhenRepos(sectionItem) } @objc func tapCellWhenReposSearch(_ data: Any!) { guard let sectionItem = data as? SectionItem else { return } self.tapCellWhenRepos(sectionItem) } @objc func handleUserWhenReposStars(_ data: Any!) { let user = data as? User self.reactor?.username = user?.username MainScheduler.asyncInstance.schedule(()) { [weak self] _ -> Disposable in guard let `self` = self else { return Disposables.create {} } self.reactor?.action.onNext(.load) return Disposables.create {} }.disposed(by: self.disposeBag) } func tapCellWhenRepos(_ sectionItem: SectionItem) { switch sectionItem { case let .repo(item): guard let repo = item.model as? Repo else { return } self.navigator.push( Router.urlString(host: .repo).url! .appendingPathComponent(repo.owner.username) .appendingPathComponent(repo.name) ) default: break } } }
29.807692
81
0.602581
2faf76fa304d43a7849c23904aa3c0804e6d7617
26,604
// BNNetworkManager.swift // Biin // Created by Esteban Padilla on 6/3/14. // Copyright (c) 2014 Biin. All rights reserved. import Foundation import UIKit import SystemConfiguration import CoreLocation class BNNetworkManager:NSObject, BNDataManagerDelegate, BNErrorManagerDelegate, BNPositionManagerDelegate { //URL requests let connectibityUrl = "http://google.com/" var versionUrl = "" var errorManager:BNErrorManager? var delegateDM:BNNetworkManagerDelegate? var delegateVC:BNNetworkManagerDelegate? var requests = Dictionary<Int, BNRequest>() var requestsQueue = Dictionary<Int, BNRequest>() var requestAttempts = 0 var requestAttemptsLimit = 3 var requestTimer:NSTimer? var isRequestTimerAllow = false var epsNetwork:EPSNetworking? var queueCounter = 0 var queueLimit = 10 var totalNumberOfRequest = 0 var requestProcessed = 0 var rootURL = "" var requestManager:BNRequestManager? init(errorManager:BNErrorManager) { //Initialize here any data or variables. super.init() self.errorManager = errorManager epsNetwork = EPSNetworking() requestManager = BNRequestManager(networkManager: self, errorManager: errorManager) } func setRootURLForRequest(){ var value = "" if BNAppSharedManager.instance.settings!.IS_PRODUCTION_DATABASE { value = "prod" } else if BNAppSharedManager.instance.settings!.IS_DEMO_DATABASE { value = "demo" } else if BNAppSharedManager.instance.settings!.IS_QA_DATABASE { value = "qa" } else if BNAppSharedManager.instance.settings!.IS_DEVELOPMENT_DATABASE { value = "dev" } self.versionUrl = "https://www.biin.io/checkversion/\(BNAppSharedManager.instance.version)/ios/\(value)" //print(versionUrl) } //New request manager calls func internet_Failed() { self.errorManager!.showInternetError() } func initialData_Completed() { self.delegateVC!.didReceivedAllInitialData!() } func initialData_Failed(){ } func versionCheck_Completed() { self.delegateVC!.didReceivedVersionStatus!() } func versionCheck_Failed() { self.errorManager!.showVersionError() } func biinie_Completed(biinie:Biinie?) { self.delegateDM!.didReceivedBiinieData!(biinie) } func biinie_Failed() { } func biinie_NotRegistered() { self.delegateDM!.biinieNotRegistered!() self.errorManager!.showNotBiinieError() } func sendBiinieActions_Completed(){ BNAppSharedManager.instance.dataManager.biinie!.actions.removeAll(keepCapacity: false) BNAppSharedManager.instance.dataManager.biinie!.save() } func sendBiinieActions_Failed() { } func sendBiinieToken_Completed() { } func sendBiinieToken_Failed() { BNAppSharedManager.instance.dataManager!.biinie!.token! = "" BNAppSharedManager.instance.dataManager!.biinie!.save() } func sendBiinieOnEnterSite_Completed() { } func sendBiinieOnExitSite_Completed() { } func login_Completed() { self.delegateVC!.didReceivedLoginValidation!(true) } func login_Failed() { self.delegateVC!.didReceivedLoginValidation!(false) } func login_Facebook_Completed() { self.delegateVC!.didReceivedFacebookLoginValidation!(true) } func login_Facebook_Failed() { self.delegateVC!.didReceivedFacebookLoginValidation!(false) } func register_Completed() { self.delegateVC!.didReceivedRegisterConfirmation!(true) } func register_Failed() { self.delegateVC!.didReceivedRegisterConfirmation!(true) } func sendBiinie_Update_Completed() { self.delegateVC!.didReceivedUpdateConfirmation!(true) } func sendBiinie_Failed() { self.delegateVC!.didReceivedUpdateConfirmation!(false) } func sendBiinieOnEnterSite_Failed() { } func sendBiinieOnExitSite_Failed() { } func addToQueue(request:BNRequest){ self.requestManager!.processRequest(request) } func checkVersion() { let request = BNRequest_VersionCheck(requestString:versionUrl, errorManager: self.errorManager!, networkManager: self) addToQueue(request) } func addTo_OLD_QUEUE(request:BNRequest) { self.requests[request.identifier] = request } func sendClaimedGift_Completed(){ } func sendClaimedGift_Failed(){ } func sendRefusedGift_Completed() { } func sendRefusedGift_Failed() { } /** Enable biinie to login. @param email:Biinie email. @param password:Biinie password. */ func login(email:String, password:String){ // // let address = "\(rootURL)/mobile/biinies/auth/\(email)/\(password)" // let escapedAddress = address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) // let urlpath = NSString(format: "\(escapedAddress!)") let url : NSString = "\(rootURL)/mobile/biinies/auth/\(email)/\(password)" // let urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! // let stringURL : NSURL = NSURL(string: "\(urlStr)")! let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! let request = BNRequest_Login(requestString:"\(urlStr)" , errorManager: self.errorManager!, networkManager: self) addToQueue(request) } /** Enable biinie to login. @param email:Biinie email. @param password:Biinie password. */ func login_Facebook(email:String){ let url : NSString = "\(rootURL)/mobile/biinies/auth/thirdparty/facebook/\(email)" let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! let request = BNRequest_Login_Facebook(requestString:"\(urlStr)" , errorManager: self.errorManager!, networkManager: self) addToQueue(request) } /** Enable biinie to register. @param user:Biinie data. */ func register(user:Biinie) { var date:String? if user.birthDate != nil { date = user.birthDate?.bnDateFormattForActions() }else { date = "none" } let url : NSString = "\(rootURL)/mobile/biinies/\(SharedUIManager.instance.fixEmptySpace(user.firstName!))/\(user.lastName!)/\(user.email!)/\(user.password!)/\(user.gender!)/\(date!)" let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! let request = BNRequest_Register(requestString: "\(urlStr)", errorManager: self.errorManager!, networkManager: self) addToQueue(request) } /** Enable biinie to register using Facebook. @param user:Biinie data. */ func register_with_Facebook(user:Biinie) { var date:String? if user.birthDate != nil { date = user.birthDate?.bnDateFormattForActions() }else { date = "none" } if user.password == "" { user.password = "none" } let url : NSString = "\(rootURL)/mobile/biinies/facebook/\(SharedUIManager.instance.fixEmptySpace(user.firstName!))/\(user.lastName!)/\(user.email!)/\(user.password!)/\(user.gender!)/\(date!)/\(user.facebook_id!)" let urlStr = url.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! let request = BNRequest_Register_with_Facebook(requestString: "\(urlStr)", errorManager: self.errorManager!, networkManager: self) addToQueue(request) } /** Request all biinie data @param biinie:Biinie object. */ func requestBiinieData(manager:BNDataManager?, biinie: Biinie?) { let request = BNRequest_Biinie(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)", errorManager: self.errorManager!, networkManager: self, biinie: biinie) addToQueue(request) } /** Send biinie data. @param user:Biinie data. */ func sendBiinie(biinie:Biinie?) { let request = BNRequest_SendBiinie(requestString:"\(rootURL)/mobile/biinies/\(biinie!.identifier!)", errorManager:self.errorManager, networkManager:self, biinie:biinie) addToQueue(request) } func sendBiinieToken(biinie:Biinie?) { //PUT /mobile/biinies/<identifierbiinie>/registerfornotifications let request = BNRequest_SendBiinieToken(requestString:"\(rootURL)/mobile/biinies/\(biinie!.identifier!)/registerfornotifications", errorManager: self.errorManager!, networkManager: self, biinie: biinie) addToQueue(request) } func sendBiinieOnEnterSite(biinie:Biinie?, siteIdentifier:String?, time:NSDate?) { let request = BNRequest_SendBiinieOnEnterSite(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/onentersite/\(siteIdentifier!)", errorManager: self.errorManager, networkManager: self, biinie: biinie, time: time) addToQueue(request) } func sendBiinieOnExitSite(biinie:Biinie?, siteIdentifier:String?, time:NSDate?) { let request = BNRequest_SendBiinieOnExitSite(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/onexitsite/\(siteIdentifier!)", errorManager: self.errorManager, networkManager: self, biinie: biinie, time: time) addToQueue(request) } /** Send biinie actions. @param user:Biinie data. */ func sendBiinieActions(biinie:Biinie?) { if biinie!.actions.count > 0 { let request = BNRequest_SendBiinieActions(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/history", errorManager: self.errorManager, networkManager: self, biinie: biinie) addToQueue(request) } } //LOYALTY func sendLoyaltyCardEnrolled(biinie:Biinie?, loyalty:BNLoyalty?){ //get /mobile/biinies/:identifier/cards/enroll/:cardidentifier let request = BNRequest_SendLoyaltyCardEnrolled(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/cards/enroll/\(loyalty!.loyaltyCard!.identifier!)", errorManager: self.errorManager, networkManager: self, biinie: biinie, loyalty: loyalty) addToQueue(request) } func sendLoyaltyCardAddStar(biinie:Biinie?, loyalty:BNLoyalty?){ //get /mobile/biinies/:identifier/cards/setStar/:cardidentifier let request = BNRequest_SendLoyaltyCardAddStar(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/cards/setStar/\(loyalty!.loyaltyCard!.identifier!)/\(BNAppSharedManager.instance.dataManager.qrCode!)", errorManager: self.errorManager, networkManager: self, biinie: biinie, loyalty: loyalty) addToQueue(request) } func sendLoyaltyCardCompleted(biinie:Biinie?, loyalty:BNLoyalty?){ //get /mobile/biinies/:identifier/cards/setCompleted/:cardidentifier let request = BNRequest_SendLoyaltyCardCompleted(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/cards/setCompleted/\(loyalty!.loyaltyCard!.identifier!)", errorManager: self.errorManager, networkManager: self, biinie: biinie, loyalty: loyalty) addToQueue(request) } func manager(manager: BNDataManager!, initialdata biinie: Biinie?) { if BNAppSharedManager.instance.positionManager.userCoordinates == nil { BNAppSharedManager.instance.positionManager.userCoordinates = CLLocationCoordinate2DMake(9.73854872449546, -83.99879993264159) } let s1 = "\(rootURL)/mobile/initialData/\(biinie!.identifier!)/\(BNAppSharedManager.instance.positionManager.userCoordinates!.latitude)/\(BNAppSharedManager.instance.positionManager.userCoordinates!.longitude)" let request = BNRequest_InitialData(requestString:s1, errorManager: self.errorManager!, networkManager: self) addToQueue(request) } func sendLikedElement(biinie:Biinie?, element:BNElement?) { var like = "unlike" if element!.userLiked { like = "like" } let request = BNRequest_SendLikedElement(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/\(like)", errorManager: self.errorManager, networkManager: self, element: element) addToQueue(request) } func sendSharedElement(biinie: Biinie?, element: BNElement?) { let request = BNRequest_SendSharedElement(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/share", errorManager: self.errorManager!, networkManager: self, element: element) addToQueue(request) } func sendLikedSite(biinie: Biinie?, site: BNSite?) { var like = "unlike" if site!.userLiked { like = "like" } let request = BNRequest_SendLikedSite(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/\(like)", errorManager: self.errorManager!, networkManager: self, site:site) addToQueue(request) } func sendSharedSite(biinie:Biinie?, site:BNSite? ) { let request = BNRequest_SendSharedSite(requestString: "\(rootURL)/mobile/biinies/\(biinie!.identifier!)/share", errorManager: self.errorManager!, networkManager: self, site: site) addToQueue(request) } func requestElementsForShowcase(showcase: BNShowcase?, view: BNView?) { let url = "\(rootURL)/mobile/biinies/\(BNAppSharedManager.instance.dataManager.biinie!.identifier!)/requestElementsForShowcase/\(showcase!.site!.identifier!)/\(showcase!.identifier!)/\(showcase!.batch)" let request = BNRequest_ElementsForShowcase(requestString: url, errorManager: self.errorManager!, networkManager: self, showcase: showcase, biinie:BNAppSharedManager.instance.dataManager.biinie , view: view) addToQueue(request) } func requestElementsForCategory(category:BNCategory?, view:BNView?){ let url = "\(rootURL)/mobile/biinies/\(BNAppSharedManager.instance.dataManager.biinie!.identifier!)/requestElementsForCategory/\(category!.identifier!)/0" let request = BNRequest_ElementsForCategory(requestString: url, errorManager: self.errorManager!, networkManager: self, category:category, view:view) addToQueue(request) } func requestSites(view: BNView?) { let url = "\(rootURL)/mobile/biinies/\(BNAppSharedManager.instance.dataManager.biinie!.identifier!)/requestSites/0" let request = BNRequest_Sites(requestString: url, errorManager: self.errorManager!, networkManager: self, view: view) addToQueue(request) } func sendSurvey(biinie: Biinie?, site: BNSite?, rating:Int, comment:String) { let request = BNRequest_SendSurvey(requestString: "\(rootURL)/mobile/rating/site", errorManager: self.errorManager!, networkManager: self, site: site, rating: rating, comment: comment, biinie: biinie) addToQueue(request) } func removeImageRequest(stringUrl:String){ for (_, request) in self.requests { if stringUrl == request.requestString { self.removeRequestOnCompleted(request.identifier) break } } } func requestImageData(stringUrl:String, image:BNUIImageView!) { if !self.requestManager!.isQueued(stringUrl) { let request = BNRequest_Image(requestString: stringUrl, errorManager: self.errorManager!, networkManager: self, image:image) addToQueue(request) } else { epsNetwork!.getImageInCache(stringUrl, image: image) } } func sendClaimedGift(gift:BNGift?) { let request = BNRequest_SendClaimedGift(requestString: "\(rootURL)/mobile/biinies/\(BNAppSharedManager.instance.dataManager.biinie!.identifier!)/gifts/claim", errorManager: self.errorManager!, networkManager: self, gift: gift) addToQueue(request) } func sendRefusedGift(gift:BNGift?){ // var refusedGift:BNGift? // refusedGift = BNGift() // refusedGift!.identifier = gift!.identifier // let request = BNRequest_SendRefusedGift(requestString: "\(rootURL)/mobile/biinies/\(BNAppSharedManager.instance.dataManager.biinie!.identifier!)/gifts/refuse", errorManager: self.errorManager!, networkManager: self, gift: gift) addToQueue(request) } func resume(){ self.errorManager!.isAlertOn = false self.requestManager!.resume() } //Request to remove a showcase when it data is corrupt or is not longer in server. func removeShowcase( identifier:String ) { } //BNErrorManagerDelegate func manager(manager:BNErrorManager!, saveError error:BNError) { //var url = "http://biin.herokuapp.com/api/errors/add/" //var parameters = ["code": error.code, "title":error.title, "description":error.errorDescription, "proximityUUID":error.proximityUUID, "region":error.region] } func removeRequestOnCompleted(identifier:Int){ requests.removeValueForKey(identifier) requestAttempts = 0 if requests.count == 0 { } else { if requests.count == 1 { } } } } @objc protocol BNNetworkManagerDelegate:NSObjectProtocol { optional func didReceivedVersionStatus() optional func didReceivedAllInitialData() optional func didReceivedBiinieData(user:Biinie?) optional func biinieNotRegistered() optional func didReceivedLoginValidation(isValidated:Bool) optional func didReceivedFacebookLoginValidation(isValidated:Bool) optional func didReceivedRegisterConfirmation(isRegistered:Bool) optional func didReceivedUpdateConfirmation(updated:Bool) optional func manager(manager:BNNetworkManager!, didReceivedUserIdentifier idetifier:String?) optional func manager(manager:BNNetworkManager!, didReceivedEmailVerification value:Bool) optional func manager(manager:BNNetworkManager!, didReceivedCategoriesSavedConfirmation response:BNResponse?) optional func manager(manager:BNNetworkManager!, didReceivedInitialData biins:Array<BNBiin>?) optional func manager(manager:BNNetworkManager!, didReceivedRegions regions:Array<BNRegion>) ///Takes connection status and start initial requests /// ///- parameter BNNetworkManager.: ///- parameter Status: of the network check. optional func manager(manager:BNNetworkManager!, didReceivedConnectionStatus status:Bool) // optional func manager(manager:BNNetworkManager!, didReceivedVersionStatus) ///Takes categories data requested and procces that data. /// ///- parameter BNNetworkManager.: ///- parameter An: array of categories. optional func manager(manager:BNNetworkManager!, didReceivedUserCategories categories:Array<BNCategory>) optional func manager(manager:BNNetworkManager!, didReceivedUserCategoriesOnBackground categories:Array<BNCategory>) // optional func receivedSite(site:BNSite) // optional func receivedOrganization(organization:BNOrganization) // optional func receivedShowcase(showcase:BNShowcase) // optional func receivedElement(element:BNElement) // optional func receivedHightlight(element:BNElement) ///Takes site data requested and proccess that data. /// ///- parameter BNNetworkManager.: ///- parameter BNSite: requested. optional func manager(manager:BNNetworkManager!, didReceivedSite site:BNSite) ///Takes showcase data requested and proccess that data. /// ///- parameter BNNetworkManager.: ///- parameter BNShowcase: requested. optional func manager(manager:BNNetworkManager!, didReceivedShowcase showcase:BNShowcase) ///Takes element data requested and proccess that data. /// ///- parameter BNNetworkManager.: ///- parameter BNElement: requested. optional func manager(manager:BNNetworkManager!, didReceivedElement element:BNElement) optional func manager(manager:BNNetworkManager!, didReceivedHihglightList showcase:BNShowcase) ///Takes element data requested and proccess that data. /// ///- parameter BNNetworkManager.: ///- parameter BNElement: requested. //optional func manager(manager:BNNetworkManager!, didReceivedHightlight element:BNElement) ///Takes user biined element list and process data and request to download elements. /// ///- parameter BNNetworkManager.: ///- parameter BNElement: list biined by user. optional func manager(manager:BNNetworkManager!, didReceivedBiinedElementList elementList:Array<BNElement>) ///Takes user boards and process data and request to download elements. /// ///- parameter BNNetworkManager.: ///- parameter User: boards. optional func manager(manager:BNNetworkManager!, didReceivedCollections collectionList:Array<BNCollection>) optional func manager(manager:BNNetworkManager!, updateProgressView value:Float) ///Takes a notification string data requested for a element and proccess that data. /// ///- parameter BNNetworkManager.: ///- parameter String: notification requested. ///- parameter BNEelement: requesting the data. optional func manager(manager:BNNetworkManager!, didReceivedElementNotification notification:String, element:BNElement) optional func manager(manager:BNNetworkManager!, didReveivedBiinsOnRegion biins:Array<BNBiin>, identifier:String) optional func manager(manager:BNNetworkManager!, removeShowcaseRelationShips identifier:String) optional func manager(manager:BNNetworkManager!, didReveivedSharedBiins biins:Array<BNBiin>, identifier:String ) optional func refreshTable(manager:BNNetworkManager!) } extension NSDate { convenience init(dateString:String) { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let d = formatter.dateFromString(dateString) self.init(timeInterval:0, sinceDate:d!) } convenience init(dateStringMMddyyyy:String) { let formatter = NSDateFormatter() formatter.dateFormat = "MM/dd/yyyy" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let d = formatter.dateFromString(dateStringMMddyyyy) self.init(timeInterval:0, sinceDate:d!) } convenience init(dateString_yyyyMMddZ:String) { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let d = formatter.dateFromString(dateString_yyyyMMddZ) if dateString_yyyyMMddZ != "" { self.init(timeInterval:0, sinceDate:d!) } else { self.init() } } func bnDateFormatt()->String{ let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter.stringFromDate(self) } func bnDateFormattForActions() -> String { let formatter = NSDateFormatter() formatter.timeZone = NSTimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter.stringFromDate(self) } func bnDateFormattForNotification() -> String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss ZZZ" return formatter.stringFromDate(self) } func bnDisplayDateFormatt()->String{ let formatter = NSDateFormatter() formatter.dateFormat = "dd MMM yyyy" return formatter.stringFromDate(self) } func bnDisplayDateFormatt_by_Day()->String { let formatter = NSDateFormatter() formatter.dateFormat = "EEEE, MMM d" return formatter.stringFromDate(self) } func bnShortDateFormat()->String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.stringFromDate(self) } func isBefore(date:NSDate) -> Bool { if self.compare(date) == NSComparisonResult.OrderedAscending { return true } else { return false } } func alredyPassedADay() { } func daysBetweenFromAndTo(toDate:NSDate) -> Int { let cal = NSCalendar.currentCalendar() let unit:NSCalendarUnit = .Day let components = cal.components(unit, fromDate:toDate, toDate:NSDate(), options: []) return (components.day + 1) } } extension String { var lastPathComponent: String { get { return (self as NSString).lastPathComponent } } var pathExtension: String { get { return (self as NSString).pathExtension } } var stringByDeletingLastPathComponent: String { get { return (self as NSString).stringByDeletingLastPathComponent } } var stringByDeletingPathExtension: String { get { return (self as NSString).stringByDeletingPathExtension } } var pathComponents: [String] { get { return (self as NSString).pathComponents } } func stringByAppendingPathComponent(path: String) -> String { let nsSt = self as NSString return nsSt.stringByAppendingPathComponent(path) } func stringByAppendingPathExtension(ext: String) -> String? { let nsSt = self as NSString return nsSt.stringByAppendingPathExtension(ext) } }
36.745856
312
0.67129
87824f2968090bd0da96a2ee7c3151bdebeda375
210
// // LogOutUseCases.swift // Outcubator // // Created by doquanghuy on 16/05/2021. // import Foundation import RxSwift protocol LogoutUseCases { func execute(query: LogoutQuery) -> Observable<Void> }
15
56
0.714286
9150eab0f6234f5d4878bd4577356036612afc65
19,942
// // MessageImplTests.swift // WebimClientLibrary_Tests // // Created by Nikita Lazarev-Zubov on 20.02.18. // Copyright © 2018 Webim. 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 @testable import WebimClientLibrary import XCTest class MessageImplTests: XCTestCase { // MARK: - Tests func testToString() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let expectedString = """ MessageImpl { serverURLString = http://demo.webim.ru, ID = id, operatorID = nil, senderAvatarURLString = nil, senderName = Name, type = VISITOR, text = Text, timeInMicrosecond = 0, attachment = nil, historyMessage = false, currentChatID = nil, historyID = nil, rawText = nil, read = false } """ XCTAssertEqual(message.toString(), expectedString) } func testGetSenderAvatarURL() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertNil(message.getSenderAvatarFullURL()) } func testGetSendStatus() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertEqual(message.getSendStatus(), MessageSendStatus.sent) } func testIsEqual() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let message1 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id1", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let message2 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name1", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let message3 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text1", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let message4 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .operatorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) let message5 = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertFalse(message.isEqual(to: message1)) XCTAssertFalse(message.isEqual(to: message2)) XCTAssertFalse(message.isEqual(to: message3)) XCTAssertFalse(message.isEqual(to: message4)) XCTAssertTrue(message.isEqual(to: message5)) } // MARK: MessageSource tests func testAssertIsCurrentChat() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertNoThrow(try message.getSource().assertIsCurrentChat()) } func testAssertIsHistory() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertThrowsError(try message.getSource().assertIsHistory()) } func testGetHistoryID() { let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertNil(message.getHistoryID()) } func testGetCurrentChatID() { let currentChatID = "id" let message = MessageImpl(serverURLString: "http://demo.webim.ru", id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: nil, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: currentChatID, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertEqual(currentChatID, message.getCurrentChatID()) } func testGetSenderAvatarFullURL() { let baseURLString = "http://demo.webim.ru" let avatarURLString = "/image.jpg" let message = MessageImpl(serverURLString: baseURLString, id: "id", keyboard: nil, keyboardRequest: nil, operatorID: nil, quote: nil, senderAvatarURLString: avatarURLString, senderName: "Name", sendStatus: .sent, type: .visitorMessage, data: nil, text: "Text", timeInMicrosecond: 0, attachment: nil, historyMessage: false, internalID: nil, rawText: nil, read: false, messageCanBeEdited: false, messageCanBeReplied: false) XCTAssertEqual(URL(string: (baseURLString + avatarURLString)), message.getSenderAvatarFullURL()) } } // MARK: - class MessageAttachmentTests: XCTestCase { // MARK: - Tests func testInit() { let messageAttachment = MessageAttachmentImpl(urlString: "/image.jpg", size: 1, filename: "image", contentType: "image/jpeg", imageInfo: nil) XCTAssertEqual(messageAttachment.getContentType(), "image/jpeg") XCTAssertEqual(messageAttachment.getFileName(), "image") XCTAssertNil(messageAttachment.getImageInfo()) XCTAssertEqual(messageAttachment.getSize(), 1) XCTAssertEqual(messageAttachment.getURL(), URL(string: "/image.jpg")!) } } // MARK: - class ImageInfoImplTests: XCTestCase { // MARK: - Tests func testInit() { let imageInfo = ImageInfoImpl(withThumbURLString: "https://demo.webim.ru/thumb.jpg", width: 100, height: 200) XCTAssertEqual(imageInfo.getThumbURL(), URL(string: "https://demo.webim.ru/thumb.jpg")) XCTAssertEqual(imageInfo.getWidth(), 100) XCTAssertEqual(imageInfo.getHeight(), 200) } }
45.738532
92
0.368268
729f6824cf8eb73ffd0a59a0ba936efeafa68d61
6,642
// // Copyright © 2021 Stephen F. Booth <[email protected]> // Part of https://github.com/sbooth/Pipeline // MIT license // import Foundation extension Database { /// A hook called when a database transaction is committed. /// /// - returns: `true` if the commit operation is allowed to proceed, `false` otherwise. /// /// - seealso: [Commit And Rollback Notification Callbacks](https://www.sqlite.org/c3ref/commit_hook.html) public typealias CommitHook = () -> Bool /// Sets the hook called when a database transaction is committed. /// /// - parameter commitHook: A closure called when a transaction is committed. public func setCommitHook(_ block: @escaping CommitHook) { let context = UnsafeMutablePointer<CommitHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_commit_hook(databaseConnection, { $0.unsafelyUnwrapped.assumingMemoryBound(to: CommitHook.self).pointee() ? 0 : 1 }, context) { let oldContext = old.assumingMemoryBound(to: CommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the commit hook. public func removeCommitHook() { if let old = sqlite3_commit_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: CommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// A hook called when a database transaction is rolled back. /// /// - seealso: [Commit And Rollback Notification Callbacks](https://www.sqlite.org/c3ref/commit_hook.html) public typealias RollbackHook = () -> Void /// Sets the hook called when a database transaction is rolled back. /// /// - parameter rollbackHook: A closure called when a transaction is rolled back. public func setRollbackHook(_ block: @escaping RollbackHook) { let context = UnsafeMutablePointer<RollbackHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_rollback_hook(databaseConnection, { $0.unsafelyUnwrapped.assumingMemoryBound(to: RollbackHook.self).pointee() }, context) { let oldContext = old.assumingMemoryBound(to: RollbackHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the rollback hook. public func removeRollbackHook() { if let old = sqlite3_rollback_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: RollbackHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } } extension Database { /// A hook called when a database transaction is committed in write-ahead log mode. /// /// - parameter databaseName: The name of the database that was written to. /// - parameter pageCount: The number of pages in the write-ahead log file. /// /// - returns: Normally `SQLITE_OK`. /// /// - seealso: [Write-Ahead Log Commit Hook](https://www.sqlite.org/c3ref/wal_hook.html) public typealias WALCommitHook = (_ databaseName: String, _ pageCount: Int) -> Int32 /// Sets the hook called when a database transaction is committed in write-ahead log mode. /// /// - parameter commitHook: A closure called when a transaction is committed. public func setWALCommitHook(_ block: @escaping WALCommitHook) { let context = UnsafeMutablePointer<WALCommitHook>.allocate(capacity: 1) context.initialize(to: block) if let old = sqlite3_wal_hook(databaseConnection, { context, database_connection, database_name, pageCount in // guard database_connection == self.databaseConnection else { // fatalError("Unexpected database connection handle from sqlite3_wal_hook") // } let database = String(utf8String: database_name.unsafelyUnwrapped).unsafelyUnwrapped return context.unsafelyUnwrapped.assumingMemoryBound(to: WALCommitHook.self).pointee(database, Int(pageCount)) }, context) { let oldContext = old.assumingMemoryBound(to: WALCommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } /// Removes the write-ahead log commit hook. public func removeWALCommitHook() { if let old = sqlite3_wal_hook(databaseConnection, nil, nil) { let oldContext = old.assumingMemoryBound(to: WALCommitHook.self) oldContext.deinitialize(count: 1) oldContext.deallocate() } } } extension Database { /// A hook that may be called when an attempt is made to access a locked database table. /// /// - parameter attempts: The number of times the busy handler has been called for the same event. /// /// - returns: `true` if the attempts to access the database should stop, `false` to continue. /// /// - seealso: [Register A Callback To Handle SQLITE_BUSY Errors](https://www.sqlite.org/c3ref/busy_handler.html) public typealias BusyHandler = (_ attempts: Int) -> Bool /// Sets a callback that may be invoked when an attempt is made to access a locked database table. /// /// - parameter busyHandler: A closure called when an attempt is made to access a locked database table. /// /// - throws: An error if the busy handler couldn't be set. public func setBusyHandler(_ block: @escaping BusyHandler) throws { if busyHandler == nil { busyHandler = UnsafeMutablePointer<BusyHandler>.allocate(capacity: 1) } else { busyHandler?.deinitialize(count: 1) } busyHandler?.initialize(to: block) guard sqlite3_busy_handler(databaseConnection, { context, count in return context.unsafelyUnwrapped.assumingMemoryBound(to: BusyHandler.self).pointee(Int(count)) ? 0 : 1 }, busyHandler) == SQLITE_OK else { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil throw Database.Error(message: "Error setting busy handler") } } /// Removes the busy handler. /// /// - throws: An error if the busy handler couldn't be removed. public func removeBusyHandler() throws { defer { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil } guard sqlite3_busy_handler(databaseConnection, nil, nil) == SQLITE_OK else { throw SQLiteError(fromDatabaseConnection: databaseConnection) } } /// Sets a busy handler that sleeps when an attempt is made to access a locked database table. /// /// - parameter ms: The minimum time in milliseconds to sleep. /// /// - throws: An error if the busy timeout couldn't be set. /// /// - seealso: [Set A Busy Timeout](https://www.sqlite.org/c3ref/busy_timeout.html) public func setBusyTimeout(_ ms: Int) throws { defer { busyHandler?.deinitialize(count: 1) busyHandler?.deallocate() busyHandler = nil } guard sqlite3_busy_timeout(databaseConnection, Int32(ms)) == SQLITE_OK else { throw Database.Error(message: "Error setting busy timeout") } } }
37.738636
114
0.733062
23d91076cbc9b4b170f6d1ac11c8c92ec102958b
1,314
// // STPaths.swift // swagger-transform // // Created by Eric Hyche on 10/22/17. // Copyright © 2017 HeirPlay Software. All rights reserved. // import Foundation class STPaths: STVendorExtensible { var paths: [String: STPathItem]? // Decodable protocol methods required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: STNonExtensionKey.self) let pathKeys = container.allKeys if !pathKeys.isEmpty { var tmpPaths = [String:STPathItem]() for pathKey in pathKeys { let path = try container.decode(STPathItem.self, forKey: pathKey) tmpPaths[pathKey.stringValue] = path } paths = tmpPaths } try super.init(from: decoder) } // Encodable protocol methods override func encode(to encoder: Encoder) throws { if let paths = paths, !paths.isEmpty { var container = encoder.container(keyedBy: STNonExtensionKey.self) for (pathKey, pathItem) in paths { if let nonExtensionKey = STNonExtensionKey(stringValue: pathKey) { try container.encode(pathItem, forKey: nonExtensionKey) } } } try super.encode(to: encoder) } }
26.816327
82
0.605023
50c6415d732a7771ff28cd4d8e460fd37071de90
865
import ArgumentParser import Foundation import TSCBasic /// A command to lint the Swift code using Swiftlint struct LintCodeCommand: ParsableCommand { static var configuration: CommandConfiguration { CommandConfiguration(commandName: "code", _superCommandName: "lint", abstract: "Lints the code of your projects using Swiftlint.") } @Option( name: .shortAndLong, help: "The path to the directory that contains the workspace or project whose code will be linted.", completion: .directory ) var path: String? @Argument( help: "The target to be linted. When not specified all the targets of the graph are linted." ) var target: String? func run() throws { try LintCodeService().run(path: path, targetName: target) } }
29.827586
108
0.643931
33acae80d2d5e31af19b556724b0b2e32f98efaf
2,210
// // ImageMetadataView.swift // LiveSurface // // Created by Rob Booth on 9/28/19. // Copyright © 2019 Rob Booth. All rights reserved. // import SwiftUI struct ImageMetadataView: View { var image: LSImage var body: some View { HStack(alignment: .top, spacing: 10) { VStack(alignment: .leading) { KeyValueView(key: "Name:", value: image.name) KeyValueView(key: "Number:", value: image.number) KeyValueView(key: "Image:", value: image.image) KeyValueView(key: "Category:", value: image.category) KeyValueView(key: "Version:", value: image.version) } VStack(alignment: .leading) { Text("Tags:") .underline(true, color: .black) KeyValueView(key: "Description:", value: image.tags.sizedescription) KeyValueView(key: "Scale:", value: image.tags.sizescale) KeyValueView(key: "Width:", value: image.tags.sizewidth) KeyValueView(key: "Widtharc:", value: image.tags.sizewidtharc) KeyValueView(key: "Height:", value: image.tags.sizeheight) KeyValueView(key: "Heightarc:", value: image.tags.sizeheightarc) KeyValueView(key: "Depth:", value: image.tags.sizedepth) KeyValueView(key: "Deptharc:", value: image.tags.sizedeptharc) KeyValueView(key: "Units:", value: image.tags.sizeunits) } } .padding() .border(Color.black, width: 1) } } struct KeyValueView: View { var key: String var value: String var body: some View { HStack { Text(key) Text(value) } } } struct ImageMetadataView_Previews: PreviewProvider { static var previews: some View { ImageMetadataView(image: LSImage(index: 0, name: "one", number: "one", image: "one.jpg", category: "category", version: "version", tags: Tags(sizedescription: "A7", sizescale: "0.000", sizewidth: "7.25", sizewidtharc: "0", sizeheight: "5.250", sizeheightarc: "0", sizedepth: "0.000", sizedeptharc: "0", sizeunits: "in"))) } }
36.833333
329
0.578733
ed486d99d3dc19c071cc919c41d2556429e42000
456
import Domain import Vapor import Fluent import FluentMySQL extension LanguageTag: MySQLType { public static var mysqlDataType: MySQLDataType { return .varchar(64) } public func convertToMySQLData() -> MySQLData { return String(self).convertToMySQLData() } public static func convertFromMySQLData(_ data: MySQLData) throws -> LanguageTag { return try self.init(string: .convertFromMySQLData(data)) } }
20.727273
86
0.70614
76de8a696acedaedfd0ce4fbea0d5d8d0bf6a340
176
// // BitSet.swift // CodingChallenges // // Created by Maxim Eremenko on 9/8/18. // Copyright © 2018 Eremenko Maxim. All rights reserved. // /// TODO: Implement a BitSet
17.6
57
0.670455
edd25f6ba600a2579ec6cae3253cd567e590bbb3
2,196
// RUN: %target-swift-frontend -enable-experimental-cxx-interop -I %S/Inputs %s -emit-ir | %FileCheck %s // This tests output needs to be updated for arm64. // XFAIL: CPU=arm64e import CustomDestructor protocol InitWithDummy { init(dummy: DummyStruct) } extension HasUserProvidedDestructorAndDummy : InitWithDummy { } // Make sure the destructor is added as a witness. // CHECK: @"$sSo33HasUserProvidedDestructorAndDummyVWV" = linkonce_odr hidden constant %swift.vwtable // CHECK-SAME: i8* bitcast (void (%swift.opaque*, %swift.type*)* @"$sSo33HasUserProvidedDestructorAndDummyVwxx" to i8*) // CHECK-LABEL: define {{.*}}void @"$s4main37testHasUserProvidedDestructorAndDummyyyF" // CHECK: [[OBJ:%.*]] = alloca %TSo33HasUserProvidedDestructorAndDummyV // CHECK: [[CXX_OBJ:%.*]] = bitcast %TSo33HasUserProvidedDestructorAndDummyV* [[OBJ]] to %struct.HasUserProvidedDestructorAndDummy* // CHECK: call {{.*}}@{{_ZN33HasUserProvidedDestructorAndDummyD(1|2)Ev|"\?\?1HasUserProvidedDestructorAndDummy@@QEAA@XZ"}}(%struct.HasUserProvidedDestructorAndDummy* [[CXX_OBJ]]) // CHECK: ret void // Make sure we not only declare but define the destructor. // CHECK-LABEL: define {{.*}}@{{_ZN33HasUserProvidedDestructorAndDummyD(1|2)Ev|"\?\?1HasUserProvidedDestructorAndDummy@@QEAA@XZ"}} // CHECK: ret public func testHasUserProvidedDestructorAndDummy() { _ = HasUserProvidedDestructorAndDummy(dummy: DummyStruct()) } // CHECK-LABEL: define {{.*}}void @"$s4main26testHasDefaultedDestructoryyF" // CHECK: call {{.*}}@{{_ZN22HasDefaultedDestructorC(1|2)Ev|"\?\?0HasDefaultedDestructor@@QEAA@XZ"}}(%struct.HasDefaultedDestructor* // CHECK: ret void // CHECK-LABEL: define {{.*}}@{{_ZN22HasDefaultedDestructorC(1|2)Ev|"\?\?0HasDefaultedDestructor@@QEAA@XZ"}}(%struct.HasDefaultedDestructor* // CHECK: ret public func testHasDefaultedDestructor() { _ = HasDefaultedDestructor() } // Make sure the destroy value witness calls the destructor. // CHECK-LABEL: define {{.*}}void @"$sSo33HasUserProvidedDestructorAndDummyVwxx" // CHECK: call {{.*}}@{{_ZN33HasUserProvidedDestructorAndDummyD(1|2)Ev|"\?\?1HasUserProvidedDestructorAndDummy@@QEAA@XZ"}}(%struct.HasUserProvidedDestructorAndDummy* // CHECK: ret
48.8
178
0.759107
463fe91b2ee2041eee092f9c04d4d92b4314a035
2,424
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension TFL.BikePoint { /** Gets all bike point locations. The Place object has an addtionalProperties array which contains the nbBikes, nbDocks and nbSpaces numbers which give the status of the BikePoint. A mismatch in these numbers i.e. nbDocks - (nbBikes + nbSpaces) != 0 indicates broken docks. */ public enum BikePointGetAll { public static let service = APIService<Response>(id: "BikePoint_GetAll", tag: "BikePoint", method: "GET", path: "/BikePoint", hasBody: false) public final class Request: APIRequest<Response> { public init() { super.init(service: BikePointGetAll.service) } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = [Place] /** OK */ case status200([Place]) public var success: [Place]? { switch self { case .status200(let response): return response } } public var response: Any { switch self { case .status200(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 } } public var successful: Bool { switch self { case .status200: return true } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode([Place].self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
32.32
155
0.534241
9b243de54dbc908ea8956457733976c542ac24f1
723
import Foundation import OneginiSDKiOS import OneginiCrypto import Flutter protocol OneginiPluginBaseProtocol { func startApp(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) -> Void } extension SwiftOneginiPlugin: OneginiPluginBaseProtocol { func startApp(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) { guard let _arg = call.arguments as! [String: Any]?, let _connectionTimeout = _arg["connectionTimeout"] as? Int else { return; } let timeInterval = TimeInterval(_connectionTimeout); ONGClientBuilder().setHttpRequestTimeout(timeInterval) OneginiModuleSwift.sharedInstance.startOneginiModule(callback: result) } }
32.863636
87
0.73444
5b6c6b9243fc6bf0922eaadf1c99dd49dffdd9d1
3,186
// @copyright Trollwerks Inc. import Anchorage /// Notify of display state changes protocol CountSectionHeaderDelegate: AnyObject { /// Toggle expanded state of section /// - Parameter section: Name func toggle(section: String) } /// Display model for count section struct CountSectionModel { /// Region or brand var section: String /// Number visited var visited: Int? /// Number total var count: Int /// Whether is expanded var isExpanded: Bool } /// Counts section header final class CountSectionHeader: UICollectionReusableView { /// Dequeueing identifier static let reuseIdentifier = NSStringFromClass(CountSectionHeader.self) /// Delegate weak var delegate: CountSectionHeaderDelegate? private var model: CountSectionModel? /// Handle dependency injection /// - Parameter model: Data model func inject(model: CountSectionModel) { self.model = model let disclose: Disclosure = model.isExpanded ? .close : .expand disclosure.image = disclose.image if let visited = model.visited { label.text = L.locationVisitedCount(model.section, visited, model.count) } else { label.text = L.locationCount(model.section, model.count) } let rounded: ViewCorners = model.isExpanded ? .top(radius: Layout.cornerRadius) : .all(radius: Layout.cornerRadius) round(corners: rounded) } private enum Layout { static let cornerRadius = CGFloat(4) static let insets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) static let font = Avenir.heavy.of(size: 18) } private let disclosure = UIImageView { $0.setContentHuggingPriority(.required, for: .horizontal) } private let label = UILabel { $0.font = Layout.font } /// Procedural intializer /// - Parameter frame: Display frame override init(frame: CGRect) { super.init(frame: frame) configure() } /// :nodoc: required init?(coder: NSCoder) { nil } /// Empty display override func prepareForReuse() { super.prepareForReuse() delegate = nil model = nil disclosure.image = nil label.text = nil layer.mask = nil } } // MARK: - Private private extension CountSectionHeader { func configure() { backgroundColor = .white let stack = UIStackView(arrangedSubviews: [ disclosure, label, ]).with { $0.alignment = .center $0.spacing = 5 } addSubview(stack) stack.edgeAnchors == edgeAnchors + Layout.insets let tap = UITapGestureRecognizer(target: self, action: #selector(tapped)) addGestureRecognizer(tap) } @objc func tapped(_ sender: UIGestureRecognizer) { if let section = model?.section { delegate?.toggle(section: section) } } }
25.693548
87
0.58349
e6c5fda1c03d2dcc5e055527e91a0583e1c78195
2,890
// // LogListView.swift // ExpenseTracker // // Created by Alfian Losari on 19/04/20. // Copyright © 2020 Alfian Losari. All rights reserved. // import SwiftUI import CoreData struct LogListView: View { @State var logToEdit: ExpenseLog? @Environment(\.managedObjectContext) var context: NSManagedObjectContext @FetchRequest( entity: ExpenseLog.entity(), sortDescriptors: [ NSSortDescriptor(keyPath: \ExpenseLog.date, ascending: false) ] ) private var result: FetchedResults<ExpenseLog> init(predicate: NSPredicate?, sortDescriptor: NSSortDescriptor) { let fetchRequest = NSFetchRequest<ExpenseLog>(entityName: ExpenseLog.entity().name ?? "ExpenseLog") fetchRequest.sortDescriptors = [sortDescriptor] if let predicate = predicate { fetchRequest.predicate = predicate } _result = FetchRequest(fetchRequest: fetchRequest) } var body: some View { List { ForEach(result) { (log: ExpenseLog) in Button(action: { self.logToEdit = log }) { HStack(spacing: 16) { CategoryImageView(category: log.categoryEnum) VStack(alignment: .leading, spacing: 8) { Text(log.nameText).font(.headline) Text(log.dateText).font(.subheadline) } Spacer() Text(log.amountText).font(.headline) } .padding(.vertical, 4) } } .onDelete(perform: onDelete) .sheet(item: $logToEdit, onDismiss: { self.logToEdit = nil }) { (log: ExpenseLog) in LogFormView( logToEdit: log, context: self.context, name: log.name ?? "", amount: log.amount?.doubleValue ?? 0, category: Category(rawValue: log.category ?? "") ?? .food, date: log.date ?? Date() ) } } } private func onDelete(with indexSet: IndexSet) { indexSet.forEach { index in let log = result[index] context.delete(log) } try? context.saveContext() } } struct LogListView_Previews: PreviewProvider { static var previews: some View { let stack = CoreDataStack(containerName: "ExpenseTracker") let sortDescriptor = ExpenseLogSort(sortType: .date, sortOrder: .descending).sortDescriptor return LogListView(predicate: nil, sortDescriptor: sortDescriptor) .environment(\.managedObjectContext, stack.viewContext) } }
31.758242
107
0.532872
385419bb45253adec55d8ec99f33ecada432f3a7
897
import UIKit import Core import Store import WelcomeFeature @UIApplicationMain final class AppDelegate: NSObject, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() let vc = UIViewController() vc.view.backgroundColor = .red let mealStore = MealStore(storage: .inMemory, calendar: .autoupdatingCurrent, sendNotification: { _, _ in }) mealStore.add(Meal(name: "Pizza", date: Date(), type: .dinner)) window?.rootViewController = vc WelcomeFeature.start(root: vc, dependencies: CurrentEnvironment.welcomeFeature) return true } }
30.931034
152
0.661093
d6b59a37633f6b81968506c609bb80fe9986a438
6,826
// // CRRefreshComponent.swift // CRRefresh // // ************************************************** // * _____ * // * __ _ __ ___ \ / * // * \ \/ \/ / / __\ / / * // * \ _ / | (__ / / * // * \/ \/ \___/ / /__ * // * /_____/ * // * * // ************************************************** // Github :https://github.com/imwcl // HomePage:http://imwcl.com // CSDN :http://blog.csdn.net/wang631106979 // // Created by 王崇磊 on 16/9/14. // Copyright © 2016年 王崇磊. All rights reserved. // // @class CRRefreshComponent // @abstract 刷新控件的基类 // @discussion 刷新控件的基类 // import UIKit public typealias CRRefreshHandler = (() -> ()) public enum CRRefreshState { /// 普通闲置状态 case idle /// 松开就可以进行刷新的状态 case pulling /// 正在刷新中的状态 case refreshing /// 即将刷新的状态 case willRefresh /// 所有数据加载完毕,没有更多的数据了 case noMoreData } open class CRRefreshComponent: UIView { open weak var scrollView: UIScrollView? open var scrollViewInsets: UIEdgeInsets = .zero open var handler: CRRefreshHandler? open var animator: CRRefreshProtocol! open var state: CRRefreshState = .idle { didSet { DispatchQueue.main.async { self.animator.refresh(view: self, stateDidChange: self.state) } } } fileprivate var isObservingScrollView = false fileprivate var isIgnoreObserving = false fileprivate(set) var isRefreshing = false public override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [.flexibleLeftMargin, .flexibleWidth, .flexibleRightMargin] } public convenience init(animator: CRRefreshProtocol = CRRefreshAnimator(), handler: @escaping CRRefreshHandler) { self.init(frame: .zero) self.handler = handler self.animator = animator } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) // 旧的父控件移除监听 removeObserver() if let newSuperview = newSuperview as? UIScrollView { // 记录UIScrollView最开始的contentInset scrollViewInsets = newSuperview.contentInset DispatchQueue.main.async { [weak self, newSuperview] in guard let weakSelf = self else { return } weakSelf.addObserver(newSuperview) } } } open override func didMoveToSuperview() { super.didMoveToSuperview() scrollView = superview as? UIScrollView let view = animator.view if view.superview == nil { let inset = animator.insets addSubview(view) view.frame = CGRect(x: inset.left, y: inset.top, width: bounds.size.width - inset.left - inset.right, height: bounds.size.height - inset.top - inset.bottom) view.autoresizingMask = [ .flexibleWidth, .flexibleTopMargin, .flexibleHeight, .flexibleBottomMargin ] } } //MARK: Public Methods public final func beginRefreshing() -> Void { guard isRefreshing == false else { return } if self.window != nil { state = .refreshing start() }else { if state != .refreshing { state = .willRefresh // 预防view还没显示出来就调用了beginRefreshing DispatchQueue.main.async { self.scrollViewInsets = self.scrollView?.contentInset ?? .zero if self.state == .willRefresh { self.state = .refreshing self.start() } } } } } public final func endRefreshing() -> Void { guard isRefreshing else { return } self.stop() } public func ignoreObserver(_ ignore: Bool = false) { // 会导致tabview下串 // if let scrollView = scrollView { // scrollView.isScrollEnabled = !ignore // } isIgnoreObserving = ignore } public func start() { isRefreshing = true } public func stop() { isRefreshing = false } public func sizeChange(change: [NSKeyValueChangeKey : Any]?) {} public func offsetChange(change: [NSKeyValueChangeKey : Any]?) {} } //MARK: Observer Methods extension CRRefreshComponent { fileprivate static var context = "CRRefreshContext" fileprivate static let offsetKeyPath = "contentOffset" fileprivate static let contentSizeKeyPath = "contentSize" public static let animationDuration = 0.25 fileprivate func removeObserver() { if let scrollView = superview as? UIScrollView, isObservingScrollView { scrollView.removeObserver(self, forKeyPath: CRRefreshComponent.offsetKeyPath, context: &CRRefreshComponent.context) scrollView.removeObserver(self, forKeyPath: CRRefreshComponent.contentSizeKeyPath, context: &CRRefreshComponent.context) isObservingScrollView = false } } fileprivate func addObserver(_ view: UIView?) { if let scrollView = view as? UIScrollView, !isObservingScrollView { scrollView.addObserver(self, forKeyPath: CRRefreshComponent.offsetKeyPath, options: [.initial, .new], context: &CRRefreshComponent.context) scrollView.addObserver(self, forKeyPath: CRRefreshComponent.contentSizeKeyPath, options: [.initial, .new], context: &CRRefreshComponent.context) isObservingScrollView = true } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &CRRefreshComponent.context { guard isUserInteractionEnabled == true && isHidden == false else { return } if keyPath == CRRefreshComponent.contentSizeKeyPath { if isIgnoreObserving == false { sizeChange(change: change) } } else if keyPath == CRRefreshComponent.offsetKeyPath { if isIgnoreObserving == false { offsetChange(change: change) } } } } }
33.135922
156
0.555084
21126cae3c5878345a43d5e695217f30f84374af
2,374
// // JDSwiftSpinner.swift // SwiftCocoa // // Created by admin on 2017/8/10. // Copyright © 2017年 admin. All rights reserved. // import UIKit class JDSwiftSpinner: NSObject { static let shared = JDSwiftSpinner() fileprivate lazy var backgroundVi:UIView = { let vi = UIView() vi.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) vi.backgroundColor = UIColor.clear return vi }() fileprivate lazy var spinnerVi:UIView = { let vi = UIView() vi.center = CGPoint(x: UIScreen.main.bounds.width*0.5, y: UIScreen.main.bounds.height*0.5) vi.bounds = CGRect(x: 0, y: 0, width: 80, height: 80) vi.backgroundColor = UIColor.clear return vi }() fileprivate lazy var lineLa:JDLineLayer = { let la = JDLineLayer() la.frame = CGRect(x: 0, y: 0, width: 80, height: 80) la.anchorPoint = CGPoint.zero la.position = CGPoint(x: 40, y: 40) return la }() override init() { super.init() } /** * 初始化视图(添加视图) */ fileprivate func initView() { let window = UIApplication.shared.windows[0] window.addSubview(backgroundVi) backgroundVi.addSubview(spinnerVi) spinnerVi.layer.addSublayer(lineLa) } public func show() { initView() } public func dismiss() { backgroundVi.removeFromSuperview() } } class JDLineLayer : CAShapeLayer { override init() { super.init() configLayer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** * 配置layer */ fileprivate func configLayer () { let bezierPa = UIBezierPath(arcCenter: CGPoint(x: bounds.size.width*0.5, y: bounds.size.height*0.5), radius: 30, startAngle: CGFloat(-0.5*Double.pi), endAngle: CGFloat(1.625*Double.pi), clockwise: true) path = bezierPa.cgPath fillColor = nil strokeColor = 0x797C8F.HexColor.cgColor lineWidth = 3 let gradient = CAGradientLayer() } } extension JDLineLayer:CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { } }
23.979798
210
0.58551
1c5ef7df2715d75a3d0ed98a560b22ce295e6534
4,386
// // ViewController.swift // tippy // // Created by natthakorn pattanapongsak on 8/15/17. // Copyright © 2017 natthakorn pattanapongsak. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var eachPay: UILabel! @IBOutlet var mainView: UIView! @IBOutlet weak var numPeople: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let defaults = UserDefaults.standard // Swift 3 syntax, previously NSUserDefaults.standardUserDefaults() let locale = Locale.current let currencySymbol = locale.currencySymbol! defaults.set(18, forKey: "option1Value") defaults.set(20, forKey: "option2Value") defaults.set(25, forKey: "option3Value") defaults.set(1, forKey: "numPeople") defaults.set("18%", forKey: "option1Name") defaults.set("20%",forKey: "option2Name") defaults.set("25%",forKey: "option3Name") numPeople.text = String(defaults.integer(forKey: "numPeople")) tipControl.setTitle(defaults.string(forKey: "option1Name"), forSegmentAt: 0) tipControl.setTitle(defaults.string(forKey: "option2Name"), forSegmentAt: 1) tipControl.setTitle(defaults.string(forKey: "option3Name"), forSegmentAt: 2) print("View Did Load") billField.becomeFirstResponder() eachPay.text = String(format: "%@%@",currencySymbol,"0.00") tipLabel.text = String(format: "%@%@", currencySymbol,"0.00") totalLabel.text = String(format: "%@%@", currencySymbol,"0.00") } func calculateTip(){ let defaults = UserDefaults.standard let option1Value = defaults.integer(forKey: "option1Value") let option2Value = defaults.integer(forKey: "option2Value") let option3Value = defaults.integer(forKey: "option3Value") let tipPercentages = [Double(option1Value)/Double(100),Double(option2Value)/Double(100),Double(option3Value)/Double(100)] let bill = Double(billField.text!) ?? 0 print(tipPercentages[tipControl.selectedSegmentIndex]) let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip // tipControl.segme let locale = Locale.current let currencySymbol = locale.currencySymbol! eachPay.text = String(format: "%@%.2f",currencySymbol,Double(total)/Double(defaults.integer(forKey: "numPeople"))) tipLabel.text = String(format: "%@%.2f", currencySymbol,tip) totalLabel.text = String(format: "%@%.2f", currencySymbol,total) print(currencySymbol); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("view will appear") let defaults = UserDefaults.standard print(defaults.string(forKey: "option1Value") ?? "ss") tipControl.setTitle(defaults.string(forKey: "option1Value")!+"%", forSegmentAt: 0) tipControl.setTitle(defaults.string(forKey: "option2Value")!+"%", forSegmentAt: 1) tipControl.setTitle(defaults.string(forKey: "option3Value")!+"%", forSegmentAt: 2) numPeople.text = String(defaults.integer(forKey: "numPeople")) calculateTip() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("view did appear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("view will disappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("view did disappear") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { calculateTip() } }
34
129
0.641131
2157eba6d0e31445ac430117565a39426e887ffa
617
// // OverpassQueryParserMock.swift // GoMapTests // // Created by Wolfgang Timme on 5/7/19. // Copyright © 2019 Bryce. All rights reserved. // import Foundation @testable import Go_Map__ class OverpassQueryParserMock: NSObject { var parseCallCounter = 0 var queries = [String]() var mockedResult: OverpassQueryParserResult = .success(BaseObjectMatcherMock()) } extension OverpassQueryParserMock: OverpassQueryParsing { func parse(_ query: String) -> OverpassQueryParserResult { parseCallCounter += 1 queries.append(query) return mockedResult } }
22.035714
83
0.696921
bbc1028d9baa6af68ca427dae3524c9d05af9ee2
550
// // CTMediator+Extension.swift // Rickenbacker // // Created by Condy on 2021/10/2. // ///`CTMediator`文档 /// https://github.com/casatwy/CTMediator /// https://casatwy.com/CTMediator_in_Swift.html /// 参考用例 /// https://github.com/yangKJ/Rickenbacker/blob/master/Rickenbacker/Modules/CTMediator/CTMediator/SecondViewController+CTMediator.swift import Foundation #if canImport(CTMediator) import CTMediator @objc public extension CTMediator { @objc static var shared: CTMediator { return CTMediator.sharedInstance() } } #endif
20.37037
135
0.738182
9c077ed47cc0fbfddf73090162282ccf3c8e7b2d
2,703
// // InterfaceController.swift // SnowplowSwiftDemoWatch WatchKit Extension // // Created by Leo Mehlig on 12.11.19. // Copyright © 2019 snowplowanalytics. All rights reserved. // import WatchKit import Foundation import SnowplowTracker class InterfaceController: WKInterfaceController, SPRequestCallback { let kAppId = "DemoAppId" let kNamespace = "DemoAppNamespace" func getTracker(_ url: String, method: SPRequestOptions, protocol _protocol: SPProtocol) -> SPTracker { let emitter = SPEmitter.build({ (builder : SPEmitterBuilder?) -> Void in builder!.setUrlEndpoint(url) builder!.setHttpMethod(method) builder!.setProtocol(_protocol) builder!.setCallback(self) builder!.setEmitRange(500) builder!.setEmitThreadPoolSize(20) builder!.setByteLimitPost(52000) }) let subject = SPSubject(platformContext: true, andGeoContext: false) let newTracker = SPTracker.build({ (builder : SPTrackerBuilder?) -> Void in builder!.setEmitter(emitter) builder!.setAppId(self.kAppId) builder!.setTrackerNamespace(self.kNamespace) builder!.setBase64Encoded(false) builder!.setSessionContext(true) builder!.setSubject(subject) builder!.setLifecycleEvents(true) builder!.setAutotrackScreenViews(true) builder!.setScreenContext(true) builder!.setApplicationContext(true) builder!.setExceptionEvents(true) builder!.setInstallEvent(true) }) return newTracker! } var tracker : SPTracker! override func awake(withContext context: Any?) { super.awake(withContext: context) self.tracker = self.getTracker("acme.fake.com", method: .get, protocol: .http) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func sendEvent() { DispatchQueue.global(qos: .default).async { // Track all types of events DemoUtils.trackAll(self.tracker) } } func onSuccess(withCount successCount: Int) { print("Success: \(successCount)") } func onFailure(withCount failureCount: Int, successCount: Int) { print("Failure: \(failureCount), Success: \(successCount)") } }
33.37037
107
0.63707
6926769d518dc0fd97e7cd1b28464cccc9524a99
654
// // DennyTabBarController.swift // Alamofire // // Created by Denny Caruso on 12/03/2019. // import UIKit class DennyTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.navigationController?.title = "AIUTO" } override func viewWillAppear(_ animated: Bool) { // self.navigationItem.title = self.tabBarController?.tabBar.items?[0].title = NSLocalizedString("BotonMapas", comment: "comment") self.tabBarController?.tabBar.items?[1].title = NSLocalizedString("BotonRA", comment: "comment") self.navigationItem.title = "AIUTO" } }
25.153846
107
0.666667
16ecc7d4dced8c8b04035c69aa18ad21c1e966f8
48,256
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import ArgumentParser import Basics import Build import Dispatch import func Foundation.NSUserName import class Foundation.ProcessInfo import func Foundation.NSHomeDirectory import PackageGraph import PackageLoading import PackageModel import SourceControl import SPMBuildCore import TSCBasic import TSCLibc import TSCUtility import Workspace import XCBuildSupport #if os(Windows) import WinSDK #endif typealias Diagnostic = Basics.Diagnostic private class ToolWorkspaceDelegate: WorkspaceDelegate { /// The stream to use for reporting progress. private let outputStream: ThreadSafeOutputByteStream /// The progress animation for downloads. private let downloadAnimation: NinjaProgressAnimation /// The progress animation for repository fetches. private let fetchAnimation: NinjaProgressAnimation /// Logging level private let logLevel: Diagnostic.Severity private struct DownloadProgress { let bytesDownloaded: Int64 let totalBytesToDownload: Int64 } private struct FetchProgress { let objectsFetched: Int let totalObjectsToFetch: Int } /// The progress of each individual downloads. private var downloadProgress: [String: DownloadProgress] = [:] /// The progress of each individual fetch operation private var fetchProgress: [String: FetchProgress] = [:] private let queue = DispatchQueue(label: "org.swift.swiftpm.commands.tool-workspace-delegate") private let diagnostics: DiagnosticsEngine init(_ outputStream: OutputByteStream, logLevel: Diagnostic.Severity, diagnostics: DiagnosticsEngine) { // FIXME: Implement a class convenience initializer that does this once they are supported // https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924 self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream) self.downloadAnimation = NinjaProgressAnimation(stream: self.outputStream) self.fetchAnimation = NinjaProgressAnimation(stream: self.outputStream) self.logLevel = logLevel self.diagnostics = diagnostics } func fetchingWillBegin(repository: String, fetchDetails: RepositoryManager.FetchDetails?) { queue.async { self.outputStream <<< "Fetching \(repository)" if let fetchDetails = fetchDetails { if fetchDetails.fromCache { self.outputStream <<< " from cache" } } self.outputStream <<< "\n" self.outputStream.flush() } } func fetchingDidFinish(repository: String, fetchDetails: RepositoryManager.FetchDetails?, diagnostic: TSCBasic.Diagnostic?, duration: DispatchTimeInterval) { queue.async { if self.diagnostics.hasErrors { self.fetchAnimation.clear() } let step = self.fetchProgress.values.reduce(0) { $0 + $1.objectsFetched } let total = self.fetchProgress.values.reduce(0) { $0 + $1.totalObjectsToFetch } if step == total && !self.fetchProgress.isEmpty { self.fetchAnimation.complete(success: true) self.fetchProgress.removeAll() } self.outputStream <<< "Fetched \(repository) (\(duration.descriptionInSeconds))" self.outputStream <<< "\n" self.outputStream.flush() } } func repositoryWillUpdate(_ repository: String) { queue.async { self.outputStream <<< "Updating \(repository)" self.outputStream <<< "\n" self.outputStream.flush() } } func repositoryDidUpdate(_ repository: String, duration: DispatchTimeInterval) { queue.async { self.outputStream <<< "Updated \(repository) (\(duration.descriptionInSeconds))" self.outputStream <<< "\n" self.outputStream.flush() } } func dependenciesUpToDate() { queue.async { self.outputStream <<< "Everything is already up-to-date" self.outputStream <<< "\n" self.outputStream.flush() } } func willCreateWorkingCopy(repository: String, at path: AbsolutePath) { queue.async { self.outputStream <<< "Creating working copy for \(repository)" self.outputStream <<< "\n" self.outputStream.flush() } } func willCheckOut(repository: String, revision: String, at path: AbsolutePath) { // noop } func didCheckOut(repository: String, revision: String, at path: AbsolutePath, error: TSCBasic.Diagnostic?) { guard case .none = error else { return // error will be printed before hand } queue.async { self.outputStream <<< "Working copy of \(repository) resolved at \(revision)" self.outputStream <<< "\n" self.outputStream.flush() } } func removing(repository: String) { queue.async { self.outputStream <<< "Removing \(repository)" self.outputStream <<< "\n" self.outputStream.flush() } } func willResolveDependencies(reason: WorkspaceResolveReason) { guard self.logLevel <= .info else { return } queue.sync { self.outputStream <<< Workspace.format(workspaceResolveReason: reason) self.outputStream <<< "\n" self.outputStream.flush() } } func willComputeVersion(package: PackageIdentity, location: String) { queue.async { self.outputStream <<< "Computing version for \(location)" self.outputStream <<< "\n" self.outputStream.flush() } } func didComputeVersion(package: PackageIdentity, location: String, version: String, duration: DispatchTimeInterval) { queue.async { self.outputStream <<< "Computed \(location) at \(version) (\(duration.descriptionInSeconds))" self.outputStream <<< "\n" self.outputStream.flush() } } func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) { queue.async { if let totalBytesToDownload = totalBytesToDownload { self.downloadProgress[url] = DownloadProgress( bytesDownloaded: bytesDownloaded, totalBytesToDownload: totalBytesToDownload) } let step = self.downloadProgress.values.reduce(0, { $0 + $1.bytesDownloaded }) / 1024 let total = self.downloadProgress.values.reduce(0, { $0 + $1.totalBytesToDownload }) / 1024 self.downloadAnimation.update(step: Int(step), total: Int(total), text: "Downloading binary artifacts") } } func didDownloadBinaryArtifacts() { queue.async { if self.diagnostics.hasErrors { self.downloadAnimation.clear() } self.downloadAnimation.complete(success: true) self.downloadProgress.removeAll() } } func fetchingRepository(from repository: String, objectsFetched: Int, totalObjectsToFetch: Int) { queue.async { self.fetchProgress[repository] = FetchProgress( objectsFetched: objectsFetched, totalObjectsToFetch: totalObjectsToFetch) let step = self.fetchProgress.values.reduce(0) { $0 + $1.objectsFetched } let total = self.fetchProgress.values.reduce(0) { $0 + $1.totalObjectsToFetch } self.fetchAnimation.update(step: step, total: total, text: "Fetching objects") } } // noop func willLoadManifest(packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind) {} func didLoadManifest(packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind, manifest: Manifest?, diagnostics: [TSCBasic.Diagnostic]) {} func didCreateWorkingCopy(repository url: String, at path: AbsolutePath, error: TSCBasic.Diagnostic?) {} func resolvedFileChanged() {} } protocol SwiftCommand: ParsableCommand { var swiftOptions: SwiftToolOptions { get } func run(_ swiftTool: SwiftTool) throws } extension SwiftCommand { public func run() throws { let swiftTool = try SwiftTool(options: swiftOptions) try self.run(swiftTool) if swiftTool.observabilityScope.errorsReported || swiftTool.executionStatus == .failure { throw ExitCode.failure } } public static var _errorLabel: String { "error" } } public class SwiftTool { #if os(Windows) // unfortunately this is needed for C callback handlers used by Windows shutdown handler static var shutdownRegistry: (processSet: ProcessSet, buildSystemRef: BuildSystemRef)? #endif /// The original working directory. let originalWorkingDirectory: AbsolutePath /// The options of this tool. let options: SwiftToolOptions /// Path to the root package directory, nil if manifest is not found. let packageRoot: AbsolutePath? /// Helper function to get package root or throw error if it is not found. func getPackageRoot() throws -> AbsolutePath { guard let packageRoot = packageRoot else { throw StringError("Could not find \(Manifest.filename) in this directory or any of its parent directories.") } return packageRoot } /// Get the current workspace root object. func getWorkspaceRoot() throws -> PackageGraphRootInput { let packages: [AbsolutePath] if let workspace = options.multirootPackageDataFile { packages = try XcodeWorkspaceLoader(diagnostics: self.observabilityScope.makeDiagnosticsEngine()).load(workspace: workspace) } else { packages = [try getPackageRoot()] } return PackageGraphRootInput(packages: packages) } /// Path to the build directory. let buildPath: AbsolutePath /// The process set to hold the launched processes. These will be terminated on any signal /// received by the swift tools. let processSet: ProcessSet /// The current build system reference. The actual reference is present only during an active build. let buildSystemRef: BuildSystemRef /// The execution status of the tool. var executionStatus: ExecutionStatus = .success /// The stream to print standard output on. fileprivate(set) var outputStream: OutputByteStream = TSCBasic.stdoutStream /// Holds the currently active workspace. /// /// It is not initialized in init() because for some of the commands like package init , usage etc, /// workspace is not needed, infact it would be an error to ask for the workspace object /// for package init because the Manifest file should *not* present. private var _workspace: Workspace? private var _workspaceDelegate: ToolWorkspaceDelegate? let observabilityScope: ObservabilityScope let logLevel: Diagnostic.Severity /// Create an instance of this tool. /// /// - parameter args: The command line arguments to be passed to this tool. public init(options: SwiftToolOptions) throws { // first, bootstrap the observability syste self.logLevel = options.logLevel let observabilitySystem = ObservabilitySystem.init(SwiftToolObservability(logLevel: self.logLevel)) self.observabilityScope = observabilitySystem.topScope // Capture the original working directory ASAP. guard let cwd = localFileSystem.currentWorkingDirectory else { self.observabilityScope.emit(error: "couldn't determine the current working directory") throw ExitCode.failure } originalWorkingDirectory = cwd do { try Self.postprocessArgParserResult(options: options, observabilityScope: self.observabilityScope) self.options = options // Honor package-path option is provided. if let packagePath = options.packagePath ?? options.chdir { try ProcessEnv.chdir(packagePath) } let processSet = ProcessSet() let buildSystemRef = BuildSystemRef() #if os(Windows) // set shutdown handler to terminate sub-processes, etc SwiftTool.shutdownRegistry = (processSet: processSet, buildSystemRef: buildSystemRef) _ = SetConsoleCtrlHandler({ _ in // Terminate all processes on receiving an interrupt signal. SwiftTool.shutdownRegistry?.processSet.terminate() SwiftTool.shutdownRegistry?.buildSystemRef.buildSystem?.cancel() // Reset the handler. _ = SetConsoleCtrlHandler(nil, false) // Exit as if by signal() TerminateProcess(GetCurrentProcess(), 3) return true }, true) #else // trap SIGINT to terminate sub-processes, etc signal(SIGINT, SIG_IGN) let interruptSignalSource = DispatchSource.makeSignalSource(signal: SIGINT) interruptSignalSource.setEventHandler { // cancel the trap? interruptSignalSource.cancel() // Terminate all processes on receiving an interrupt signal. processSet.terminate() buildSystemRef.buildSystem?.cancel() #if os(macOS) || os(OpenBSD) // Install the default signal handler. var action = sigaction() action.__sigaction_u.__sa_handler = SIG_DFL sigaction(SIGINT, &action, nil) kill(getpid(), SIGINT) #elseif os(Android) // Install the default signal handler. var action = sigaction() action.sa_handler = SIG_DFL sigaction(SIGINT, &action, nil) kill(getpid(), SIGINT) #else var action = sigaction() action.__sigaction_handler = unsafeBitCast( SIG_DFL, to: sigaction.__Unnamed_union___sigaction_handler.self) sigaction(SIGINT, &action, nil) kill(getpid(), SIGINT) #endif } interruptSignalSource.resume() #endif self.processSet = processSet self.buildSystemRef = buildSystemRef } catch { self.observabilityScope.emit(error) throw ExitCode.failure } // Create local variables to use while finding build path to avoid capture self before init error. let customBuildPath = options.buildPath let packageRoot = findPackageRoot() self.packageRoot = packageRoot self.buildPath = getEnvBuildPath(workingDir: cwd) ?? customBuildPath ?? (packageRoot ?? cwd).appending(component: ".build") // set verbosity globals. // TODO: get rid of this global settings in TSC switch self.logLevel { case .debug: TSCUtility.verbosity = .debug case .info: TSCUtility.verbosity = .verbose case .warning, .error: TSCUtility.verbosity = .concise } Process.verbose = TSCUtility.verbosity != .concise } static func postprocessArgParserResult(options: SwiftToolOptions, observabilityScope: ObservabilityScope) throws { if options.chdir != nil { observabilityScope.emit(warning: "'--chdir/-C' option is deprecated; use '--package-path' instead") } if options.multirootPackageDataFile != nil { observabilityScope.emit(.unsupportedFlag("--multiroot-data-file")) } if options.useExplicitModuleBuild && !options.useIntegratedSwiftDriver { observabilityScope.emit(error: "'--experimental-explicit-module-build' option requires '--use-integrated-swift-driver'") } if !options.archs.isEmpty && options.customCompileTriple != nil { observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: ["--arch", "--triple"])) } // --enable-test-discovery should never be called on darwin based platforms #if canImport(Darwin) if options.enableTestDiscovery { observabilityScope.emit(warning: "'--enable-test-discovery' option is deprecated; tests are automatically discovered on all platforms") } #endif if options.shouldDisableManifestCaching { observabilityScope.emit(warning: "'--disable-package-manifest-caching' option is deprecated; use '--manifest-caching' instead") } if let _ = options.netrcFilePath, options.netrc == false { observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: ["--disable-netrc", "--netrc-file"])) } if options._deprecated_netrc { observabilityScope.emit(warning: "'--netrc' option is deprecated; .netrc files are located by default") } if options._deprecated_netrcOptional { observabilityScope.emit(warning: "'--netrc-optional' option is deprecated; .netrc files are located by default") } if options._deprecated_enableResolverTrace { observabilityScope.emit(warning: "'--enableResolverTrace' option is deprecated; use --verbose flag to log resolver output") } } private func editsDirectory() throws -> AbsolutePath { // TODO: replace multiroot-data-file with explicit overrides if let multiRootPackageDataFile = options.multirootPackageDataFile { return multiRootPackageDataFile.appending(component: "Packages") } return try Workspace.DefaultLocations.editsDirectory(forRootPackage: self.getPackageRoot()) } private func resolvedVersionsFile() throws -> AbsolutePath { // TODO: replace multiroot-data-file with explicit overrides if let multiRootPackageDataFile = options.multirootPackageDataFile { return multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "Package.resolved") } return try Workspace.DefaultLocations.resolvedVersionsFile(forRootPackage: self.getPackageRoot()) } func getMirrorsConfig(sharedConfigurationDirectory: AbsolutePath? = nil) throws -> Workspace.Configuration.Mirrors { let sharedConfigurationDirectory = try sharedConfigurationDirectory ?? self.getSharedConfigurationDirectory() let sharedMirrorFile = sharedConfigurationDirectory.map { Workspace.DefaultLocations.mirrorsConfigurationFile(at: $0) } return try .init( localMirrorFile: self.mirrorsConfigFile(), sharedMirrorFile: sharedMirrorFile, fileSystem: localFileSystem ) } private func mirrorsConfigFile() throws -> AbsolutePath { // TODO: does this make sense now that we a global configuration as well? or should we at least rename it? // Look for the override in the environment. if let envPath = ProcessEnv.vars["SWIFTPM_MIRROR_CONFIG"] { return try AbsolutePath(validating: envPath) } // Otherwise, use the default path. // TODO: replace multiroot-data-file with explicit overrides if let multiRootPackageDataFile = options.multirootPackageDataFile { // migrate from legacy location let legacyPath = multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "config") let newPath = multiRootPackageDataFile.appending(components: "xcshareddata", "swiftpm", "configuration", "mirrors.json") if localFileSystem.exists(legacyPath) { try localFileSystem.createDirectory(newPath.parentDirectory, recursive: true) try localFileSystem.move(from: legacyPath, to: newPath) } return newPath } // migrate from legacy location let legacyPath = try self.getPackageRoot().appending(components: ".swiftpm", "config") let newPath = try Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: self.getPackageRoot()) if localFileSystem.exists(legacyPath) { try localFileSystem.createDirectory(newPath.parentDirectory, recursive: true) try localFileSystem.move(from: legacyPath, to: newPath) } return newPath } func getRegistriesConfig(sharedConfigurationDirectory: AbsolutePath? = nil) throws -> Workspace.Configuration.Registries { let localRegistriesFile = try Workspace.DefaultLocations.registriesConfigurationFile(forRootPackage: self.getPackageRoot()) let sharedConfigurationDirectory = try sharedConfigurationDirectory ?? self.getSharedConfigurationDirectory() let sharedRegistriesFile = sharedConfigurationDirectory.map { Workspace.DefaultLocations.registriesConfigurationFile(at: $0) } return try .init( localRegistriesFile: localRegistriesFile, sharedRegistriesFile: sharedRegistriesFile, fileSystem: localFileSystem ) } func getAuthorizationProvider() throws -> AuthorizationProvider? { var providers = [AuthorizationProvider]() // netrc file has higher specificity than keychain so use it first try providers.append(contentsOf: self.getNetrcAuthorizationProviders()) #if canImport(Security) if self.options.keychain { providers.append(KeychainAuthorizationProvider(observabilityScope: self.observabilityScope)) } #endif return providers.isEmpty ? .none : CompositeAuthorizationProvider(providers, observabilityScope: self.observabilityScope) } func getNetrcAuthorizationProviders() throws -> [NetrcAuthorizationProvider] { guard options.netrc else { return [] } var providers = [NetrcAuthorizationProvider]() // Use custom .netrc file if specified, otherwise look for it within workspace and user's home directory. if let configuredPath = options.netrcFilePath { guard localFileSystem.exists(configuredPath) else { throw StringError("Did not find .netrc file at \(configuredPath).") } providers.append(try NetrcAuthorizationProvider(path: configuredPath, fileSystem: localFileSystem)) } else { // User didn't tell us to use these .netrc files so be more lenient with errors func loadNetrcNoThrows(at path: AbsolutePath) -> NetrcAuthorizationProvider? { guard localFileSystem.exists(path) else { return nil } do { return try NetrcAuthorizationProvider(path: path, fileSystem: localFileSystem) } catch { self.observabilityScope.emit(warning: "Failed to load .netrc file at \(path). Error: \(error)") return nil } } // Workspace's .netrc file should be consulted before user-global file // TODO: replace multiroot-data-file with explicit overrides if let localPath = try? (options.multirootPackageDataFile ?? self.getPackageRoot()).appending(component: ".netrc"), let localProvider = loadNetrcNoThrows(at: localPath) { providers.append(localProvider) } let userHomePath = localFileSystem.homeDirectory.appending(component: ".netrc") if let userHomeProvider = loadNetrcNoThrows(at: userHomePath) { providers.append(userHomeProvider) } } return providers } private func getSharedCacheDirectory() throws -> AbsolutePath? { if let explicitCachePath = options.cachePath { // Create the explicit cache path if necessary if !localFileSystem.exists(explicitCachePath) { try localFileSystem.createDirectory(explicitCachePath, recursive: true) } return explicitCachePath } do { return try localFileSystem.getOrCreateSwiftPMCacheDirectory() } catch { self.observabilityScope.emit(warning: "Failed creating default cache location, \(error)") return .none } } private func getSharedConfigurationDirectory() throws -> AbsolutePath? { if let explicitConfigPath = options.configPath { // Create the explicit config path if necessary if !localFileSystem.exists(explicitConfigPath) { try localFileSystem.createDirectory(explicitConfigPath, recursive: true) } return explicitConfigPath } do { return try localFileSystem.getOrCreateSwiftPMConfigDirectory() } catch { self.observabilityScope.emit(warning: "Failed creating default configuration location, \(error)") return .none } } /// Returns the currently active workspace. func getActiveWorkspace() throws -> Workspace { if let workspace = _workspace { return workspace } let delegate = ToolWorkspaceDelegate(self.outputStream, logLevel: self.logLevel, diagnostics: self.observabilityScope.makeDiagnosticsEngine()) let provider = GitRepositoryProvider(processSet: self.processSet) let sharedCacheDirectory = try self.getSharedCacheDirectory() let sharedConfigurationDirectory = try self.getSharedConfigurationDirectory() let isXcodeBuildSystemEnabled = self.options.buildSystem == .xcode let workspace = try Workspace( fileSystem: localFileSystem, location: .init( workingDirectory: buildPath, editsDirectory: self.editsDirectory(), resolvedVersionsFile: self.resolvedVersionsFile(), sharedCacheDirectory: sharedCacheDirectory, sharedConfigurationDirectory: sharedConfigurationDirectory ), mirrors: self.getMirrorsConfig(sharedConfigurationDirectory: sharedConfigurationDirectory).mirrors, registries: try self.getRegistriesConfig(sharedConfigurationDirectory: sharedConfigurationDirectory).configuration, authorizationProvider: self.getAuthorizationProvider(), customManifestLoader: self.getManifestLoader(), // FIXME: doe we really need to customize it? customRepositoryProvider: provider, // FIXME: doe we really need to customize it? additionalFileRules: isXcodeBuildSystemEnabled ? FileRuleDescription.xcbuildFileTypes : FileRuleDescription.swiftpmFileTypes, resolverUpdateEnabled: !options.skipDependencyUpdate, resolverPrefetchingEnabled: options.shouldEnableResolverPrefetching, sharedRepositoriesCacheEnabled: self.options.useRepositoriesCache, delegate: delegate ) _workspace = workspace _workspaceDelegate = delegate return workspace } /// Start redirecting the standard output stream to the standard error stream. func redirectStdoutToStderr() { self.outputStream = TSCBasic.stderrStream } /// Resolve the dependencies. func resolve() throws { let workspace = try getActiveWorkspace() let root = try getWorkspaceRoot() if options.forceResolvedVersions { try workspace.resolveBasedOnResolvedVersionsFile(root: root, diagnostics: self.observabilityScope.makeDiagnosticsEngine()) } else { try workspace.resolve(root: root, diagnostics: self.observabilityScope.makeDiagnosticsEngine()) } // Throw if there were errors when loading the graph. // The actual errors will be printed before exiting. guard !self.observabilityScope.errorsReported else { throw ExitCode.failure } } /// Fetch and load the complete package graph. /// /// - Parameters: /// - explicitProduct: The product specified on the command line to a “swift run” or “swift build” command. This allows executables from dependencies to be run directly without having to hook them up to any particular target. @discardableResult func loadPackageGraph( explicitProduct: String? = nil, createMultipleTestProducts: Bool = false, createREPLProduct: Bool = false ) throws -> PackageGraph { do { let workspace = try getActiveWorkspace() // Fetch and load the package graph. let graph = try workspace.loadPackageGraph( rootInput: getWorkspaceRoot(), explicitProduct: explicitProduct, createMultipleTestProducts: createMultipleTestProducts, createREPLProduct: createREPLProduct, forceResolvedVersions: options.forceResolvedVersions, observabilityScope: self.observabilityScope ) // Throw if there were errors when loading the graph. // The actual errors will be printed before exiting. guard !self.observabilityScope.errorsReported else { throw ExitCode.failure } return graph } catch { throw error } } /// Invoke plugins for any reachable targets in the graph, and return a mapping from targets to corresponding evaluation results. func invokePlugins(graph: PackageGraph) throws -> [ResolvedTarget: [PluginInvocationResult]] { do { // Configure the plugin invocation inputs. // The `plugins` directory is inside the workspace's main data directory, and contains all temporary // files related to all plugins in the workspace. let buildEnvironment = try buildParameters().buildEnvironment let dataDir = try self.getActiveWorkspace().location.workingDirectory let pluginsDir = dataDir.appending(component: "plugins") // The `cache` directory is in the plugins directory and is where the plugin script runner caches // compiled plugin binaries and any other derived information. let cacheDir = pluginsDir.appending(component: "cache") let pluginScriptRunner = try DefaultPluginScriptRunner(cacheDir: cacheDir, toolchain: self._hostToolchain.get().configuration) // The `outputs` directory contains subdirectories for each combination of package, target, and plugin. // Each usage of a plugin has an output directory that is writable by the plugin, where it can write // additional files, and to which it can configure tools to write their outputs, etc. let outputDir = pluginsDir.appending(component: "outputs") // The `tools` directory contains any command line tools (executables) that are available for any commands // defined by the executable. // FIXME: At the moment we just pass the built products directory for the host. We will need to extend this // with a map of the names of tools available to each plugin. In particular this would not work with any // binary targets. let builtToolsDir = dataDir.appending(components: try self._hostToolchain.get().triple.platformBuildPathComponent(), buildEnvironment.configuration.dirname) // Create the cache directory, if needed. try localFileSystem.createDirectory(cacheDir, recursive: true) // Ask the graph to invoke plugins, and return the result. let result = try graph.invokePlugins( outputDir: outputDir, builtToolsDir: builtToolsDir, pluginScriptRunner: pluginScriptRunner, diagnostics: self.observabilityScope.makeDiagnosticsEngine(), fileSystem: localFileSystem ) return result } catch { throw error } } /// Returns the user toolchain to compile the actual product. func getToolchain() throws -> UserToolchain { return try _destinationToolchain.get() } func getManifestLoader() throws -> ManifestLoader { return try _manifestLoader.get() } private func canUseCachedBuildManifest() throws -> Bool { if !self.options.cacheBuildManifest { return false } let buildParameters = try self.buildParameters() let haveBuildManifestAndDescription = localFileSystem.exists(buildParameters.llbuildManifest) && localFileSystem.exists(buildParameters.buildDescriptionPath) if !haveBuildManifestAndDescription { return false } // Perform steps for build manifest caching if we can enabled it. // // FIXME: We don't add edited packages in the package structure command yet (SR-11254). let hasEditedPackages = try self.getActiveWorkspace().state.dependencies.contains(where: { $0.isEdited }) if hasEditedPackages { return false } return true } func createBuildOperation(explicitProduct: String? = nil, cacheBuildManifest: Bool = true) throws -> BuildOperation { // Load a custom package graph which has a special product for REPL. let graphLoader = { try self.loadPackageGraph(explicitProduct: explicitProduct) } // Construct the build operation. let buildOp = try BuildOperation( buildParameters: buildParameters(), cacheBuildManifest: cacheBuildManifest && self.canUseCachedBuildManifest(), packageGraphLoader: graphLoader, pluginInvoker: { _ in [:] }, outputStream: self.outputStream, logLevel: self.logLevel, fileSystem: localFileSystem, observabilityScope: self.observabilityScope ) // Save the instance so it can be cancelled from the int handler. buildSystemRef.buildSystem = buildOp return buildOp } func createBuildSystem(explicitProduct: String? = nil, buildParameters: BuildParameters? = nil) throws -> BuildSystem { let buildSystem: BuildSystem switch options.buildSystem { case .native: let graphLoader = { try self.loadPackageGraph(explicitProduct: explicitProduct) } let pluginInvoker = { try self.invokePlugins(graph: $0) } buildSystem = try BuildOperation( buildParameters: buildParameters ?? self.buildParameters(), cacheBuildManifest: self.canUseCachedBuildManifest(), packageGraphLoader: graphLoader, pluginInvoker: pluginInvoker, outputStream: self.outputStream, logLevel: self.logLevel, fileSystem: localFileSystem, observabilityScope: self.observabilityScope ) case .xcode: let graphLoader = { try self.loadPackageGraph(explicitProduct: explicitProduct, createMultipleTestProducts: true) } // FIXME: Implement the custom build command provider also. buildSystem = try XcodeBuildSystem( buildParameters: buildParameters ?? self.buildParameters(), packageGraphLoader: graphLoader, outputStream: self.outputStream, logLevel: self.logLevel, fileSystem: localFileSystem, observabilityScope: self.observabilityScope ) } // Save the instance so it can be cancelled from the int handler. buildSystemRef.buildSystem = buildSystem return buildSystem } /// Return the build parameters. func buildParameters() throws -> BuildParameters { return try _buildParameters.get() } private lazy var _buildParameters: Result<BuildParameters, Swift.Error> = { return Result(catching: { let toolchain = try self.getToolchain() let triple = toolchain.triple /// Checks if stdout stream is tty. let isTTY: Bool = { let stream: OutputByteStream if let threadSafeStream = self.outputStream as? ThreadSafeOutputByteStream { stream = threadSafeStream.stream } else { stream = self.outputStream } guard let fileStream = stream as? LocalFileOutputByteStream else { return false } return TerminalController.isTTY(fileStream) }() // Use "apple" as the subdirectory because in theory Xcode build system // can be used to build for any Apple platform and it has it's own // conventions for build subpaths based on platforms. let dataPath = buildPath.appending( component: options.buildSystem == .xcode ? "apple" : triple.platformBuildPathComponent()) return BuildParameters( dataPath: dataPath, configuration: options.configuration, toolchain: toolchain, destinationTriple: triple, archs: options.archs, flags: options.buildFlags, xcbuildFlags: options.xcbuildFlags, jobs: options.jobs ?? UInt32(ProcessInfo.processInfo.activeProcessorCount), shouldLinkStaticSwiftStdlib: options.shouldLinkStaticSwiftStdlib, canRenameEntrypointFunctionName: SwiftTargetBuildDescription.checkSupportedFrontendFlags( flags: ["entry-point-function-name"], fileSystem: localFileSystem ), sanitizers: options.enabledSanitizers, enableCodeCoverage: options.shouldEnableCodeCoverage, indexStoreMode: options.indexStoreMode.indexStoreMode, enableParseableModuleInterfaces: options.shouldEnableParseableModuleInterfaces, emitSwiftModuleSeparately: options.emitSwiftModuleSeparately, useIntegratedSwiftDriver: options.useIntegratedSwiftDriver, useExplicitModuleBuild: options.useExplicitModuleBuild, isXcodeBuildSystemEnabled: options.buildSystem == .xcode, printManifestGraphviz: options.printManifestGraphviz, forceTestDiscovery: options.enableTestDiscovery, // backwards compatibility, remove with --enable-test-discovery isTTY: isTTY ) }) }() /// Lazily compute the destination toolchain. private lazy var _destinationToolchain: Result<UserToolchain, Swift.Error> = { var destination: Destination let hostDestination: Destination do { hostDestination = try self._hostToolchain.get().destination // Create custom toolchain if present. if let customDestination = self.options.customCompileDestination { destination = try Destination(fromFile: customDestination) } else if let target = self.options.customCompileTriple, let targetDestination = Destination.defaultDestination(for: target, host: hostDestination) { destination = targetDestination } else { // Otherwise use the host toolchain. destination = hostDestination } } catch { return .failure(error) } // Apply any manual overrides. if let triple = self.options.customCompileTriple { destination.target = triple } if let binDir = self.options.customCompileToolchain { destination.binDir = binDir.appending(components: "usr", "bin") } if let sdk = self.options.customCompileSDK { destination.sdk = sdk } destination.archs = options.archs // Check if we ended up with the host toolchain. if hostDestination == destination { return self._hostToolchain } return Result(catching: { try UserToolchain(destination: destination) }) }() /// Lazily compute the host toolchain used to compile the package description. private lazy var _hostToolchain: Result<UserToolchain, Swift.Error> = { return Result(catching: { try UserToolchain(destination: Destination.hostDestination( originalWorkingDirectory: self.originalWorkingDirectory)) }) }() private lazy var _manifestLoader: Result<ManifestLoader, Swift.Error> = { return Result(catching: { let cachePath: AbsolutePath? switch (self.options.shouldDisableManifestCaching, self.options.manifestCachingMode) { case (true, _): // backwards compatibility cachePath = .none case (false, .none): cachePath = .none case (false, .local): cachePath = self.buildPath case (false, .shared): cachePath = try self.getSharedCacheDirectory().map{ Workspace.DefaultLocations.manifestsDirectory(at: $0) } } var extraManifestFlags = self.options.manifestFlags // Disable the implicit concurrency import if the compiler in use supports it to avoid warnings if we are building against an older SDK that does not contain a Concurrency module. if SwiftTargetBuildDescription.checkSupportedFrontendFlags(flags: ["disable-implicit-concurrency-module-import"], fileSystem: localFileSystem) { extraManifestFlags += ["-Xfrontend", "-disable-implicit-concurrency-module-import"] } return try ManifestLoader( // Always use the host toolchain's resources for parsing manifest. toolchain: self._hostToolchain.get().configuration, isManifestSandboxEnabled: !self.options.shouldDisableSandbox, cacheDir: cachePath, extraManifestFlags: extraManifestFlags ) }) }() /// An enum indicating the execution status of run commands. enum ExecutionStatus { case success case failure } } /// Returns path of the nearest directory containing the manifest file w.r.t /// current working directory. private func findPackageRoot() -> AbsolutePath? { guard var root = localFileSystem.currentWorkingDirectory else { return nil } // FIXME: It would be nice to move this to a generalized method which takes path and predicate and // finds the lowest path for which the predicate is true. while !localFileSystem.isFile(root.appending(component: Manifest.filename)) { root = root.parentDirectory guard !root.isRoot else { return nil } } return root } /// Returns the build path from the environment, if present. private func getEnvBuildPath(workingDir: AbsolutePath) -> AbsolutePath? { // Don't rely on build path from env for SwiftPM's own tests. guard ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"] == nil else { return nil } guard let env = ProcessEnv.vars["SWIFTPM_BUILD_DIR"] else { return nil } return AbsolutePath(env, relativeTo: workingDir) } /// A wrapper to hold the build system so we can use it inside /// the int. handler without requiring to initialize it. final class BuildSystemRef { var buildSystem: BuildSystem? } extension Basics.Diagnostic { static func unsupportedFlag(_ flag: String) -> Self { .warning("\(flag) is an *unsupported* option which can be removed at any time; do not rely on it") } } extension DispatchTimeInterval { var descriptionInSeconds: String { switch self { case .seconds(let value): return "\(value)s" case .milliseconds(let value): return String(format: "%.2f", Double(value)/Double(1000)) + "s" case .microseconds(let value): return String(format: "%.2f", Double(value)/Double(1_000_000)) + "s" case .nanoseconds(let value): return String(format: "%.2f", Double(value)/Double(1_000_000_000)) + "s" case .never: return "n/a" #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @unknown default: return "n/a" #endif } } } // MARK: - Diagnostics private struct SwiftToolObservability: ObservabilityHandlerProvider, DiagnosticsHandler { private let logLevel: Diagnostic.Severity var diagnosticsHandler: DiagnosticsHandler { self } init(logLevel: Diagnostic.Severity) { self.logLevel = logLevel } func handleDiagnostic(scope: ObservabilityScope, diagnostic: Basics.Diagnostic) { // TODO: do something useful with scope if diagnostic.severity >= self.logLevel { diagnostic.print() } } } extension Basics.Diagnostic { func print() { let writer = InteractiveWriter.stderr if let diagnosticPrefix = self.metadata?.diagnosticPrefix { writer.write(diagnosticPrefix) writer.write(": ") } switch self.severity { case .error: writer.write("error: ", inColor: .red, bold: true) case .warning: writer.write("warning: ", inColor: .yellow, bold: true) case .info: writer.write("info: ", inColor: .white, bold: true) case .debug: writer.write("debug: ", inColor: .white, bold: true) } writer.write(self.message) writer.write("\n") } } /// This class is used to write on the underlying stream. /// /// If underlying stream is a not tty, the string will be written in without any /// formatting. private final class InteractiveWriter { /// The standard error writer. static let stderr = InteractiveWriter(stream: TSCBasic.stderrStream) /// The standard output writer. static let stdout = InteractiveWriter(stream: TSCBasic.stdoutStream) /// The terminal controller, if present. let term: TerminalController? /// The output byte stream reference. let stream: OutputByteStream /// Create an instance with the given stream. init(stream: OutputByteStream) { self.term = TerminalController(stream: stream) self.stream = stream } /// Write the string to the contained terminal or stream. func write(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) { if let term = term { term.write(string, inColor: color, bold: bold) } else { stream <<< string stream.flush() } } } // FIXME: this is for backwards compatibility with existing diagnostics printing format // we should remove this as we make use of the new scope and metadata to provide better contextual information extension ObservabilityMetadata { fileprivate var diagnosticPrefix: String? { if let packageIdentity = self.packageIdentity, let packageLocation = self.packageLocation { return "'\(packageIdentity)' \(packageLocation)" } else if let legacyLocation = self.legacyDiagnosticLocation { return legacyLocation.description } else { return .none } } } extension SwiftToolOptions { var logLevel: Diagnostic.Severity { if self.verbose { return .info } else if self.veryVerbose { return .debug } else { return .warning } } }
41.13896
231
0.649184
50e7159de9f4ce7e4d4466e7ec66e7b1ee0bdc4c
8,191
import Quick import Nimble @testable import MiniApp // swiftlint:disable function_body_length class MiniAppInfoFetcherTests: QuickSpec { override func spec() { describe("fetch mini apps list") { context("when request from server returns valid data") { it("will decode the response with MiniAppInfo decodable") { let mockAPIClient = MockAPIClient() var decodedResponse: [MiniAppInfo]? let miniAppInfoFetcher = MiniAppInfoFetcher() let responseString = """ [ { "id": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } },{ "id": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } }] """ mockAPIClient.data = responseString.data(using: .utf8) miniAppInfoFetcher.fetchList(apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success(let responseData): decodedResponse = responseData case .failure: break } }) expect(decodedResponse).toEventually(beAnInstanceOf([MiniAppInfo].self)) } } context("when request from server returns invalid data") { it("will decode the response with MiniAppInfo decodable") { let mockAPIClient = MockAPIClient() var testError: NSError? let miniAppInfoFetcher = MiniAppInfoFetcher() let responseString = """ [ { "test": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } },{ "id": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } }] """ mockAPIClient.data = responseString.data(using: .utf8) miniAppInfoFetcher.fetchList(apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success: break case .failure(let error): testError = error as NSError } }) expect(testError?.code).toEventually(equal(0)) } } context("when request from server returns error") { it("will pass an error with status code and failure completion handler is called") { let mockAPIClient = MockAPIClient() var testError: NSError? mockAPIClient.error = NSError( domain: "Test", code: 123, userInfo: nil ) let miniAppInfoFetcher = MiniAppInfoFetcher() miniAppInfoFetcher.fetchList(apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success: break case .failure(let error): testError = error as NSError } }) expect(testError?.code).toEventually(equal(123)) } } } describe("fetch mini app") { context("when request from server returns valid data") { it("will decode the response with MiniAppInfo decodable") { let mockAPIClient = MockAPIClient() var decodedResponse: MiniAppInfo? let miniAppInfoFetcher = MiniAppInfoFetcher() let responseString = """ [{ "id": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } }] """ mockAPIClient.data = responseString.data(using: .utf8) miniAppInfoFetcher.getInfo(miniAppId: "123", apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success(let responseData): decodedResponse = responseData case .failure: break } }) expect(decodedResponse).toEventually(beAnInstanceOf(MiniAppInfo.self)) } } context("when request from server returns invalid data") { it("will decode the response with MiniAppInfo decodable") { let mockAPIClient = MockAPIClient() var testError: NSError? let miniAppInfoFetcher = MiniAppInfoFetcher() let responseString = """ [{ "test": "123", "displayName": "Test", "icon": "https://test.com", "version": { "versionTag": "1.0.0", "versionId": "455" } }] """ mockAPIClient.data = responseString.data(using: .utf8) miniAppInfoFetcher.getInfo(miniAppId: "123", apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success: break case .failure(let error): testError = error as NSError } }) expect(testError?.code).toEventually(equal(0)) } } context("when request from server returns error") { it("will pass an error with status code and failure completion handler is called") { let mockAPIClient = MockAPIClient() var testError: NSError? mockAPIClient.error = NSError( domain: "Test", code: 123, userInfo: nil ) let miniAppInfoFetcher = MiniAppInfoFetcher() miniAppInfoFetcher.fetchList(apiClient: mockAPIClient, completionHandler: { (result) in switch result { case .success: break case .failure(let error): testError = error as NSError } }) expect(testError?.code).toEventually(equal(123)) } } } } }
43.569149
123
0.396044
dd8e28236e4242448afc69e8484da8cedc84be92
1,661
// // AINetworkWebviewTestController.swift // GleanerExample // // Created by 李盛安 on 2019/11/18. // Copyright © 2019 Aisino. All rights reserved. // import UIKit import WebKit class AINetworkWebviewTestController: UIViewController { let currentModel = AINetworkModel() // wkWebView lazy var wkWebView = WKWebView() // url var _url: URL! var url: URL! { set { _url = newValue wkWebView.load(URLRequest(url: newValue)) } get { return _url } } override func viewDidLoad() { super.viewDidLoad() wkWebView.navigationDelegate = self self.view.addSubview(self.wkWebView) wkWebView.snp.makeConstraints { (make) in make.top.left.bottom.right.equalToSuperview() } } } extension AINetworkWebviewTestController: WKNavigationDelegate { // 监听 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { } // 页面开始加载时调用 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print("开始加载...") } // 当内容开始返回时调用 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { print("当内容开始返回...") } // 页面加载完成之后调用 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { print("页面加载完成...") } // 页面加载失败时调用 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("页面加载失败...") } }
24.426471
151
0.62071
08fe1add811b6b59984014632848014764dc6560
520
// // KQHomeWorker.swift // TaskProjectDemo // // Created by Muhammad Qasim Muhammad Mubeen on 28/01/2022. // Copyright (c) 2022 ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit class KQHomeWorker { // RequestValidation func homeApiRequest(completion:@escaping((_ message:HomeModel?,_ error:Error?) -> ())) { } }
23.636364
88
0.696154
e5d10998ccce791d98e05aaf639b0899c7c1b195
368
// // FirstViewController.swift // Emojify // // Created by Imad ENNEIYMY on 22/01/2019. // Copyright © 2019 Imad ENNEIYMY. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
17.52381
80
0.679348
e428dc4a138caf6e73b4c48b46086d663e470254
610
// // TaskViewModel.swift // PomodoroHub (iOS) // // Created by 鈴木航 on 2020/09/21. // import Foundation import Combine class TaskViewModel: ObservableObject { let id: UUID @Published var title = "" @Published var taskDescription = "" init(task: Task? = nil) { if let task = task { id = task.id ?? UUID() title = task.title ?? "" taskDescription = task.taskDescription ?? "" } else { id = UUID() } } private static let unknown = "" var valid: Bool { get { return !title.isEmpty } } }
19.677419
56
0.531148
718a3043d9adcf573ef2ca8036ffc51a47b88825
889
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // import XCTest import Nimble @testable import EmbeddedSocial class AcceptPendingUserOperationTests: XCTestCase { func testThatItUsesCorrectServiceMethod() { // given let service = MockSocialService() service.acceptPendingReturnResult = .success() let command = UserCommand(user: User()) let sut = AcceptPendingUserOperation(command: command, socialService: service) // when let queue = OperationQueue() queue.addOperation(sut) queue.waitUntilAllOperationsAreFinished() // then expect(service.acceptPendingCalled).to(beTrue()) expect(service.acceptPendingInputUser).to(equal(command.user)) } }
29.633333
91
0.67829
d721c040dee823d92ad03040972d40f2a49d40f7
2,776
// // Copyright (c) 2018 cauli.works // // 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 internal final class MemoryStorage: Storage { var records: [Record] = [] var capacity: StorageCapacity { didSet { ensureCapacity() } } var preStorageRecordModifier: RecordModifier? init(capacity: StorageCapacity, preStorageRecordModifier: RecordModifier? = nil) { self.capacity = capacity self.preStorageRecordModifier = preStorageRecordModifier } func store(_ record: Record) { assert(Thread.isMainThread, "\(#file):\(#line) must run on the main thread!") let modifiedRecord = preStorageRecordModifier?.modify(record) ?? record if let recordIndex = records.firstIndex(where: { $0.identifier == modifiedRecord.identifier }) { records[recordIndex] = modifiedRecord } else { records.insert(modifiedRecord, at: 0) ensureCapacity() } } func records(_ count: Int, after record: Record?) -> [Record] { assert(Thread.isMainThread, "\(#file):\(#line) must run on the main thread!") let index: Int if let record = record, let recordIndex = records.firstIndex(where: { $0.identifier == record.identifier }) { index = recordIndex + 1 } else { index = 0 } let maxCount = min(count, records.count - index) return Array(records[index..<(index + maxCount)]) } private func ensureCapacity() { switch capacity { case .unlimited: return case .records(let maximumRecordCount): records = Array(records.prefix(maximumRecordCount)) } } }
38.555556
104
0.668228
e86aa0b06a89915ac8cfacf4965b58d102d77d2e
4,091
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Internal magnetometer with 1-step calibration peripheral implementation public class MagnetometerWith1StepCalibrationCore: MagnetometerCore, MagnetometerWith1StepCalibration { /// State of the calibration process. private (set) public var calibrationProcessState: Magnetometer1StepCalibrationProcessState? /// implementation backend private unowned let backend: MagnetometerBackend public override init(store: ComponentStoreCore, backend: MagnetometerBackend) { self.backend = backend super.init(desc: Peripherals.magnetometerWith1StepCalibration, store: store, backend: backend) } public func startCalibrationProcess() { if calibrationProcessState == nil { calibrationProcessState = Magnetometer1StepCalibrationProcessState() backend.startCalibrationProcess() // notify the changes markChanged() notifyUpdated() } } public func cancelCalibrationProcess() { if calibrationProcessState != nil { backend.cancelCalibrationProcess() calibrationProcessState = nil // notify the changes markChanged() notifyUpdated() } } } /// Backend callback methods extension MagnetometerWith1StepCalibrationCore { /// Changes the current axes calibration progress. /// /// - Parameters: /// - rollProgress: the calibration progress on the roll axis (from 0 to 100) /// - pitchProgress: the calibration progress on the pitch axis (from 0 to 100) /// - yawProgress: the calibration progress on the yaw axis (from 0 to 100) /// - Returns: self to allow call chaining /// - Note: Changes are not notified until notifyUpdated() is called. @discardableResult public func update( rollProgress: Int, pitchProgress: Int, yawProgress: Int) -> MagnetometerWith1StepCalibrationCore { if let calibrationProcessState = calibrationProcessState, (calibrationProcessState.rollProgress != rollProgress || calibrationProcessState.pitchProgress != pitchProgress || calibrationProcessState.yawProgress != yawProgress) { calibrationProcessState.rollProgress = rollProgress calibrationProcessState.pitchProgress = pitchProgress calibrationProcessState.yawProgress = yawProgress markChanged() } return self } }
43.063158
106
0.704473
abad0d22f7c4209f9983a797bf50f0005d19202e
2,912
// // PencilChooseView.swift // testDemoSwift // // Created by 陈亮陈亮 on 2017/5/23. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit typealias clickPencilImageClouse = (UIImage) -> () class PencilChooseView: UIView { @objc var scrollView: UIScrollView! @objc var clickPencilImage: clickPencilImageClouse? @objc var currentImage: UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(white: 0, alpha: 0.8) scrollView = UIScrollView() scrollView?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height) scrollView.showsHorizontalScrollIndicator = false self.addSubview(scrollView!) let imageArr = ["clr_red","clr_orange","clr_blue","clr_green","clr_purple","clr_black"] let imgW: CGFloat = 20 let imgH: CGFloat = 20 let imgY: CGFloat = 0.5*(self.cl_height-imgH) let magin: CGFloat = (KScreenWidth-CGFloat(imageArr.count)*imgW)/CGFloat(imageArr.count+1) for i in 0..<imageArr.count { let imgX: CGFloat = magin + (magin+imgW)*CGFloat(i) let img = UIImageView.init(frame: CGRect(x: imgX, y: imgY, width: imgW, height: imgH)) img.image = UIImage(named: imageArr[i], in: BundleUtil.getCurrentBundle(), compatibleWith: nil) img.isUserInteractionEnabled = true CLViewsBorder(img, borderWidth: 1.5, borderColor: UIColor.white, cornerRadius: 3) scrollView.addSubview(img) img.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(PencilChooseView.clickPencilImageView(tap:)))) // 默认选中红色 if i == 0 { self.currentImage = img self.currentImage?.alpha = 0.5 CLViewsBorder(self.currentImage!, borderWidth: 0, borderColor: UIColor.white, cornerRadius: 3) } } scrollView.contentSize = CGSize(width: magin*CGFloat(imageArr.count+1)+imgW*CGFloat(imageArr.count)-KScreenWidth, height: 0) } @objc func clickPencilImageView(tap:UITapGestureRecognizer) { if clickPencilImage != nil { self.currentImage?.alpha = 1 CLViewsBorder(self.currentImage!, borderWidth: 1.5, borderColor: UIColor.white, cornerRadius: 3) let imageView = tap.view as! UIImageView imageView.alpha = 0.5 CLViewsBorder(imageView, borderWidth: 0, borderColor: UIColor.white, cornerRadius: 3) self.currentImage = imageView self.clickPencilImage!(imageView.image!) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
36.860759
143
0.615385
ac387de6eacf430b3bc698c624493d0f9e9f2561
505
// // AppDelegate.swift // Triangulation // // Created by Alex Littlejohn on 2016/01/08. // Copyright © 2016 zero. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
22.954545
144
0.728713
edabad7f313985854c72329c56fe2013bf0bd440
8,058
// // WebViewController.swift // Dagensvimmerby // // Created by Carlos Martin (SE) on 25/10/2016. // Copyright © 2016 TUVA Sweden AB. All rights reserved. // import UIKit import WebKit import Foundation import Parse class WebViewController: UIViewController { static let RELOAD_TIME_LIMIT: Double = 15 * 60 @IBOutlet weak var wkwvContainer: UIView! @IBOutlet weak var goBackButtonItem: UIBarButtonItem! @IBOutlet weak var goForwardButtonItem: UIBarButtonItem! @IBOutlet weak var reloadButtonItem: UIBarButtonItem! @IBOutlet weak var shareButtonItem: UIBarButtonItem! var wkWebView: WKWebView! var backgroundTimeStamp: TimeInterval = 0 @IBAction func goBackAction(_ sender: AnyObject) { if wkWebView.canGoBack { wkWebView.goBack() } } @IBAction func goForwardAction(_ sender: AnyObject) { if wkWebView.canGoForward { wkWebView.goForward() } } @IBAction func reloadAction(_ sender: AnyObject) { wkWebView.reload() } @IBAction func shareAction(_ sender: Any) { func shareURL (sharingUrl: String?) { var sharingItems = [AnyObject]() if let currentUrl = sharingUrl { sharingItems.append(currentUrl as AnyObject) } let vc = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil) vc.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem self.present(vc, animated: true, completion: nil) } if let url = self.wkWebView.url?.absoluteString { shareURL(sharingUrl: url) } } var url: URL? var url_name: String = Bundle.main.infoDictionary!["WEB_URL"] as! String var support_path: String = Bundle.main.infoDictionary!["SUPPORTER_PATH"] as! String //progress var @IBOutlet weak var progressView: UIProgressView! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) let config = WKWebViewConfiguration() config.allowsInlineMediaPlayback = true if #available(iOS 10.0, *) { config.mediaTypesRequiringUserActionForPlayback = .audio } else { // Fallback on earlier versions } wkWebView = WKWebView(frame: wkwvContainer.bounds, configuration: config) wkWebView.navigationDelegate = self wkWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight] wkwvContainer.addSubview(wkWebView) wkWebView.allowsBackForwardNavigationGestures = true wkWebView.uiDelegate = self wkWebView.navigationDelegate = self let webViewKeyPathsToObserve = ["loading", "estimatedProgress"] for keyPath in webViewKeyPathsToObserve { wkWebView.addObserver(self, forKeyPath: keyPath, options: .new, context: nil) } self.loadWebData() } deinit { NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) } @objc fileprivate func applicationDidEnterBackground() { backgroundTimeStamp = NSDate().timeIntervalSince1970 } @objc fileprivate func applicationDidBecomeActive() { if (backgroundTimeStamp > 0 && (backgroundTimeStamp+WebViewController.RELOAD_TIME_LIMIT) <= NSDate().timeIntervalSince1970) { self.loadWebData() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case "loading": goBackButtonItem.isEnabled = wkWebView.canGoBack goForwardButtonItem.isEnabled = wkWebView.canGoForward case "estimatedProgress": goBackButtonItem.isEnabled = wkWebView.canGoBack goForwardButtonItem.isEnabled = wkWebView.canGoForward progressView.isHidden = wkWebView.estimatedProgress == 1 progressView.progress = Float(wkWebView.estimatedProgress) default: break } } override func viewDidAppear(_ animated: Bool) { self.cleanBadge() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadWebData () { self.progressView.isHidden = true self.progressView.progress = 0.0 goBackButtonItem.isEnabled = false goForwardButtonItem.isEnabled = false if self.initWebData() { self.initWebView() } } func initWebData () -> Bool { let done: Bool if let _nurl = URL(string: self.url_name) { self.url = _nurl done = true } else { done = false } return done } func initWebView () { wkWebView.load(URLRequest(url: self.url!)) } func navigateSupporter() { if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "supporterVC") as? SupporterViewController { present(vc, animated: true, completion: nil) } } } extension WebViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { webView.load(navigationAction.request) } return nil } } extension WebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == WKNavigationType.linkActivated { if let url = navigationAction.request.url, let path = url.absoluteString.split(separator: "/").last, path.contains(support_path) { print(url) print("Open it in app!") navigateSupporter() decisionHandler(.cancel) } else { print("Open it locally") decisionHandler(.allow) } return } //print("no link") decisionHandler(.allow) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // show error dialog if error.localizedDescription == "A server with the specified hostname could not be found." { Alert.showFailiureAlert(message: "Sidan kunde inte hittas") } print(" >>>>>>> \(error.localizedDescription)") } } extension WebViewController { func cleanBadge() { UIApplication.shared.applicationIconBadgeNumber = 0 if let installation = PFInstallation.current() { installation.badge = 0 installation.saveInBackground() } } }
33.575
187
0.634897
6a10f79e962d585b6458d75eb0ad92d41747dc4a
2,420
// // ListViewController.swift // Memento // // Created by Pawel Kania on 28/01/2018. // Copyright © 2018 Pawel Kania. All rights reserved. // import UIKit import Shared // MARK: - ListTableCell class ListTableCell: UITableViewCell { // MARK: Outlets @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var latLngLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var accuracyLabel: UILabel! @IBOutlet weak var notuploadedImageView: UIImageView! } // MARK: ListViewController class ListViewController: UIViewController, StoryboardLoader, ViewTransmitter { // MARK: StoryboardLoader static var storyboardId = "ListViewController" // MARK: Outlets @IBOutlet weak var tableView: UITableView! // MARK: Properties var viewModel: ListViewModel? // MARK: View life cycle override func viewDidLoad() { super.viewDidLoad() viewModel?.viewDelegate = self } } // MARK: - UITableViewDataSource extension ListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.numberOfItems() ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as ListTableCell if let checkpointWrapper = viewModel?.checkpointWrapper(at: indexPath.row) { cell.numberLabel.text = checkpointWrapper.number cell.latLngLabel.text = checkpointWrapper.latLngString cell.dateLabel.text = checkpointWrapper.date cell.accuracyLabel.text = checkpointWrapper.accuracy if checkpointWrapper.forced == true { cell.accuracyLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 13, weight: .black) } else { cell.accuracyLabel.font = UIFont.systemFont(ofSize: 13) } cell.notuploadedImageView.isHidden = checkpointWrapper.uploaded cell.contentView.alpha = checkpointWrapper.highlight ? 1 : 0.5 } return cell } } // MARK: - MainViewModelDelegate extension ListViewController: ListViewModelDelegate { func setupView(viewModel: ListViewModel) { tableView.reloadData() } }
27.816092
102
0.671901
d678099e7b9da5a2c6c1bf932cab215adc5d22a7
981
// // SizeViewModifier.swift // SwiftUIPager // // Created by Fernando Moya de Rivas on 19/01/2020. // Copyright © 2020 Fernando Moya de Rivas. All rights reserved. // import SwiftUI /// This modifier wraps a view into a `GeometryReader` and tracks the available space by using `SizePreferenceKey` on the content struct SizeViewModifier: ViewModifier { @Binding var size: CGSize func body(content: Content) -> some View { GeometryReader { proxy in content .frame(width: proxy.size.width, height: proxy.size.height) .onAppear (perform: { self.size = proxy.size }) } .clipped() } } extension View { /// Tracks the size available for the view /// /// - Parameter size: This binding will receive the size updates func sizeTrackable(_ size: Binding<CGSize>) -> some View { self.modifier(SizeViewModifier(size: size)) } }
25.815789
129
0.616718
d6f8327b0d8daf85fbbce9afe036af05948c45ed
2,830
// // DashboardRouter.swift // Rivi Demo // // Created by Amol Prakash on 28/01/20. // Copyright © 2020 Amol Prakash. All rights reserved. // import Foundation import UIKit var mainStoryboard: UIStoryboard { return UIStoryboard(name: "Main", bundle: Bundle.main) } class DashboardRouter: DashboardRouterProtocol { static func createFoodDashboardModule() -> UIViewController { let navController = mainStoryboard.instantiateViewController(withIdentifier: "DashboardNavigationViewController") if let view = navController.children.first as? DashboardViewController { let presenter: DashboardPresenterProtocol & DashboardInteractorOutputProtocol = DashboardPresenter() let interactor: DashboardInteractorInputProtocol & DashboardFetcherOutputProtocol = DashboardInteractor() let remoteDataFetcher: DashboardFetcherInputProtocol = DashboardFetcher() let router: DashboardRouterProtocol = DashboardRouter() view.presenter = presenter presenter.view = view presenter.router = router presenter.interactor = interactor interactor.presenter = presenter interactor.fetcher = remoteDataFetcher remoteDataFetcher.interactor = interactor return navController } return UIViewController() } static func createFoodDetailModule(withIndex selectedIndex: Int, foodDetail: FoodDataViewModel) -> UIViewController { if let view = mainStoryboard.instantiateViewController(withIdentifier: "FoodDetailsViewController") as? FoodDetailsViewController { let presenter: FoodDetailsPresenterProtocol = FoodDetailsPresenter(foodData: foodDetail, currentSelectedIndex: selectedIndex) view.presenter = presenter presenter.view = view return view } return FoodDetailsViewController() } func presentFoodDetailScreen(from view: DashboardViewProtocol?, forIndex selectedIndex: Int, andDetail foodDetail: FoodDataViewModel) { let detailVc = type(of: self).createFoodDetailModule(withIndex: selectedIndex, foodDetail: foodDetail) if let view = view as? UIViewController { // the issue by using a UITableViewCell which had its selectionStyle set to UITableViewCellSelectionStyleNone, so that no selection animation triggered the runloop after the row selection handler ran. To fix it, you can trigger the main runloop by several means: // https://stackoverflow.com/questions/21075540/presentviewcontrolleranimatedyes-view-will-not-appear-until-user-taps-again DispatchQueue.main.async { view.navigationController?.present(detailVc, animated: true, completion: nil) } } } }
47.966102
274
0.713781
21d876a968abbe0a295a0e2748e08d57cdf80e36
749
// // WorkerTableViewCell.swift // Tipsease // // Created by Marlon Raskin on 6/24/19. // Copyright © 2019 Marlon Raskin. All rights reserved. // import UIKit class WorkerTableViewCell: UITableViewCell { @IBOutlet var workerNameLabel: UILabel! @IBOutlet var positionLabel: UILabel! @IBOutlet var ratingLabel: UILabel! @IBOutlet var imagePlaceholder: UIImageView! var worker: Worker? { didSet { // updateViews() } } override func awakeFromNib() { super.awakeFromNib() imagePlaceholder.layer.cornerRadius = 12 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
17.833333
65
0.686248
e0da2023737cbfa5928341017a2b266b326c5c27
1,658
// // NSOutlineView+Snapshot.swift // OutlineViewDiffableDataSource // // Created by Steve Sparks on 2/8/20. // Copyright © 2020 Big Nerd Ranch. All rights reserved. // import Cocoa // Turn a diff into commands extension NSOutlineView { func apply(_ snapshot: OutlineViewSnapshotDiff, with animation: NSTableView.AnimationOptions = [.effectFade]) { beginUpdates() snapshot.forEach { instr in switch instr { case .insert(_, let indexPath): let parent = lastParent(for: indexPath) if let childIndex = indexPath.last { insertItems(at: [childIndex], inParent: parent, withAnimation: animation) } case .move(let src, let dst): let srcParent = lastParent(for: src) let dstParent = lastParent(for: dst) if let srcChild = src.last, let dstChild = dst.last { moveItem(at: srcChild, inParent: srcParent, to: dstChild, inParent: dstParent) } case .remove(_, let indexPath): let parent = lastParent(for: indexPath) if let childIndex = indexPath.last { removeItems(at: [childIndex], inParent: parent, withAnimation: animation) } } } endUpdates() } func lastParent(for indexPath: IndexPath) -> Any? { var parent: Any? var ip = indexPath ip.removeLast() for index in ip { if let g = child(index, ofItem: parent) { parent = g } } return parent } }
31.283019
115
0.552473
39b17eebcb2de95340deb66eca498bfba165cf44
10,154
// // MLXrClientSession.swift // RNMagicScript // // Created by Pawel Leszkiewicz on 17/07/2019. // Copyright © 2019 MagicLeap. All rights reserved. // import Foundation import ARKit import CoreLocation import MLXR @objc public class XrClientSession: NSObject { @objc public static let instance = XrClientSession() static fileprivate let locationManager = CLLocationManager() fileprivate weak var arSession: ARSession? fileprivate let mlxrSession = MLXRSession() fileprivate let xrQueue = DispatchQueue(label: "xrQueue") fileprivate var lastLocation: CLLocation? fileprivate var trackingState: ARCamera.TrackingState? public override init() { super.init() setupLocationManager() } deinit { // NOTE: Due to the following warning: // "Failure to deallocate CLLocationManager on the same runloop as its creation // may result in a crash" // locationManager is a static member and we only stop updating location in deinit. XrClientSession.locationManager.stopUpdatingLocation() XrClientSession.locationManager.delegate = nil } fileprivate func setupLocationManager() { XrClientSession.locationManager.delegate = self XrClientSession.locationManager.desiredAccuracy = kCLLocationAccuracyBest XrClientSession.locationManager.requestWhenInUseAuthorization() XrClientSession.locationManager.startUpdatingLocation() } private func findArSession(view: UIView) -> ARSession? { if let arSceneView = view as? ARSCNView { return arSceneView.session } for subview in view.subviews { if let arSession = findArSession(view: subview) { return arSession } } return nil } private func findArSession() -> ARSession? { var arSession: ARSession? = nil DispatchQueue.main.sync { let viewController = UIApplication.shared.keyWindow!.rootViewController if let view = viewController?.view { arSession = findArSession(view: view) } } return arSession } private func waitForArSession() -> ARSession? { for _ in 1...30 { guard let arSession = findArSession() else { // Sleep for 200ms usleep(200 * 1000) continue; } return arSession } return nil } @objc public func connect(_ token: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { [weak self] in guard let self = self else { reject("code", "XrClientSession does not exist", nil) return } guard let arSession = self.waitForArSession() else { reject("code", "ARSession does not exist", nil) return } self.arSession = arSession if (self.mlxrSession.start(token)) { if (arSession.delegate == nil) { let worldOriginAnchor = ARAnchor(name: "WorldAnchor", transform: matrix_identity_float4x4) arSession.add(anchor: worldOriginAnchor) arSession.delegate = self; } let status: XrClientSessionStatus = XrClientSessionStatus(sessionStatus: self.mlxrSession.getStatus()?.status ?? MLXRSessionStatus_Disconnected) resolve(true) } else { reject("code", "XrClientSession could not be initialized!", nil) } } } @objc public func stop(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { [weak self] in guard let self = self else { reject("code", "XrClientSession does not exist", nil) return } self.mlxrSession.stop() resolve(true) } } fileprivate func update() { guard let currentLocation = lastLocation else { print("current location is not available") return } guard let frame = self.arSession?.currentFrame else { print("no ar frame available") return } if let previuosTrackingState = trackingState, let currentTrackingState = self.arSession?.currentFrame?.camera.trackingState, previuosTrackingState != currentTrackingState { print("TrackingState: ", currentTrackingState.description); } trackingState = self.arSession?.currentFrame?.camera.trackingState _ = mlxrSession.update(frame, currentLocation) } @objc public func getAllPCFs(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { [weak self] in guard let xrSession = self?.mlxrSession else { reject("code", "XrClientSession has not been initialized!", nil) return } let results: [[String: Any]] = xrSession.getAllAnchors().map { XrClientAnchorData($0) }.map { $0.getJsonRepresentation() } resolve(results) } } @objc public func getSessionStatus(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { [weak self] in guard let self = self else { reject("code", "XrClientSession does not exist", nil) return } let status: XrClientSessionStatus = XrClientSessionStatus(sessionStatus: self.mlxrSession.getStatus()?.status ?? MLXRSessionStatus_Disconnected) resolve(status.rawValue) } } @objc public func getLocalizationStatus(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { [weak self] in guard let self = self else { reject("code", "XrClientSession does not exist", nil) return } let status: XrClientLocalization = XrClientLocalization(localizationStatus: self.mlxrSession.getLocalizationStatus()?.status ?? MLXRLocalizationStatus_LocalizationFailed) resolve(status.rawValue) } } @objc static func requiresMainQueueSetup() -> Bool { return true } @objc public func createAnchor(_ anchorId: String, position: NSArray, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { guard let arSession = self.arSession else { reject("code", "ARSession has not been initialized!", nil) return } var transform: simd_float4x4? if let position = position as? [NSNumber] { transform = XrClientAnchorData.mat4FromColumnMajorFlatArray(position.map{$0.floatValue}) } else if let position = position as? [Float] { transform = XrClientAnchorData.mat4FromColumnMajorFlatArray(position) } if let transform = transform { arSession.add(anchor: ARAnchor(name: anchorId, transform: transform)) resolve(true) } else { reject("code", "position should be a array of 16 float elements", nil) } } } @objc public func removeAnchor(_ anchorId: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { if let anchors = self.arSession?.currentFrame?.anchors { for anchor in anchors { if let name = anchor.name, name == anchorId { self.arSession?.remove(anchor: anchor) } } } resolve(true) } } @objc public func removeAllAnchors(_ resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { xrQueue.async { if let anchors = self.arSession?.currentFrame?.anchors { for anchor in anchors { self.arSession?.remove(anchor: anchor) } } resolve(true) } } } // CLLocationManagerDelegate extension XrClientSession: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { xrQueue.async { [weak self] in if let self = self { self.lastLocation = locations.last } } } } extension XrClientSession: ARSessionDelegate { public func session(_ session: ARSession, didUpdate frame: ARFrame) { self.update(); } } extension ARCamera.TrackingState { var description: String { switch self { case .notAvailable: return "UNAVAILABLE" case .normal: return "NORMAL" case .limited(let reason): switch reason { case .excessiveMotion: return "LIMITED: Too much camera movement" case .insufficientFeatures: return "LIMITED: Not enough surface detail" case .initializing: return "LIMITED: Initializing" case .relocalizing: return "LIMITED: Relocalizing" @unknown default: return "LIMITED: Unknown reason" } } } static func == (left: ARCamera.TrackingState, right: ARCamera.TrackingState) -> Bool { switch (left, right) { case (.notAvailable, .notAvailable): return true case (.normal, .normal): return true case let (.limited(a), .limited(b)): return a == b default: return false } } static func != (left: ARCamera.TrackingState, right: ARCamera.TrackingState) -> Bool { return !(left == right) } }
34.304054
182
0.597695
c13af6ca4536a430fd829e672d0f6f1c8ac8f937
56,831
// // SBATrackedDataObjectTests.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest import ResearchKit import ResearchUXFactory class SBATrackedDataObjectTests: ResourceTestCase { 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 testMedicationArchiveAndUnarchive() { // Create a medication let duopa = SBAMedication(dictionaryRepresentation: [ "identifier" : "Duopa", "name" : "Carbidopa/Levodopa", "detail" : "Continuous Infusion", "brand" : "Duopa", "tracking" : true, "injection" : true, ]) // Modify the frequency duopa.frequency = 4; // Archive let data = NSKeyedArchiver.archivedData(withRootObject: [duopa]); // Unarchive it and check the result guard let arr = NSKeyedUnarchiver.unarchiveObject(with: data) as? [SBAMedication], let med = arr.first else { XCTAssert(false, "Value did not unarchive as array") return } XCTAssertEqual(duopa.identifier, med.identifier) XCTAssertEqual(duopa.name, med.name) XCTAssertEqual(duopa.brand, med.brand) XCTAssertEqual(duopa.detail, med.detail) XCTAssertEqual(duopa.frequency, med.frequency) XCTAssertTrue(duopa.tracking) XCTAssertTrue(duopa.injection) } func testMedicationTrackerFromResourceFile() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } XCTAssertEqual(dataCollection.taskIdentifier, "Medication Task") XCTAssertEqual(dataCollection.schemaIdentifier, "Medication Tracker") } func testMedicationTrackerFromResourceFile_Items() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } XCTAssertEqual(dataCollection.itemsClassType, "Medication") let expectedCount = 15 XCTAssertEqual(dataCollection.items.count, expectedCount); if (dataCollection.items.count != expectedCount) { return } let meds = dataCollection.items; guard let levodopa = meds?[0] as? SBAMedication, let carbidopa = meds?[1] as? SBAMedication, let rytary = meds?[2] as? SBAMedication, let duopa = meds?.last as? SBAMedication else { XCTAssert(false, "items not of expected type \(meds)") return } XCTAssertEqual(levodopa.identifier, "Levodopa"); XCTAssertEqual(levodopa.name, "Levodopa"); XCTAssertEqual(levodopa.text, "Levodopa"); XCTAssertEqual(levodopa.shortText, "Levodopa"); XCTAssertTrue(levodopa.tracking); XCTAssertFalse(levodopa.injection); XCTAssertEqual(carbidopa.identifier, "Carbidopa"); XCTAssertEqual(carbidopa.name, "Carbidopa"); XCTAssertEqual(carbidopa.text, "Carbidopa"); XCTAssertEqual(carbidopa.shortText, "Carbidopa"); XCTAssertFalse(carbidopa.tracking); XCTAssertFalse(carbidopa.injection); XCTAssertEqual(rytary.identifier, "Rytary"); XCTAssertEqual(rytary.name, "Carbidopa/Levodopa"); XCTAssertEqual(rytary.brand, "Rytary"); XCTAssertEqual(rytary.text, "Carbidopa/Levodopa (Rytary)"); XCTAssertEqual(rytary.shortText, "Rytary"); XCTAssertTrue(rytary.tracking); XCTAssertFalse(rytary.injection); XCTAssertEqual(duopa.identifier, "Duopa"); XCTAssertEqual(duopa.name, "Carbidopa/Levodopa"); XCTAssertEqual(duopa.brand, "Duopa"); XCTAssertEqual(duopa.detail, "Continuous Infusion"); XCTAssertEqual(duopa.text, "Carbidopa/Levodopa Continuous Infusion (Duopa)"); XCTAssertEqual(duopa.shortText, "Duopa"); XCTAssertFalse(duopa.tracking); XCTAssertTrue(duopa.injection); } func testMedicationTrackerFromResourceFile_Steps_StandAloneSurvey() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let include = SBATrackingStepIncludes.StandAloneSurvey let steps = dataCollection.filteredSteps(include) checkStandAloneSurveySteps(steps, dataCollection: dataCollection) } func checkStandAloneSurveySteps(_ steps: [ORKStep], dataCollection: SBATrackedDataObjectCollection) { let expectedCount = 4 XCTAssertEqual(steps.count, expectedCount) guard steps.count == expectedCount else { return } // Step 1 guard let introStep = steps[0] as? ORKInstructionStep else { XCTAssert(false, "\(steps[0]) not of expected type") return } XCTAssertEqual(introStep.identifier, "medicationIntroduction") XCTAssertEqual(introStep.title, "Diagnosis and Medication") XCTAssertEqual(introStep.text, "We want to understand how certain medications affect the app activities. To do that we need more information from all study participants.\n\nPlease tell us if you have PD and if you take medications from the proposed list. We’ll ask you again from time to time to track any changes.\n\nThis survey should take about 5 minutes.") let selectionPageStep = steps[1] let (selectionStep, frequencyStep) = splitMedicationSelectionStep(selectionPageStep) checkMedicationSelectionStep(selectionStep, optional: false) checkMedicationFrequencyStep(frequencyStep, idList: [], expectedFrequencyIds: [], items: dataCollection.items) checkMedicationFrequencyStep(frequencyStep, idList: ["Levodopa", "Carbex", "Duopa"], expectedFrequencyIds: ["Levodopa", "Carbex"], items: dataCollection.items) checkMedicationFrequencyStep(frequencyStep, idList: ["Duopa"], expectedFrequencyIds: [], items: dataCollection.items) guard let handStep = steps[2] as? ORKFormStep else { XCTAssert(false, "\(steps[2]) not of expected type") return } XCTAssertEqual(handStep.identifier, "dominantHand") XCTAssertEqual(handStep.text, "Which hand would you normally use to write or throw a ball?") guard let conclusionStep = steps.last as? ORKInstructionStep else { XCTAssert(false, "\(steps.last) not of expected type") return } XCTAssertEqual(conclusionStep.identifier, "medicationConclusion") XCTAssertEqual(conclusionStep.title, "Thank You!") XCTAssertNil(conclusionStep.text) } func testMedicationSelectionStep_Optional() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let inputItem: NSDictionary = [ "identifier" : "medicationSelection", "trackingType" : "selection", "type" : "trackingSelection", "text" : "Do you take any of these medications?\n(Please select all that apply)", "optional" : true, ] let step = SBABaseSurveyFactory().createSurveyStep(inputItem, trackingType: .selection, trackedItems: dataCollection.items) let (selectionStep, _) = splitMedicationSelectionStep(step) checkMedicationSelectionStep(selectionStep, optional: true) } func splitMedicationSelectionStep(_ step: ORKStep?) -> (selection:ORKStep?, frequency:ORKStep?) { guard let selectionStep = step as? SBATrackedSelectionStep else { XCTAssert(false, "\(step) not of expected type") return (nil, nil) } return (selectionStep.steps.first, selectionStep.steps.last) } func checkMedicationSelectionStep(_ step: ORKStep?, optional: Bool) { guard let selectionStep = step as? ORKFormStep else { XCTAssert(false, "\(step) not of expected type") return } XCTAssertEqual(selectionStep.identifier, "medicationSelection") XCTAssertEqual(selectionStep.text, "Do you take any of these medications?\n(Please select all that apply)") let selectionFormItem = selectionStep.formItems?.first XCTAssertNotNil(selectionFormItem) guard let answerFormat = selectionFormItem?.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(selectionFormItem?.answerFormat) not of expected type") return } XCTAssertEqual(selectionStep.identifier, "medicationSelection") XCTAssertFalse(selectionStep.isOptional) XCTAssertEqual(selectionStep.formItems?.count, 1) XCTAssertEqual(answerFormat.style, ORKChoiceAnswerStyle.multipleChoice) var expectedChoices = [ ["Levodopa", "Levodopa"], ["Carbidopa", "Carbidopa"], ["Carbidopa/Levodopa (Rytary)", "Rytary"], ["Carbidopa/Levodopa (Sinemet)", "Sinemet"], ["Carbidopa/Levodopa (Atamet)", "Atamet"], ["Carbidopa/Levodopa/Entacapone (Stalevo)","Stalevo"], ["Amantadine (Symmetrel)", "Symmetrel"], ["Rotigotine (Neupro)", "Neupro"], ["Selegiline (Eldepryl)", "Eldepryl"], ["Selegiline (Carbex)", "Carbex"], ["Selegiline (Atapryl)", "Atapryl"], ["Pramipexole (Mirapex)", "Mirapex"], ["Ropinirole (Requip)", "Requip"], ["Apomorphine (Apokyn)", "Apokyn"], ["Carbidopa/Levodopa Continuous Infusion (Duopa)", "Duopa"], ["None of the above", "None"]]; if (optional) { expectedChoices += [["Prefer not to answer", "Skipped"]]; } XCTAssertEqual(answerFormat.textChoices.count, expectedChoices.count) if answerFormat.textChoices.count <= expectedChoices.count { for (idx, textChoice) in answerFormat.textChoices.enumerated() { XCTAssertEqual(textChoice.text, expectedChoices[idx].first!) if let value = textChoice.value as? String { XCTAssertEqual(value, expectedChoices[idx].last!) } else { XCTAssert(false, "\(textChoice.value) not expected type") } let exclusive = optional ? (idx >= expectedChoices.count - 2) : (idx == expectedChoices.count - 1); XCTAssertEqual(textChoice.exclusive, exclusive); } } } func checkMedicationFrequencyStep(_ step: ORKStep?, idList:[String], expectedFrequencyIds: [String], items:[SBATrackedDataObject]) { guard let trackNav = step as? SBATrackedNavigationStep, let formStep = step as? ORKFormStep else { XCTAssert(false, "\(step) not of expected type") return } XCTAssertEqual(formStep.identifier, "medicationFrequency") XCTAssertEqual(formStep.text, "How many times a day do you take each of the following medications?") let selectedItems = items.filter({ idList.contains($0.identifier) }) trackNav.update(selectedItems: selectedItems) XCTAssertEqual(formStep.formItems?.count, expectedFrequencyIds.count) XCTAssertEqual(trackNav.shouldSkipStep, expectedFrequencyIds.count == 0) for identifier in idList { guard let item = items.find(withIdentifier: identifier) else { XCTAssert(false, "Couldn't find item \(identifier)") return } let formItem = formStep.formItems?.find(withIdentifier: identifier) if (expectedFrequencyIds.contains(item.identifier)) { XCTAssertNotNil(formItem, "\(identifier)") XCTAssertEqual(formItem?.text, item.text) if let answerFormat = formItem?.answerFormat as? ORKScaleAnswerFormat { XCTAssertEqual(answerFormat.minimum, 1) XCTAssertEqual(answerFormat.maximum, 12) XCTAssertEqual(answerFormat.step, 1) } else { XCTAssert(false, "\(formItem?.answerFormat) not expected type for \(identifier)") } } else { XCTAssertNil(formItem, "\(identifier)") } } } func testMedicationTrackerFromResourceFile_Steps_ActivityOnly() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let include = SBATrackingStepIncludes.ActivityOnly let steps = dataCollection.filteredSteps(include) checkActivityOnlySteps(steps, dataCollection: dataCollection) } func checkActivityOnlySteps(_ steps: [ORKStep], dataCollection: SBATrackedDataObjectCollection) { let expectedCount = 3 XCTAssertEqual(steps.count, expectedCount) guard steps.count == expectedCount else { return } guard let momentInDayStep = steps.first as? SBATrackedActivityFormStep, let formItem = momentInDayStep.formItems?.first, let answerFormat = formItem.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(steps.first) not of expected type") return } XCTAssertEqual(momentInDayStep.identifier, "momentInDay") XCTAssertFalse(momentInDayStep.isOptional) XCTAssertEqual(momentInDayStep.formItems?.count, 1) XCTAssertEqual(momentInDayStep.text, "We would like to understand how your performance on this activity could be affected by the timing of your medication.") XCTAssertEqual(formItem.identifier, "momentInDayFormat") XCTAssertEqual(formItem.text, "When are you performing this activity?") XCTAssertEqual(answerFormat.textChoices.count, 3) XCTAssertEqual(answerFormat.style, ORKChoiceAnswerStyle.singleChoice) checkMedicationActivityStep(momentInDayStep, idList: ["Levodopa", "Carbidopa", "Rytary"], expectedSkipped: false, items: dataCollection.items) checkMedicationActivityStep(momentInDayStep, idList: ["Carbidopa"], expectedSkipped: true, items: dataCollection.items) guard let timingStep = steps[1] as? SBATrackedActivityFormStep, let timingFormItem = timingStep.formItems?.first, let timingAnswerFormat = timingFormItem.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(steps[1]) not of expected type") return } XCTAssertEqual(timingStep.identifier, "medicationActivityTiming") XCTAssertFalse(timingStep.isOptional) XCTAssertEqual(timingStep.formItems?.count, 1) XCTAssertEqual(timingFormItem.identifier, "medicationActivityTiming") // Look at the answer format XCTAssertEqual(timingAnswerFormat.style, ORKChoiceAnswerStyle.singleChoice) let expectedTimeChoices = [ "0-30 minutes ago", "30-60 minutes ago", "1-2 hours ago", "2-4 hours ago", "4-8 hours ago", "More than 8 hours ago", "Not sure"] XCTAssertEqual(timingAnswerFormat.textChoices.count, expectedTimeChoices.count) for (idx, textChoice) in timingAnswerFormat.textChoices.enumerated() { if (idx < expectedTimeChoices.count) { XCTAssertEqual(textChoice.text, expectedTimeChoices[idx]) if let value = textChoice.value as? String { XCTAssertEqual(value, expectedTimeChoices[idx]) } else { XCTAssert(false, "\(textChoice.value) not of expected type") } } } // Check the text formatting checkMedicationActivityStep(timingStep, idList: ["Levodopa", "Carbidopa", "Rytary"], expectedSkipped: false, items: dataCollection.items) XCTAssertEqual(timingStep.text, "When was the last time you took your Levodopa or Rytary?") checkMedicationActivityStep(timingStep, idList: ["Carbidopa"], expectedSkipped: true, items: dataCollection.items) checkMedicationActivityStep(timingStep, idList: ["Levodopa", "Rytary", "Sinemet"], expectedSkipped: false, items: dataCollection.items) XCTAssertEqual(timingStep.text, "When was the last time you took your Levodopa, Rytary, or Sinemet?") checkMedicationActivityStep(timingStep, idList: ["Levodopa", "Rytary", "Sinemet", "Atamet"], expectedSkipped: false, items: dataCollection.items) XCTAssertEqual(timingStep.text, "When was the last time you took your Levodopa, Rytary, Sinemet, or Atamet?") } func checkMedicationActivityStep(_ step: SBATrackedNavigationStep, idList:[String], expectedSkipped: Bool, items:[SBATrackedDataObject]) { let selectedItems = items.filter({ idList.contains($0.identifier) }) step.update(selectedItems: selectedItems) XCTAssertEqual(step.shouldSkipStep, expectedSkipped, "\(idList)") } func testMedicationTrackerFromResourceFile_Steps_ChangedAndActivity() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let include = SBATrackingStepIncludes.ChangedAndActivity let steps = dataCollection.filteredSteps(include) checkChangedAndActivitySteps(steps, expectedSkipIdentifier: "momentInDay", dataCollection: dataCollection) } func checkDefaultMomentInDayResults(_ dataStore: SBATrackedDataStore) -> Bool { guard let momentInDayResults = dataStore.momentInDayResults, momentInDayResults.count == 3 else { XCTAssert(false, "\(dataStore.momentInDayResults) nil or not expected count") return false } // Moment in day should have let result1 = momentInDayResults[0] XCTAssertEqual(result1.identifier, "momentInDay") XCTAssertNotNil(result1.results) XCTAssertEqual(result1.results!.count, 1) let questionResult1 = result1.results!.first! as! ORKChoiceQuestionResult XCTAssertEqual(questionResult1.identifier, "momentInDayFormat") XCTAssertEqual(questionResult1.choiceAnswers as! [String], ["No Tracked Data"]) // let result2 = momentInDayResults[1] XCTAssertEqual(result2.identifier, "medicationActivityTiming") XCTAssertNotNil(result2.results) XCTAssertEqual(result2.results!.count, 1) let questionResult2 = result2.results!.first! as! ORKChoiceQuestionResult XCTAssertEqual(questionResult2.identifier, "medicationActivityTiming") XCTAssertEqual(questionResult2.choiceAnswers as! [String], ["No Tracked Data"]) let result3 = momentInDayResults[2] XCTAssertEqual(result3.identifier, "medicationTrackEach") XCTAssertNotNil(result3.results) XCTAssertEqual(result3.results!.count, 1) let questionResult3 = result3.results!.first! as! ORKChoiceQuestionResult XCTAssertEqual(questionResult3.identifier, "medicationTrackEach") XCTAssertEqual(questionResult3.choiceAnswers as! [String], [] as [String]) return true } func checkChangedAndActivitySteps(_ steps: [ORKStep], expectedSkipIdentifier: String, dataCollection: SBATrackedDataObjectCollection) { let expectedCount = 6 XCTAssertEqual(steps.count, expectedCount) guard steps.count == expectedCount else { return } guard let changedStep = steps.first as? SBANavigationFormStep, let formItem = changedStep.formItems?.first, let _ = formItem.answerFormat as? ORKBooleanAnswerFormat else { XCTAssert(false, "\(steps.first) not of expected type") return } XCTAssertEqual(changedStep.identifier, "medicationChanged") XCTAssertEqual(changedStep.text, "Has your medication changed?") guard let navigationRule = changedStep.rules?.first?.rulePredicate else { return } // Check navigation let questionResult = ORKBooleanQuestionResult(identifier:formItem.identifier) questionResult.booleanAnswer = false XCTAssertTrue(navigationRule.evaluate(with: questionResult)) let taskResult = ORKTaskResult(identifier: "task") taskResult.results = [ORKStepResult(stepIdentifier: "medicationChanged", results: [questionResult])] let nextIdentifier = changedStep.nextStepIdentifier(with:taskResult, and: nil) XCTAssertEqual(nextIdentifier, expectedSkipIdentifier) questionResult.booleanAnswer = true XCTAssertFalse(navigationRule.evaluate(with: questionResult)) taskResult.results = [ORKStepResult(stepIdentifier: "medicationChanged", results: [questionResult])] let failedIdentifier = changedStep.nextStepIdentifier(with:taskResult, and: nil) XCTAssertNil(failedIdentifier) let selectionStep = steps[1] XCTAssertEqual(selectionStep.identifier, "medicationSelection") let handStep = steps[2] XCTAssertEqual(handStep.identifier, "dominantHand") let momentInDayStep = steps[3] XCTAssertEqual(momentInDayStep.identifier, "momentInDay") let timingStep = steps[4] XCTAssertEqual(timingStep.identifier, "medicationActivityTiming") let trackEachStep = steps[5] XCTAssertEqual(trackEachStep.identifier, "medicationTrackEach") } func testMedicationTrackerFromResourceFile_Steps_ChangedAndNoMedsPreviouslySelected() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let include = SBATrackingStepIncludes.ChangedOnly let steps = dataCollection.filteredSteps(include) checkChangedAndActivitySteps(steps, expectedSkipIdentifier: "nextSection", dataCollection: dataCollection) } func testMedicationTrackerFromResourceFile_Steps_SurveyAndActivity() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let include = SBATrackingStepIncludes.SurveyAndActivity let steps = dataCollection.filteredSteps(include) checkSurveyAndActivitySteps(steps, dataCollection: dataCollection) } func checkSurveyAndActivitySteps(_ steps: [ORKStep], dataCollection: SBATrackedDataObjectCollection) { let expectedCount = 6 XCTAssertEqual(steps.count, expectedCount) guard steps.count == expectedCount else { return } let stepIntro = steps[0] XCTAssertEqual(stepIntro.identifier, "medicationIntroduction") let selectionStep = steps[1] XCTAssertEqual(selectionStep.identifier, "medicationSelection") let handStep = steps[2] XCTAssertEqual(handStep.identifier, "dominantHand") let momentInDayStep = steps[3] XCTAssertEqual(momentInDayStep.identifier, "momentInDay") let timingStep = steps[4] XCTAssertEqual(timingStep.identifier, "medicationActivityTiming") let trackEachStep = steps[5] XCTAssertEqual(trackEachStep.identifier, "medicationTrackEach") } // MARK: transformToStep tests func testTransformToStep_StandAlone() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: true) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } checkStandAloneSurveySteps(task.steps, dataCollection: dataCollection) } func testTransformToStep_EmptySet_LastSurveyToday() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // If the selected items set is empty (but there is one) then do not show the activity steps dataStore.selectedItems = [] dataStore.commitChanges() let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) // The moment in day results should have default values XCTAssert(checkDefaultMomentInDayResults(dataStore)) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } // Task should be empty XCTAssertEqual(task.steps.count, 0) } func testTransformToStep_InjectionOnlySet_LastSurveyToday() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // If the selected items set does not include any that are tracked then should // return the empty set (for a date in the near past) dataStore.selectedItems = dataCollection.items.filter({ !$0.usesFrequencyRange }) dataStore.commitChanges() let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) // The moment in day results should have default values XCTAssert(checkDefaultMomentInDayResults(dataStore)) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } // Task should be empty XCTAssertEqual(task.steps.count, 0) } func testTransformToStep_ActivityOnly() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // If the activity steps includes a tracked item, then should include the activty // steps, but do not need to include any of the others dataStore.selectedItems = dataCollection.items.filter({ $0.identifier == "Levodopa" }) dataStore.commitChanges() dataStore.lastTrackingSurveyDate = Date() let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } checkActivityOnlySteps(task.steps, dataCollection: dataCollection) } func testTransformToStep_ChangedAndActivity_CurrentlyHasTracked() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // If the activity steps includes a tracked item and the last survey was more than // 30 days ago then should ask about changes dataStore.selectedItems = dataCollection.items.filter({ $0.identifier == "Levodopa" }) dataStore.commitChanges() dataStore.lastTrackingSurveyDate = Date(timeIntervalSinceNow: -40*24*60*60) let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) // The moment in day results should have steps for creating default results XCTAssertNil(dataStore.momentInDayResults) XCTAssertNotNil(dataStore.momentInDaySteps) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } checkChangedAndActivitySteps(task.steps, expectedSkipIdentifier: "momentInDay", dataCollection: dataCollection) } func testTransformToStep_ChangedAndActivity_NoMedsCurrentlyTracked() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // If the activity steps includes a tracked item and the last survey was more than // 30 days ago then should ask about changes dataStore.selectedItems = [] dataStore.commitChanges() dataStore.lastTrackingSurveyDate = Date(timeIntervalSinceNow: -40*24*60*60) let step = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) // The moment in day results should have default values XCTAssert(checkDefaultMomentInDayResults(dataStore)) guard let taskStep = step as? SBASubtaskStep, let task = taskStep.subtask as? SBANavigableOrderedTask else { XCTAssert(false, "\(step) not of expected class type") return } checkChangedAndActivitySteps(task.steps, expectedSkipIdentifier: "nextSection", dataCollection: dataCollection) } // Mark: Navigation tests func testNavigation_NoMedsSelected() { let (retTask, retDataStore, step, retTaskResult) = stepToActivity(["None"]) guard let task = retTask, let dataStore = retDataStore, let taskResult = retTaskResult, let selectedItems = dataStore.selectedItems else { XCTAssert(false, "preconditions not met") return } // Check that there are no selected items XCTAssertEqual(selectedItems.count, 0) // And the default moment in day results are given XCTAssert(checkDefaultMomentInDayResults(dataStore)) // Tracked steps should not be shown let nextStep = task.step(after: step, with: taskResult) XCTAssertNil(nextStep) } func testNavigation_WithMedsSelected() { // Check shared functionality let (retTask, retDataStore, step, retTaskResult) = stepToActivity(["Levodopa", "Carbidopa", "Rytary", "Apokyn"]) guard let task = retTask, let dataStore = retDataStore, let taskResult = retTaskResult, let selectedItems = dataStore.selectedItems else { XCTAssert(false, "preconditions not met") return } // check that the selected items is set in the data store XCTAssertEqual(selectedItems.count, 4) // get the next step let step1 = task.step(after: step, with: taskResult) XCTAssertNotNil(step1) // Get moment in day guard let momentStep = step1 as? SBATrackedActivityFormStep , momentStep.trackingType == .activity, let momentFormItem = momentStep.formItems?.first else { XCTAssert(false, "\(step1) not of expected type") return } XCTAssertEqual(momentStep.identifier, "momentInDay") XCTAssertEqual(momentFormItem.identifier, "momentInDayFormat") XCTAssertEqual(momentStep.formItems!.count, 1) // Add the moment in day result let momentResult = momentStep.instantiateDefaultStepResult([momentFormItem.identifier : "Another time"]) taskResult.results?.append(momentResult) // Get next step let step2 = task.step(after: step1, with: taskResult) XCTAssertNotNil(step2) guard let timingStep = step2 as? SBATrackedActivityFormStep, timingStep.trackingType == .activity, let timingFormItem = timingStep.formItems?.first else { XCTAssert(false, "\(step2) not of expected type") return } XCTAssertEqual(timingStep.identifier, "medicationActivityTiming") XCTAssertEqual(timingFormItem.identifier, "medicationActivityTiming") XCTAssertEqual(timingStep.formItems!.count, 1) // Add timing result let timingResult = timingStep.instantiateDefaultStepResult([timingFormItem.identifier : "30-60 minutes ago"]) taskResult.results?.append(timingResult) // Get track each step let step3 = task.step(after: step2, with: taskResult) XCTAssertNotNil(step3) guard let timingEachStep = step3 as? SBATrackedActivityPageStep else { XCTAssert(false, "\(step3) not of expected type") return } XCTAssertEqual(timingEachStep.identifier, "medicationTrackEach") // Add timing each result let timingEachResult = timingEachStep.instantiateDefaultStepResult(nil) taskResult.results?.append(timingEachResult) // Check that this is the last step let step4 = task.step(after: step3, with: taskResult) XCTAssertNil(step4) guard let momentInDayResults = dataStore.momentInDayResults else { XCTAssert(false, "Data store momentInDayResults are nil") return } guard momentInDayResults.count == 3 else { XCTAssert(false, "results count does not match expected") return } XCTAssertEqual(momentInDayResults[0], momentResult) XCTAssertEqual(momentInDayResults[1], timingResult) XCTAssertEqual(momentInDayResults[2], timingEachResult) } // Mark: Commit/reset func testCommitChanges_NoMedication() { let dataStore = self.dataStoreForMedicationTracking() dataStore.selectedItems = [] // --- method under test dataStore.commitChanges() // Changes have been saved and does not have changes XCTAssertFalse(dataStore.hasChanges); XCTAssertNotNil(dataStore.storedDefaults.object(forKey: "selectedItems")) XCTAssertNotNil(dataStore.lastTrackingSurveyDate) XCTAssertEqualWithAccuracy(dataStore.lastTrackingSurveyDate?.timeIntervalSinceNow ?? 99.0, 0.0, accuracy: 2) } func testCommitChanges_OtherTrackedResult() { let dataStore = self.dataStoreForMedicationTracking() let result = ORKBooleanQuestionResult(identifier: "trackedQuestion") result.booleanAnswer = true let stepResult = ORKStepResult(stepIdentifier: "trackedQuestion", results: [result]) dataStore.updateTrackedData(for: stepResult) // --- method under test dataStore.commitChanges() // Changes have been saved and does not have changes XCTAssertFalse(dataStore.hasChanges); XCTAssertNotNil(dataStore.storedDefaults.object(forKey: "results")) XCTAssertNotNil(dataStore.lastTrackingSurveyDate) XCTAssertEqualWithAccuracy(dataStore.lastTrackingSurveyDate?.timeIntervalSinceNow ?? 99.0, 0.0, accuracy: 2) } func testCommitChanges_WithTrackedMedicationAndMomentInDayResult() { let dataStore = self.dataStoreForMedicationTracking() let med = SBAMedication(dictionaryRepresentation: ["name": "Levodopa", "tracking": true]) dataStore.selectedItems = [med] let momentInDayResults = createMomentInDayResults() dataStore.momentInDayResults = momentInDayResults // --- method under test dataStore.commitChanges() // Changes have been saved and does not have changes XCTAssertFalse(dataStore.hasChanges) XCTAssertNotNil(dataStore.storedDefaults.object(forKey: "selectedItems")) XCTAssertEqual(dataStore.selectedItems?.count ?? 0, 1) XCTAssertEqual(dataStore.selectedItems?.first, med) XCTAssertNotNil(dataStore.momentInDayResults); XCTAssertEqual(dataStore.momentInDayResults!, momentInDayResults) } func testReset() { let dataStore = self.dataStoreForMedicationTracking() let med = SBAMedication(dictionaryRepresentation: ["name": "Levodopa", "tracking": true]) dataStore.selectedItems = [med] dataStore.commitChanges() let changedMed = SBAMedication(dictionaryRepresentation: ["name": "Rytary", "tracking": true]) dataStore.selectedItems = [changedMed] let momentInDayResults = createMomentInDayResults() dataStore.momentInDayResults = momentInDayResults // --- method under test dataStore.reset() XCTAssertFalse(dataStore.hasChanges) XCTAssertEqual(dataStore.selectedItems!, [med]) XCTAssertNil(dataStore.momentInDayResults) } // Mark: shouldIncludeMomentInDayQuestions func testShouldIncludeMomentInDayQuestions_LastCompletionNil() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = false dataStore.selectedItems = Array(dataCollection.items[2...3]) dataStore.momentInDayResults = createMomentInDayResults() dataStore.commitChanges() dataStore.mockLastCompletionDate = nil // Check assumptions XCTAssertNotEqual(dataStore.trackedItems?.count ?? 99, 0) XCTAssertFalse(dataStore.hasChanges) XCTAssertNotNil(dataStore.momentInDayResults) XCTAssertNil(dataStore.lastCompletionDate) // For a nil date, the collection should show the moment in day questions XCTAssertTrue(dataCollection.shouldIncludeMomentInDayQuestions()) } func testShouldIncludeMomentInDayQuestions_StashNil() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = false dataStore.selectedItems = Array(dataCollection.items[2...3]) dataStore.commitChanges() dataStore.mockLastCompletionDate = Date() // Check assumptions XCTAssertNotEqual(dataStore.trackedItems?.count ?? 99, 0) XCTAssertFalse(dataStore.hasChanges) XCTAssertNil(dataStore.momentInDayResults) XCTAssertNotNil(dataStore.lastCompletionDate) // For a nil moment in day question set should include XCTAssertTrue(dataCollection.shouldIncludeMomentInDayQuestions()) } func testShouldIncludeMomentInDayQuestions_TakesMedication() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = false dataStore.selectedItems = Array(dataCollection.items[2...3]) dataStore.momentInDayResults = createMomentInDayResults() dataStore.commitChanges() // Check assumptions XCTAssertNotEqual(dataStore.trackedItems?.count ?? 99, 0) XCTAssertFalse(dataStore.hasChanges) XCTAssertNotNil(dataStore.momentInDayResults) // If it has been more than 30 minutes, should ask the question again dataStore.mockLastCompletionDate = Date(timeIntervalSinceNow: -30 * 60) XCTAssertTrue(dataCollection.shouldIncludeMomentInDayQuestions()) // For a recent time, should NOT include step dataStore.mockLastCompletionDate = Date(timeIntervalSinceNow: -2 * 60) XCTAssertFalse(dataCollection.shouldIncludeMomentInDayQuestions()) // If should always include the timing questions then should be true dataCollection.alwaysIncludeActivitySteps = true XCTAssertTrue(dataCollection.shouldIncludeMomentInDayQuestions()) } func testShouldIncludeMomentInDayQuestions_NoMedication() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = true dataStore.selectedItems = [] dataStore.momentInDayResults = createMomentInDayResults() dataStore.commitChanges() dataStore.mockLastCompletionDate = Date(timeIntervalSinceNow: -2 * 60) // Check assumptions XCTAssertEqual(dataStore.trackedItems?.count ?? 99, 0) XCTAssertFalse(dataStore.hasChanges) XCTAssertNotNil(dataStore.momentInDayResults) XCTAssertNotNil(dataStore.lastCompletionDate) // If no meds, should not be asked the moment in day question XCTAssertFalse(dataCollection.shouldIncludeMomentInDayQuestions()) } // Mark: shouldIncludeChangedQuestion func testShouldIncludeChangedQuestion_NO() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = true dataStore.selectedItems = [] dataStore.commitChanges() // If it has been one day, do not include dataStore.lastTrackingSurveyDate = Date(timeIntervalSinceNow: -24 * 60 * 60) XCTAssertFalse(dataCollection.shouldIncludeChangedStep()) } func testShouldIncludeChangedQuestion_YES() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore dataCollection.alwaysIncludeActivitySteps = true dataStore.selectedItems = [] dataStore.commitChanges() // If it has been over a month, do not include dataStore.lastTrackingSurveyDate = Date(timeIntervalSinceNow: -32 * 24 * 60 * 60) XCTAssertTrue(dataCollection.shouldIncludeChangedStep()) } // Mark: - stepResultForStep: func testStepResultForStep_SelectedItemsStep() { // Check shared functionality let (retTask, retDataStore, _, retTaskResult) = stepToActivity(["Levodopa", "Carbidopa", "Rytary", "Apokyn"]) guard let dataStore = retDataStore, let selectionStep = retTask?.step?(withIdentifier: "medicationSelection"), let selectionResult = retTaskResult?.stepResult(forStepIdentifier: "medicationSelection") else { XCTAssert(false, "preconditions not met") return } // commit the changes dataStore.commitChanges() // --- Rebuild the result from the data store guard let storedResult = dataStore.stepResult(for: selectionStep) else { XCTAssert(false, "restored result is nil") return } // restored result should have equal answers and identifiers but not be identical objects XCTAssertFalse(storedResult === selectionResult) // Identifier should match XCTAssertEqual(storedResult.identifier, selectionResult.identifier) // And start/end date should match XCTAssertEqual(storedResult.startDate, dataStore.lastTrackingSurveyDate) XCTAssertEqual(storedResult.endDate, dataStore.lastTrackingSurveyDate) guard let storedResults = storedResult.results, let selectionResults = selectionResult.results else { XCTAssert(false, "results are nil or counts do not match") return } XCTAssertEqual(storedResults.count, selectionResults.count) for expectedResult in selectionResults { let result = storedResult.result(forIdentifier: expectedResult.identifier) XCTAssertNotNil(result, "\(expectedResult.identifier)") if let result = result as? ORKQuestionResult { XCTAssertNotNil(result, "\(expectedResult.identifier)") XCTAssertEqual(result.answer as! NSObject, (expectedResult as! ORKQuestionResult).answer as! NSObject, "\(expectedResult.identifier)") } } } func testStepResultForStep_OtherTrackedStep_BooleanForm() { let dataStore = self.dataStoreForMedicationTracking() // Create the result and commit the changes let questionResult = ORKBooleanQuestionResult(identifier: "trackedQuestion") questionResult.booleanAnswer = true let stepResult = ORKStepResult(stepIdentifier: "trackedStep", results: [questionResult]) dataStore.updateTrackedData(for: stepResult) dataStore.commitChanges() // Create the step let step = ORKFormStep(identifier: "trackedStep") step.formItems = [ORKFormItem(identifier: "trackedQuestion", text: nil, answerFormat: ORKAnswerFormat.booleanAnswerFormat())] // Get the restored result let storedResult = dataStore.stepResult(for: step) XCTAssertNotNil(storedResult) guard let booleanResult = storedResult?.results?.first as? ORKBooleanQuestionResult else { XCTAssert(false, "\(storedResult) results are nil or not expected type") return } XCTAssertEqual(storedResult!.identifier, "trackedStep") XCTAssertEqual(booleanResult.identifier, "trackedQuestion") XCTAssertEqual(booleanResult.booleanAnswer!, questionResult.booleanAnswer!) } func testStepResultForStep_OtherTrackedStep_BooleanQuestion() { let dataStore = self.dataStoreForMedicationTracking() // Create the result and commit the changes let questionResult = ORKBooleanQuestionResult(identifier: "trackedQuestion") questionResult.booleanAnswer = true let stepResult = ORKStepResult(stepIdentifier: "trackedQuestion", results: [questionResult]) dataStore.updateTrackedData(for: stepResult) dataStore.commitChanges() // Create the step let step = ORKQuestionStep(identifier: "trackedQuestion", title: nil, answer: ORKAnswerFormat.booleanAnswerFormat()) // Get the restored result let storedResult = dataStore.stepResult(for: step) XCTAssertNotNil(storedResult) guard let booleanResult = storedResult?.results?.first as? ORKBooleanQuestionResult else { XCTAssert(false, "\(storedResult) results are nil or not expected type") return } XCTAssertEqual(storedResult!.identifier, "trackedQuestion") XCTAssertEqual(booleanResult.identifier, "trackedQuestion") XCTAssertEqual(booleanResult.booleanAnswer!, questionResult.booleanAnswer!) } // MARK: ORKTaskResultSource func testStoredTaskResultSource() { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore // Setup the data store to have selected items and need to include the changed step dataStore.selectedItems = dataCollection.items.filter({ $0.identifier == "Levodopa" }) dataStore.commitChanges() dataStore.lastTrackingSurveyDate = Date(timeIntervalSinceNow: -40*24*60*60) // Create a task let factory = SBABaseSurveyFactory() let introStep = ORKInstructionStep(identifier: "intro") let surveyStep = dataCollection.transformToStep(with: factory, isLastStep: false)! let questionStep = ORKQuestionStep(identifier: "booleanQuestion", title: nil, answer: ORKAnswerFormat.booleanAnswerFormat()) let conclusionStep = ORKCompletionStep(identifier: "conclusion") let task = SBANavigableOrderedTask(identifier: "task", steps: [introStep, surveyStep, questionStep, conclusionStep]) // check assumptions let selectionStepIdentifier = "Medication Tracker.medicationSelection" let selectionStep = task.step(withIdentifier: selectionStepIdentifier) XCTAssertNotNil(selectionStep) // Check the initial stored result let result = task.stepResult(forStepIdentifier: selectionStepIdentifier) XCTAssertNotNil(result) } // MARK: convenience methods func dataStoreForMedicationTracking() -> MockTrackedDataStore { return MockTrackedDataStore() } func dataCollectionForMedicationTracking() -> SBATrackedDataObjectCollection? { guard let json = self.jsonForResource("MedicationTracking") as? [AnyHashable: Any] else { return nil } return SBATrackedDataObjectCollection(dictionaryRepresentation: json) } func createMomentInDayResults() -> [ORKStepResult] { let momResult = ORKChoiceQuestionResult(identifier: NSUUID().uuidString) momResult.startDate = Date(timeIntervalSinceNow: -2*60) momResult.endDate = momResult.startDate.addingTimeInterval(30) momResult.questionType = .singleChoice momResult.choiceAnswers = ["Another Time"] let stepResult = ORKStepResult(stepIdentifier: "momentInDay", results: [momResult]) return [stepResult] } func stepToActivity(_ choiceAnswers: [String]) -> (task: ORKTask?, dataStore: SBATrackedDataStore?, selectionStep: ORKStep?, taskResult: ORKTaskResult?) { guard let dataCollection = self.dataCollectionForMedicationTracking() else { return (nil,nil,nil,nil) } let dataStore = self.dataStoreForMedicationTracking() dataCollection.dataStore = dataStore let transformedStep = dataCollection.transformToStep(with: SBABaseSurveyFactory(), isLastStep: false) guard let subtaskStep = transformedStep as? SBASubtaskStep else { XCTAssert(false, "\(transformedStep) not of expected type") return (nil,nil,nil, nil) } // Iterate through the steps before the selection step let task = subtaskStep.subtask let taskResult = ORKTaskResult(identifier: task.identifier) taskResult.results = [] var step: ORKStep? = nil repeat { if let previousStep = step { let stepResult = ORKStepResult(stepIdentifier: previousStep.identifier, results: nil) taskResult.results! += [stepResult] } guard let nextStep = task.step(after: step, with: taskResult) else { XCTAssert(false, "\(step) after not expected to be nil") return (nil, nil, nil, nil) } step = nextStep } while (step!.identifier != "medicationSelection") // modify the result to include the selected items if this is the selection step let answerMap = NSMutableDictionary() if choiceAnswers.count > 0 { answerMap.setValue(choiceAnswers, forKey: "choices") for key in choiceAnswers { answerMap.setValue(UInt(key.characters.count), forKey: key) } } else { answerMap.setValue("None", forKey: "choices") } let stepResult = step!.instantiateDefaultStepResult(answerMap) taskResult.results?.append(stepResult) // get the next step step = task.step(after: step, with: taskResult) XCTAssertNotNil(step) XCTAssertNotNil(dataStore.selectedItems) // check that the frequency values are set for the selected items for item in dataStore.selectedItems! { if (item.usesFrequencyRange) { XCTAssertEqual(item.frequency, UInt(item.identifier.characters.count), "\(item.identifier)") } } guard let handStep = step as? ORKFormStep, let handFormItem = handStep.formItems?.first else { XCTAssert(false, "\(step) not of expected type" ) return (nil, nil, nil, nil) } // Add the hand result let handQuestionResult = ORKChoiceQuestionResult(identifier: handFormItem.identifier) handQuestionResult.choiceAnswers = ["Right hand"] let handResult = ORKStepResult(stepIdentifier: handStep.identifier, results: [handQuestionResult]) taskResult.results?.append(handResult) return (task, dataStore, step, taskResult) } }
45.868442
368
0.659077
23d8d66f7247e25ae54501f69b5c63f5a985cdf0
1,549
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit import XCTest class StringResonatorTests: XCTestCase { func testBandwidth() { let engine = AudioEngine() let input = Oscillator(waveform: Table(.triangle)) engine.output = ResonantFilter(input, bandwidth: 100) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testDefault() { let engine = AudioEngine() let input = Oscillator(waveform: Table(.triangle)) engine.output = StringResonator(input) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testFrequency() { let engine = AudioEngine() let input = Oscillator(waveform: Table(.triangle)) engine.output = ResonantFilter(input, frequency: 500) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testParameters() { let engine = AudioEngine() let input = Oscillator(waveform: Table(.triangle)) engine.output = ResonantFilter(input, frequency: 500, bandwidth: 100) input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } }
31.612245
100
0.638476
c1b7e255b4624ed0c35f4d574beddce959d339e3
1,626
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Zesame", platforms: [.macOS(.v10_15), .iOS(.v13)], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "Zesame", targets: ["Zesame"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/Sajjon/EllipticCurveKit.git", .upToNextMinor(from: "1.0.2")), .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.4.0")), .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.1.0")), .package(name: "SwiftProtobuf", url: "https://github.com/apple/swift-protobuf.git", from: "1.6.0"), .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.2.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "Zesame", dependencies: ["EllipticCurveKit", "CryptoSwift", "RxSwift", "SwiftProtobuf", "Alamofire"], exclude: ["Models/Protobuf/messages.proto"] ), .testTarget( name: "ZesameTests", dependencies: ["Zesame"]), ] )
45.166667
117
0.630381
f50230b7c4228729470d6bce49e844724ac972d8
2,158
// // AppDelegate.swift // Example // // Created by luojie on 16/4/1. // Copyright © 2016年 LuoJie. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.914894
285
0.753475
8a9d8dafffad0d7e1b28e1cd55f8b21d527512ab
4,240
// // UIViewExtensions.swift // APBCommon // // Created by ApprovedBug on 14/06/2019. // import UIKit public extension UIView { // MARK: Align different edges @discardableResult func alignAttribute(_ selfAttribute: NSLayoutConstraint.Attribute, WithView relatedView: UIView, Attribute relatedViewAttribute: NSLayoutConstraint.Attribute, constant: CGFloat) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false let constraint: NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: selfAttribute, relatedBy: .equal, toItem: relatedView, attribute: relatedViewAttribute, multiplier: 1, constant: constant) constraint.isActive = true return constraint } // MARK: Single edge layout func alignTopEdgeWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.top, WithView: relatedView, Attribute: .top, constant: constant) } func alignLeadingEdgeWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.leading, WithView: relatedView, Attribute: .leading, constant: constant) } func alignBottomEdgeWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.bottom, WithView: relatedView, Attribute: .bottom, constant: constant) } func alignTrailingEdgeWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.trailing, WithView: relatedView, Attribute: .trailing, constant: constant) } // MARK: Multple edge layout func alignTopAndLeadingEdgesWithView(_ relatedView: UIView, topConstant: CGFloat, leadingConstant: CGFloat) { self.alignTopEdgeWithView(relatedView, constant: topConstant) self.alignLeadingEdgeWithView(relatedView, constant: leadingConstant) } func alignBottomAndTrailingEdgesWithView(_ relatedView: UIView, bottomConstant: CGFloat, trailingConstant: CGFloat) { self.alignBottomEdgeWithView(relatedView, constant: bottomConstant) self.alignTrailingEdgeWithView(relatedView, constant: trailingConstant) } func alignLeadingAndTrailingEdgesWithView(_ relatedView: UIView, leadingConstant: CGFloat, trailingConstant: CGFloat) { self.alignLeadingEdgeWithView(relatedView, constant: leadingConstant) self.alignTrailingEdgeWithView(relatedView, constant: trailingConstant) } func alignWithView(_ relatedView: UIView) { self.alignTopAndLeadingEdgesWithView(relatedView, topConstant: 0, leadingConstant: 0) self.alignBottomAndTrailingEdgesWithView(relatedView, bottomConstant: 0, trailingConstant: 0) } // MARK: Width and height layout @discardableResult func constrainWidth(_ constant: CGFloat) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false let constraint: NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) constraint.isActive = true return constraint } @discardableResult func constrainHeight(_ constant: CGFloat) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false let constraint: NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: constant) constraint.isActive = true return constraint } func constrainWidthWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.width, WithView: relatedView, Attribute: .width, constant: constant) } func constrainHeightWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.height, WithView: relatedView, Attribute: .height, constant: constant) } // MARK: Center layout func alignCenterYWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.centerY, WithView: relatedView, Attribute: .centerY, constant: constant) } func alignCenterXWithView(_ relatedView: UIView, constant: CGFloat) { alignAttribute(.centerX, WithView: relatedView, Attribute: .centerX, constant: constant) } }
38.198198
209
0.738915
e985a360c5594a0d98de0c5bcab81911a877cbee
7,663
// // AnyImageViewController.swift // AnyImageKit // // Created by 刘栋 on 2020/1/7. // Copyright © 2020-2022 AnyImageKit.org. All rights reserved. // import UIKit class AnyImageViewController: UIViewController { private var page: AnyImagePage = .undefined private var isStatusBarHidden: Bool = false { didSet { setNeedsStatusBarAppearanceUpdate() } } weak var trackObserver: DataTrackObserver? override func viewDidLoad() { super.viewDidLoad() setTrackPage() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) trackObserver?.track(page: page, state: .enter) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) trackObserver?.track(page: page, state: .leave) } override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { setTrackObserverOrDelegate(viewControllerToPresent) super.present(viewControllerToPresent, animated: flag, completion: completion) } override var prefersStatusBarHidden: Bool { return isStatusBarHidden } override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return [.portrait] } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } func setStatusBar(hidden: Bool) { isStatusBarHidden = hidden } } // MARK: - Function extension AnyImageViewController { func showAlert(message: String, stringConfig: ThemeStringConfigurable) { let alert = UIAlertController(title: stringConfig[string: .alert], message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: stringConfig[string: .ok], style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } // MARK: - Data Track extension AnyImageViewController { private func setTrackPage() { switch self { #if ANYIMAGEKIT_ENABLE_PICKER case _ as AlbumPickerViewController: page = .pickerAlbum case _ as AssetPickerViewController: page = .pickerAsset case _ as PhotoPreviewController: page = .pickerPreview #endif #if ANYIMAGEKIT_ENABLE_EDITOR case _ as PhotoEditorController: page = .editorPhoto case _ as VideoEditorController: page = .editorVideo case _ as InputTextViewController: page = .editorInputText #endif #if ANYIMAGEKIT_ENABLE_CAPTURE case _ as CaptureViewController: page = .capture case _ as PadCaptureViewController: page = .capture #endif default: page = .undefined } } private func setTrackObserverOrDelegate(_ target: UIViewController) { if let controller = target as? AnyImageViewController { controller.trackObserver = trackObserver } else if let controller = target as? AnyImageNavigationController { if let navigationController = navigationController as? AnyImageNavigationController { controller.trackDelegate = navigationController.trackDelegate } else if let navigationController = presentingViewController as? AnyImageNavigationController { controller.trackDelegate = navigationController.trackDelegate } } } } // MARK: - Permission extension AnyImageViewController { func check(permission: Permission, authorized: @escaping () -> Void, limited: @escaping () -> Void, denied: @escaping (Permission) -> Void) { switch permission.status { case .notDetermined: permission.request { result in switch result { case .authorized: authorized() case .denied: denied(permission) default: limited() } } case .authorized: authorized() case .limited: limited() case .denied: denied(permission) } } func check(permissions: [Permission], authorized: @escaping () -> Void, denied: @escaping (Permission) -> Void) { if !permissions.isEmpty { var _permissions = permissions let permission = _permissions.removeFirst() check(permission: permission, authorized: { [weak self] in guard let self = self else { return } self.check(permissions: _permissions, authorized: authorized, denied: denied) }, limited: { [weak self] in guard let self = self else { return } self.check(permissions: _permissions, authorized: authorized, denied: denied) }, denied: { _ in denied(permission) }) } else { authorized() } } } // MARK: - Permission UI extension AnyImageViewController { func check(permission: Permission, stringConfig: ThemeStringConfigurable, authorized: @escaping () -> Void, canceled: @escaping (Permission) -> Void) { check(permission: permission, authorized: authorized, limited: authorized, denied: { [weak self] _ in guard let self = self else { return } let title = String(format: stringConfig[string: .permissionIsDisabled], stringConfig[string: permission.localizedTitleKey]) let message = String(format: stringConfig[string: permission.localizedAlertMessageKey], BundleHelper.appName) let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let settings = stringConfig[string: .settings] alert.addAction(UIAlertAction(title: settings, style: .default, handler: { _ in guard let url = URL(string: UIApplication.openSettingsURLString) else { return } UIApplication.shared.open(url, options: [:]) { _ in canceled(permission) } })) let cancel = stringConfig[string: .cancel] alert.addAction(UIAlertAction(title: cancel, style: .cancel, handler: { _ in canceled(permission) })) self.present(alert, animated: true, completion: nil) }) } func check(permissions: [Permission], stringConfig: ThemeStringConfigurable, authorized: @escaping () -> Void, canceled: @escaping (Permission) -> Void) { if !permissions.isEmpty { var _permissions = permissions let permission = _permissions.removeFirst() check(permission: permission, stringConfig: stringConfig, authorized: { [weak self] in guard let self = self else { return } self.check(permissions: _permissions, stringConfig: stringConfig, authorized: authorized, canceled: canceled) }, canceled: canceled) } else { authorized() } } } // MARK: - HUD extension AnyImageViewController { func showWaitHUD(_ message: String = "") { _showWaitHUD(self, message) } func showMessageHUD(_ message: String) { _showMessageHUD(self, message) } func hideHUD(animated: Bool = true) { _hideHUD(self, animated: animated) } }
35.151376
158
0.616991
1c56eafd0f15813c4d507b6285baf7a265fc98bb
374
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "Nantes", platforms: [.iOS(.v12)], products: [ .library(name: "Nantes", targets: ["Nantes"]) ], dependencies: [], targets: [ .target( name: "Nantes", path: "Source/Classes", exclude: ["Nantes.h"] ) ] )
18.7
53
0.505348
0afe2cbca562ff443e45a248aa489a549269aa7c
6,150
// // TabView.swift // Sliding Toolbar // // Created by Ulf Akerstedt-Inoue on 2020/01/10. // Copyright © 2020 hakkabon software. All rights reserved. // import UIKit @available(iOS 9.0, *) class TabView: UIView { var handleTapAction: (() -> ())? public var side: SlidingToolbarPosition = .left { didSet { gripView.side = side setNeedsLayout() } } public var cornerRadius: CGFloat = 17 { didSet { gripView.cornerRadius = cornerRadius setNeedsLayout() } } lazy var gripView: GripView = { let view = GripView() view.backgroundColor = .clear view.translatesAutoresizingMaskIntoConstraints = false return view }() let blurEffect = UIBlurEffect(style: blurEffectStyle()) lazy var blurredView: UIVisualEffectView = { let effect = UIVisualEffectView(effect: blurEffect) effect.translatesAutoresizingMaskIntoConstraints = false return effect }() lazy var vibrancyView: UIVisualEffectView = { let vibrancy = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) vibrancy.translatesAutoresizingMaskIntoConstraints = false return vibrancy }() override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } class func blurEffectStyle() -> UIBlurEffect.Style { if #available(iOS 13, *) { return .systemUltraThinMaterial } else { return .dark } } func initialize() { self.clipsToBounds = false self.isUserInteractionEnabled = true self.backgroundColor = .clear self.addSubview(gripView) self.insertSubview(blurredView, at: 0) blurredView.contentView.addSubview(vibrancyView) vibrancyView.contentView.addSubview(gripView) gripView.blurredBackgroundView = blurredView gripView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))) } override func updateConstraints() { switch side { case .left: NSLayoutConstraint.activate([ gripView.topAnchor.constraint(equalTo: self.topAnchor), gripView.bottomAnchor.constraint(equalTo: self.bottomAnchor), gripView.leadingAnchor.constraint(equalTo: self.leadingAnchor), gripView.trailingAnchor.constraint(equalTo: self.trailingAnchor), ]) case .right: NSLayoutConstraint.activate([ gripView.topAnchor.constraint(equalTo: self.topAnchor), gripView.bottomAnchor.constraint(equalTo: self.bottomAnchor), gripView.leadingAnchor.constraint(equalTo: self.leadingAnchor), gripView.trailingAnchor.constraint(equalTo: self.trailingAnchor), ]) } NSLayoutConstraint.activate([ blurredView.heightAnchor.constraint(equalTo: gripView.heightAnchor), blurredView.widthAnchor.constraint(equalTo: gripView.widthAnchor), blurredView.centerXAnchor.constraint(equalTo: gripView.centerXAnchor), blurredView.centerYAnchor.constraint(equalTo: gripView.centerYAnchor) ]) NSLayoutConstraint.activate([ vibrancyView.heightAnchor.constraint(equalTo: blurredView.contentView.heightAnchor), vibrancyView.widthAnchor.constraint(equalTo: blurredView.contentView.widthAnchor), vibrancyView.centerXAnchor.constraint(equalTo: blurredView.contentView.centerXAnchor), vibrancyView.centerYAnchor.constraint(equalTo: blurredView.contentView.centerYAnchor) ]) super.updateConstraints() } @objc func handleTap(_ sender: UITapGestureRecognizer) { self.handleTapAction?() } } class GripView: UIView { var side: SlidingToolbarPosition = .left { didSet { setNeedsLayout() } } var blurredBackgroundView: UIVisualEffectView? public var cornerRadius: CGFloat = 17 { didSet { setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize() { self.clipsToBounds = false self.backgroundColor = .clear } // Add grove lines to grip. override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() defer { context.restoreGState() } context.setStrokeColor(UIColor.white.cgColor) context.setLineCap(.round) context.setLineWidth(1.5) let groves = rect.insetBy(dx: 5, dy: 15) let countLine: Int = 3 for i in 1 ... 3 { let x = ((groves.size.width / CGFloat(countLine)) * CGFloat(i)) - CGFloat(countLine) context.move(to: CGPoint(x: x, y: groves.minY)) context.addLine(to: CGPoint(x: x, y: groves.maxY)) } context.strokePath() } func layoutView() { let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds if side == .left { maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath } else { maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath } self.layer.mask = maskLayer blurredBackgroundView?.layer.mask = maskLayer } override func layoutSubviews() { super.layoutSubviews() layoutView() } }
32.03125
113
0.622114
8a8feb81cb87d8986cdbc5f74ec8d1b98e6d0c29
2,684
// SwiftUIPlayground // https://github.com/ralfebert/SwiftUIPlayground/ import SwiftUI struct PlayerLoopView: View { @ObservedObject var player: Player var body: some View { ZStack { Circle() .stroke(style: StrokeStyle(lineWidth: 10.0)) .foregroundColor(Color.purple) .opacity(0.3) Circle() .trim( from: 0, to: player.isPlaying ? 1.0 : 0.0 ) .stroke( style: StrokeStyle(lineWidth: 10.0, lineCap: .round, lineJoin: .round) ) .animation( player.isPlaying ? Animation.linear(duration: player.duration) .repeatForever(autoreverses: false) : nil ) .rotationEffect(Angle(degrees: -90)) .foregroundColor(Color.purple) } .frame(width: 100, height: 100) .padding() } } struct PlayersProgressView: View { @ObservedObject var engine = Engine() var body: some View { NavigationView { VStack { ForEach(self.engine.players) { player in HStack { Text("Player") PlayerLoopView(player: player) } } } .navigationBarItems(trailing: HStack { Button("Add Player") { self.engine.addPlayer() } Button("Play All") { self.engine.playAll() } Button("Stop All") { self.engine.stopAll() } }.padding() ) } } } class Player: ObservableObject, Identifiable { var id = UUID() @Published var isPlaying: Bool = false var duration: Double = 10 func play() { self.isPlaying = true } func stop() { self.isPlaying = false } } class Engine: ObservableObject { @Published var players = [Player]() func addPlayer() { let player = Player() players.append(player) DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { player.isPlaying = true } } func stopAll() { self.players.forEach { $0.stop() } } func playAll() { self.players.forEach { $0.play() } } } struct PlayersProgressView_Previews: PreviewProvider { static var previews: some View { PlayersProgressView() } }
25.320755
90
0.469076
38e984963993d6abc827058f17407898663af8b6
2,183
// // UIScrollView+MYPAddition.swift // MYPTextInputVC // // Created by wakary redou on 2018/5/4. // Copyright © 2018年 wakary redou. All rights reserved. // import UIKit /** UIScrollView additional features used for MYPMessageVC. */ extension UIScrollView { /** true if the scrollView's offset is at the very top. */ var myp_isAtTop: Bool { return self.myp_visibleRect.minY <= self.bounds.minY } /** true if the scrollView's offset is at the very bottom. */ var myp_isAtBottom: Bool { return self.myp_visibleRect.maxY >= self.myp_bottomRect.maxY } /** The visible area of the content size. */ var myp_visibleRect: CGRect { return CGRect(origin: self.contentOffset, size: self.frame.size) } /** Sets the content offset to the top. animated: true to animate the transition at a constant velocity to the new offset, false to make the transition immediate. */ func myp_scrollToTop(animated: Bool) { if self.myp_canScroll { self.setContentOffset(CGPoint.zero, animated: animated) } } /** Sets the content offset to the bottom. animated: true to animate the transition at a constant velocity to the new offset, false to make the transition immediate. */ func myp_scrollToBottom(animated: Bool) { if self.myp_canScroll { self.setContentOffset(self.myp_bottomRect.origin, animated: animated) } } /** Stops scrolling, if it was scrolling. */ func myp_stopScrolling() { if !self.isDragging { return } var offset = self.contentOffset offset.y -= 1.0 self.contentOffset = offset offset.y += 1.0 self.contentOffset = offset } private var myp_canScroll: Bool { if self.contentSize.height > self.frame.height { return true } return false } private var myp_bottomRect: CGRect { return CGRect(x: 0.0, y: self.contentSize.height - self.bounds.height, width: self.bounds.width, height: self.bounds.height) } }
27.987179
132
0.62208
eb25ec0f854d3b51cfb9789843ae98c8278436bf
1,305
// // mathToolsAdv.swift // // // Created by Jerry Yan on 7/18/19. // // This is the advanced part of the mathTools in JYMTBasicKit. // Advanced computationss such as eigenvalues and eigenvectors // will be implemented with the integration of Python's NumPy // library. // // import Foundation import JYMTBasicKit import PythonKit public extension Matrix { /** The numpy 2-D array of the information contained in the matrix. */ var npForm: PythonObject { let np = Python.import("numpy") return np.array(content) } /** Find the eigensystem of the matrix. - Returns: - an optional tuple containing a 1-D optional array presenting the eigenvalues and a 2-D optional array presenting the corresponding eigenvectors. - `nil`: if the matrix is not a square matrix. - `(nil, nil)`: if the function failed to parse the result from Python's NumPy library *(This can happen when the eigenvalues/eigenvectors containing complex value)*. */ func eigenSystem() -> ([Double]?, [[Double]]?)? { guard isSquareMatrix else { return nil } let LA = Python.import("numpy.linalg") let result = LA.eig(npForm) return ([Double](result[0]), [[Double]](result[1])) } }
29.659091
174
0.644444
0a58f09a1ff63cfa5c0473e7fe57071cc5239f22
25,147
// // Board.swift // Sage // // Copyright 2016 Nikolai Vazquez // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #if os(OSX) import Cocoa #elseif os(iOS) || os(tvOS) import UIKit #endif /// A chess board used to map `Square`s to `Piece`s. /// /// Pieces map to separate instances of `Bitboard` which can be retreived with `bitboard(for:)`. public struct Board: Hashable, CustomStringConvertible { /// A chess board space. public struct Space: Hashable, CustomStringConvertible { /// The occupying chess piece. public var piece: Piece? /// The space's file. public var file: File /// The space's rank. public var rank: Rank /// The space's location on a chess board. public var location: Location { get { return (file, rank) } set { (file, rank) = newValue } } /// The space's square on a chess board. public var square: Square { get { return Square(file: file, rank: rank) } set { location = newValue.location } } /// The space's color. public var color: Color { return (file.index & 1 != rank.index & 1) ? ._white : ._black } /// The space's name. public var name: String { return "\(file.character)\(rank.rawValue)" } /// A textual representation of `self`. public var description: String { return "Space(\(name), \(piece.map({ String($0) }) ?? "nil"))" } /// The hash value. public var hashValue: Int { let pieceHash = piece?.hashValue ?? (6 << 1) let fileHash = file.hashValue << 4 let rankHash = rank.hashValue << 7 return pieceHash + fileHash + rankHash } /// Create a chess board space with a piece, file, and rank. public init(piece: Piece? = nil, file: File, rank: Rank) { self.init(piece: piece, location: (file, rank)) } /// Create a chess board space with a piece and location. public init(piece: Piece? = nil, location: Location) { self.piece = piece (file, rank) = location } /// Create a chess board space with a piece and square. public init(piece: Piece? = nil, square: Square) { self.piece = piece (file, rank) = square.location } /// Clears the piece from the space and returns it. public mutating func clear() -> Piece? { let piece = self.piece self.piece = nil return piece } #if os(OSX) || os(iOS) || os(tvOS) internal func _view(size: CGFloat) -> _View { let frame = CGRect(x: CGFloat(file.index) * size, y: CGFloat(rank.index) * size, width: size, height: size) var textFrame = CGRect(x: 0, y: 0, width: size, height: size) let fontSize = size * 0.625 let view = _View(frame: frame) let str = piece.map({ String($0.specialCharacter(background: color)) }) ?? "" #if swift(>=3) let white = _Color.white() let black = _Color.black() #else let white = _Color.whiteColor() let black = _Color.blackColor() #endif let bg: _Color = color.isWhite ? white : black let tc: _Color = color.isWhite ? black : white #if os(OSX) view.wantsLayer = true let text = NSText(frame: textFrame) #if swift(>=3) view.layer?.backgroundColor = bg.cgColor text.alignment = .center text.font = .systemFont(ofSize: fontSize) text.isEditable = false text.isSelectable = false #else view.layer?.backgroundColor = bg.CGColor text.alignment = .Center text.font = .systemFontOfSize(fontSize) text.editable = false text.selectable = false #endif text.string = str text.drawsBackground = false text.textColor = tc view.addSubview(text) #else view.backgroundColor = bg let label = UILabel(frame: textFrame) #if swift(>=3) label.textAlignment = .center label.font = .systemFont(ofSize: fontSize) #else label.textAlignment = .Center label.font = .systemFontOfSize(fontSize) #endif label.text = str label.textColor = tc view.addSubview(label) #endif return view } #endif } /// An iterator for `Board` used as a base for both `Iterator` and `Generator`. private struct _MutualIterator { let _board: Board var _index: Int init(_ board: Board) { self._board = board self._index = 0 } mutating func next() -> Board.Space? { guard let square = Square(rawValue: _index) else { return nil } defer { _index += 1 } return _board.space(at: square) } } #if swift(>=3) /// An iterator for the spaces of a chess board. public struct Iterator: IteratorProtocol { private var _base: _MutualIterator /// Advances to the next space on the board and returns it. public mutating func next() -> Board.Space? { return _base.next() } } #else /// A generator for the spaces of a chess board. public struct Generator: GeneratorType { private var _base: _MutualIterator /// Advances to the next space on the board and returns it. public mutating func next() -> Board.Space? { return _base.next() } } #endif /// A board side. public enum Side { #if swift(>=3) /// Right side of the board. case kingside /// Right side of the board. case queenside #else /// Right side of the board. case Kingside /// Right side of the board. case Queenside #endif /// `self` is kingside. public var isKingside: Bool { #if swift(>=3) return self == .kingside #else return self == .Kingside #endif } /// `self` is queenside. public var isQueenside: Bool { #if swift(>=3) return self == .queenside #else return self == .Queenside #endif } } /// The piece to bitboard mapping of `self`. internal var _bitboards: [Piece: Bitboard] /// The board's pieces. public var pieces: [Piece] { return self.flatMap({ $0.piece }) } /// The board's white pieces. public var whitePieces: [Piece] { return pieces.filter({ $0.color.isWhite }) } /// The board's black pieces. public var blackPieces: [Piece] { return pieces.filter({ $0.color.isBlack }) } /// A bitboard for the empty spaces of `self`. public var emptySpaces: Bitboard { return ~_bitboards.reduce(0, combine: { $0 | $1.1 }) } /// A textual representation of `self`. public var description: String { return "Board(\(fen()))" } /// The hash value. public var hashValue: Int { return Set(self).hashValue } /// An ASCII art representation of `self`. /// /// The ASCII representation for the starting board: /// /// ``` /// +-----------------+ /// 8 | r n b q k b n r | /// 7 | p p p p p p p p | /// 6 | . . . . . . . . | /// 5 | . . . . . . . . | /// 4 | . . . . . . . . | /// 3 | . . . . . . . . | /// 2 | P P P P P P P P | /// 1 | R N B Q K B N R | /// +-----------------+ /// a b c d e f g h /// ``` public var ascii: String { let edge = " +-----------------+\n" var result = edge #if swift(>=3) let reversed = Rank.all.reversed() #else let reversed = Rank.all.reverse() #endif for rank in reversed { let strings = File.all.map({ file in "\(self[(file, rank)]?.character ?? ".")" }) #if swift(>=3) let str = strings.joined(separator: " ") #else let str = strings.joinWithSeparator(" ") #endif result += "\(rank) | \(str) |\n" } result += "\(edge) a b c d e f g h " return result } /// Create a chess board. /// /// - parameter variant: The variant to populate the board for. Won't populate if `nil`. Default is `Standard`. public init(variant: Variant? = ._standard) { _bitboards = [:] if let variant = variant { for piece in Piece.all { _bitboards[piece] = Bitboard(startFor: piece) } if variant.isUpsideDown { for (piece, board) in _bitboards { _bitboards[piece] = board.flippedVertically() } } } else { for piece in Piece.all { _bitboards[piece] = 0 } } } /// Create a chess board from a valid FEN string. /// /// - Warning: Only to be used with the board part of a full FEN string. /// /// - seealso: [FEN (Wikipedia)](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation), /// [FEN (Chess Programming Wiki)](https://chessprogramming.wikispaces.com/Forsyth-Edwards+Notation) public init?(fen: String) { func pieces(for string: String) -> [Piece?]? { var pieces: [Piece?] = [] for char in string.characters { guard pieces.count < 8 else { return nil } if let piece = Piece(character: char) { pieces.append(piece) } else if let num = Int(String(char)) { guard 1...8 ~= num else { return nil } #if swift(>=3) pieces += Array(repeating: nil, count: num) #else pieces += Array(count: num, repeatedValue: nil) #endif } else { return nil } } return pieces } guard !fen.characters.contains(" ") else { return nil } #if swift(>=3) let parts = fen.characters.split(separator: "/").map(String.init) let ranks = Rank.all.reversed() #else let parts = fen.characters.split("/").map(String.init) let ranks = Rank.all.reverse() #endif guard parts.count == 8 else { return nil } var board = Board(variant: nil) for (rank, part) in zip(ranks, parts) { guard let pieces = pieces(for: part) else { return nil } for (file, piece) in zip(File.all, pieces) { board[(file, rank)] = piece } } self = board } /// Gets and sets a piece at `location`. public subscript(location: Location) -> Piece? { get { return self[Square(location: location)] } set { self[Square(location: location)] = newValue } } /// Gets and sets a piece at `square`. public subscript(square: Square) -> Piece? { get { for (piece, board) in _bitboards { if board[square] { return piece } } return nil } set { for piece in _bitboards.keys { self[piece][square] = false } if let piece = newValue { if _bitboards[piece] == nil { _bitboards[piece] = Bitboard() } self[piece][square] = true } } } /// Gets and sets the bitboard for `piece`. internal subscript(piece: Piece) -> Bitboard { get { return _bitboards[piece] ?? Bitboard() } set { _bitboards[piece] = newValue } } /// Returns `self` flipped horizontally. private func _flippedHorizontally() -> Board { var board = self for (p, b) in _bitboards { board._bitboards[p] = b.flippedHorizontally() } return board } /// Returns `self` flipped vertically. private func _flippedVertically() -> Board { var board = self for (p, b) in _bitboards { board._bitboards[p] = b.flippedVertically() } return board } /// Clears all the pieces from `self`. public mutating func clear() { self = Board(variant: nil) } #if swift(>=3) /// Populates `self` with with all of the pieces at their proper locations for the given chess variant. public mutating func populate(for variant: Variant = .standard) { self = Board(variant: variant) } /// Returns `self` flipped horizontally. @warn_unused_result(mutable_variant:"flipHorizontally") public func flippedHorizontally() -> Board { return _flippedHorizontally() } /// Returns `self` flipped vertically. @warn_unused_result(mutable_variant:"flipVertically") public func flippedVertically() -> Board { return _flippedVertically() } #else /// Populates `self` with with all of the pieces at their proper locations for the given chess variant. public mutating func populate(for variant: Variant = .Standard) { self = Board(variant: variant) } /// Returns `self` flipped horizontally. @warn_unused_result(mutable_variant="flipHorizontally") public func flippedHorizontally() -> Board { return _flippedHorizontally() } /// Returns `self` flipped vertically. @warn_unused_result(mutable_variant="flipVertically") public func flippedVertically() -> Board { return _flippedVertically() } #endif /// Flips `self` horizontally. public mutating func flipHorizontally() { self = flippedHorizontally() } /// Flips `self` vertically. public mutating func flipVertically() { self = flippedVertically() } /// Returns the number of pieces for `color`, or all if `nil`. @warn_unused_result public func pieceCount(for color: Color? = nil) -> Int { if let color = color { return bitboard(for: color).count } else { return _bitboards.map({ $1.count }).reduce(0, combine: +) } } /// Returns the number of `piece` in `self`. @warn_unused_result public func count(of piece: Piece) -> Int { return bitboard(for: piece).count } /// Returns the bitboard for `piece`. @warn_unused_result public func bitboard(for piece: Piece) -> Bitboard { return self[piece] } /// Returns the bitboard for `color`. @warn_unused_result public func bitboard(for color: Color) -> Bitboard { return _bitboards.flatMap({ piece, board in piece.color == color ? board : nil }).reduce(0, combine: |) } /// Returns the bitboard for all pieces. @warn_unused_result public func bitboard() -> Bitboard { return _bitboards.reduce(0, combine: { $0 | $1.1 }) } /// Returns the attackers to `square` corresponding to `color`. /// /// - parameter square: The `Square` being attacked. /// - parameter color: The `Color` of the attackers. @warn_unused_result public func attackers(to square: Square, color: Color) -> Bitboard { let all = bitboard() let attackPieces = Piece.pieces(for: color) let playerPieces = Piece.pieces(for: color.inverse()) let attacks = playerPieces.map({ piece in square.attacks(for: piece, stoppers: all) }) #if swift(>=3) let queen = Piece.queen(color) #else let queen = Piece.Queen(color) #endif let queens = (attacks[2] | attacks[3]) & self[queen] return zip(attackPieces, attacks) .map({ self[$0] & $1 }) .reduce(queens, combine: |) } /// Returns the attackers to the king for `color`. /// /// - parameter color: The `Color` of the potentially attacked king. /// /// - returns: A bitboard of all attackers, or 0 if the king does not exist or if there are no pieces attacking the /// king. @warn_unused_result public func attackersToKing(for color: Color) -> Bitboard { guard let square = squareForKing(for: color) else { return 0 } return attackers(to: square, color: color.inverse()) } /// Returns `true` if the king for `color` is in check. @warn_unused_result public func kingIsChecked(for color: Color) -> Bool { return attackersToKing(for: color) != 0 } /// Returns the spaces at `file`. @warn_unused_result public func spaces(at file: File) -> [Space] { return Rank.all.map { space(at: (file, $0)) } } /// Returns the spaces at `rank`. @warn_unused_result public func spaces(at rank: Rank) -> [Space] { return File.all.map { space(at: ($0, rank)) } } /// Returns the space at `location`. @warn_unused_result public func space(at location: Location) -> Space { return Space(piece: self[location], location: location) } /// Returns the square at `location`. @warn_unused_result public func space(at square: Square) -> Space { return Space(piece: self[square], square: square) } #if swift(>=3) /// Removes a piece at `square`, and returns it. @discardableResult public mutating func removePiece(at square: Square) -> Piece? { if let piece = self[square] { self[piece][square] = false return piece } else { return nil } } /// Removes a piece at `location`, and returns it. @discardableResult public mutating func removePiece(at location: Location) -> Piece? { return removePiece(at: Square(location: location)) } #else /// Removes a piece at `square`, and returns it. public mutating func removePiece(at square: Square) -> Piece? { if let piece = self[square] { self[piece][square] = false return piece } else { return nil } } /// Removes a piece at `location`, and returns it. public mutating func removePiece(at location: Location) -> Piece? { return removePiece(at: Square(location: location)) } #endif /// Swaps the pieces between the two locations. public mutating func swap(_ first: Location, _ second: Location) { swap(Square(location: first), Square(location: second)) } /// Swaps the pieces between the two squares. public mutating func swap(_ first: Square, _ second: Square) { switch (self[first], self[second]) { case let (firstPiece?, secondPiece?): self[firstPiece].swap(first, second) self[secondPiece].swap(first, second) case let (firstPiece?, nil): self[firstPiece].swap(first, second) case let (nil, secondPiece?): self[secondPiece].swap(first, second) default: break } } /// Returns the locations where `piece` exists. @warn_unused_result public func locations(for piece: Piece) -> [Location] { return bitboard(for: piece).map({ $0.location }) } /// Returns the squares where `piece` exists. @warn_unused_result public func squares(for piece: Piece) -> [Square] { return Array(bitboard(for: piece)) } /// Returns the squares where pieces for `color` exist. @warn_unused_result public func squares(for color: Color) -> [Square] { return Array(bitboard(for: color)) } /// Returns the square of the king for `color`, if any. @warn_unused_result public func squareForKing(for color: Color) -> Square? { #if swift(>=3) let king = Piece.king(color) #else let king = Piece.King(color) #endif return bitboard(for: king).lsbSquare } /// Returns `true` if `self` contains `piece`. public func contains(_ piece: Piece) -> Bool { return _bitboards[piece]?.isEmpty == false } /// Returns the FEN string for the board. /// /// - seealso: [FEN (Wikipedia)](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation), /// [FEN (Chess Programming Wiki)](https://chessprogramming.wikispaces.com/Forsyth-Edwards+Notation) public func fen() -> String { func fen(forRank rank: Rank) -> String { var fen = "" var accumulator = 0 for space in spaces(at: rank) { if let piece = space.piece { if accumulator > 0 { fen += String(accumulator) accumulator = 0 } fen += String(piece.character) } else { accumulator += 1 #if swift(>=3) let h = File.h #else let h = File.H #endif if space.file == h { fen += String(accumulator) } } } return fen } #if swift(>=3) return Rank.all.reversed().map(fen).joined(separator: "/") #else return Rank.all.reverse().map(fen).joinWithSeparator("/") #endif } } #if swift(>=3) extension Board: Sequence { /// Returns an iterator over the spaces of the board. public func makeIterator() -> Iterator { return Iterator(_base: _MutualIterator(self)) } } #else extension Board: SequenceType { /// Returns a generator over the spaces of the board. /// /// - complexity: O(1). public func generate() -> Generator { return Generator(_base: _MutualIterator(self)) } } #endif #if os(OSX) || os(iOS) || os(tvOS) extension Board: CustomPlaygroundQuickLookable { /// Returns the `PlaygroundQuickLook` for `self`. private var _customPlaygroundQuickLook: PlaygroundQuickLook { let spaceSize: CGFloat = 80 let boardSize = spaceSize * 8 let frame = CGRect(x: 0, y: 0, width: boardSize, height: boardSize) let view = _View(frame: frame) #if swift(>=3) for space in self { view.addSubview(space._view(size: spaceSize)) } return .view(view) #else for space in self { view.addSubview(space._view(spaceSize)) } return .View(view) #endif } #if swift(>=3) /// A custom playground quick look for this instance. public var customPlaygroundQuickLook: PlaygroundQuickLook { return _customPlaygroundQuickLook } #else /// Returns the `PlaygroundQuickLook` for `self`. @warn_unused_result public func customPlaygroundQuickLook() -> PlaygroundQuickLook { return _customPlaygroundQuickLook } #endif } #endif /// Returns `true` if both boards are the same. @warn_unused_result public func == (lhs: Board, rhs: Board) -> Bool { return lhs._bitboards == rhs._bitboards } /// Returns `true` if both spaces are the same. @warn_unused_result public func == (lhs: Board.Space, rhs: Board.Space) -> Bool { return lhs.piece == rhs.piece && lhs.file == rhs.file && lhs.rank == rhs.rank }
30.188475
119
0.534219
719f2036c3d9010248d6c54db0b69ce434a1448e
1,773
// // Validation.swift // Inquire // // Created by Wesley Cope on 1/14/16. // Copyright © 2016 Wess Cope. All rights reserved. // import Foundation /// ValidationBlock: Block used to validate string values. public typealias ValidationBlock = (AnyObject) -> Bool /** # Valdation Class used for loading and executing validations for form field values. */ open class Validation { fileprivate func validateWithPattern(_ value:String, pattern:String) -> Bool { if value.characters.count < 0 { return false } do { let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) let matches = regex.matches(in: value, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, value.characters.count)) return matches.count > 0 ? true : false } catch { print("Invalid pattern: \(pattern)") return false } } /** ## Validate Takes a value and a rule to use to validate the value and return if it's valid or note. - returns: Bool - Parameter value:String - Parameter rule:ValidationRule */ open func validate(_ value:String?, rule:ValidationRule) -> Bool { var isValid = true guard let text = value else { return false } if let block = rule.block { isValid = block(text as AnyObject) } if let pattern = rule.pattern { isValid = validateWithPattern(text, pattern: pattern) } return isValid } } /// Global validator to use with fields who have no forms. internal let GlobalValidation:Validation = Validation()
27.276923
156
0.606881
90bec95f58272b998803940322d9430334412a51
617
// // ViewController.swift // PickCreatePod05 // // Created by Supapon Pucknavin on 05/31/2016. // Copyright (c) 2016 Supapon Pucknavin. All rights reserved. // import UIKit import PickCreatePod05 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let pick = PickHelper() pick.pickTestLog() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.035714
80
0.667747
8f7e719a5658472585f5b461174111aea541297f
1,220
// // TIPCALCTests.swift // TIPCALCTests // // Created by Kuljot Singh Chadha on 1/8/22. // import XCTest @testable import TIPCALC class TIPCALCTests: 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. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } 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. } } }
32.972973
130
0.682787
f430112601b2247544a2dfaed4f7d3085822846b
6,914
import UIKit public class RedmineFeedbackReporter: NSObject, FeedbackReportDelegate { public var redmineAddress: String public var apiToken: String public var projectId: String public init(redmineAddress: String, apiToken: String, projectId: String) { self.redmineAddress = redmineAddress self.apiToken = apiToken self.projectId = projectId } public func sendReportFromViewController( activeScreenName: String, callingViewController: UIViewController, image: UIImage, description: String, userName: String) { // Start network indicator and deactivate button if let feedbacVC = callingViewController.presentedViewController as? FeedabackViewController { feedbacVC.sendButton.active = false } UIApplication.sharedApplication().networkActivityIndicatorVisible = true sendImageToRedMine( activeScreenName, viewController: callingViewController, image: image, description: description, userName: userName) } private func sendIssueToRedmine( activeScreenName: String, viewController: UIViewController, description: String, userName: String, token: String) { // Create POST request body let request = NSMutableURLRequest(URL: NSURL(string: "\(redmineAddress)/projects/\(projectId)/issues.json")!) request.HTTPMethod = "POST" request.addValue(apiToken, forHTTPHeaderField: "X-Redmine-API-Key") request.addValue("application/json", forHTTPHeaderField: "Content-Type") var title = "[ShakeReporter" if let userName = ShakeCrash.sharedInstance.userName { title += "] Report from \(userName)" } else { title += "] Report" } let versioNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")! let appBuildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion")! title += ", \(activeScreenName), version \(versioNumber)(\(appBuildNumber))" let params = [ "issue": [ "subject": title, "priority": "4", "description": description, "uploads": [ [ "token": token, "filename": "report_\(NSDate().timeIntervalSince1970).jpeg", "content_type": "image/jpeg" ] ] ] ] do { let json = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted) request.HTTPBody = json } catch { print("Redmine Reporter: crashed while creating parameters") self.showErrorMessage(viewController.presentedViewController, message: "Can't understand issue response") return } // Send it let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil else { print("Redmine Reporter: error = \(error) ") self.showErrorMessage(viewController.presentedViewController, message: "Error while sending issue") return } if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 201 { print("Redmine Reporter: statusCode should be 200, but is \(httpStatus.statusCode) ") print("Redmine Reporter: response = \(response) ") self.showErrorMessage(viewController.presentedViewController, message: "Issue couldn't be added") } // Hide network indicator on success UIApplication.sharedApplication().networkActivityIndicatorVisible = false viewController.presentedViewController?.dismissViewControllerAnimated(true, completion: nil) } task.resume() } private func sendImageToRedMine( activeScreenName: String, viewController: UIViewController, image: UIImage, description: String, userName: String) { // Create POST request body let request = NSMutableURLRequest(URL: NSURL(string: "\(redmineAddress)/uploads.json")!) request.HTTPMethod = "POST" request.addValue(apiToken, forHTTPHeaderField: "X-Redmine-API-Key") request.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type") request.HTTPBody = UIImageJPEGRepresentation(image, 1.0) // Send it let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil else { print("Redmine Reporter: error = \(error) ") self.showErrorMessage(viewController.presentedViewController, message: "Error while sending attachment") return } if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 201 { print("Redmine Reporter: statusCode should be 200, but is \(httpStatus.statusCode) ") print("Redmine Reporter: response = \(response) ") self.showErrorMessage(viewController.presentedViewController, message: "Attachment couldn't be added") } do { if let data = data { let responseJSON = try NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions.MutableContainers) if let upload = responseJSON["upload"], let token = upload?["token"] as? String { self.sendIssueToRedmine( activeScreenName, viewController: viewController, description: description, userName: userName, token: token) } else { print("Redmine Reporter: no photo token in response") self.showErrorMessage(viewController.presentedViewController, message: "No photo attachment in response") } } else { print("Redmine Reporter: no photo data in response") self.showErrorMessage(viewController.presentedViewController, message: "No data in attachment response") } } catch { print("Redmine Reporter: crashed while deserializing") self.showErrorMessage(viewController.presentedViewController, message: "Can't understand attachment response") } } task.resume() } private func showErrorMessage(viewController: UIViewController?, message: String) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.showAlertWithTitle("Issue couldn't be send", message: message, viewController: viewController) } } private func showAlertWithTitle(title: String, message: String, viewController: UIViewController?) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let viewController = viewController { // Hide network indicator on error and activate button if let feedbacVC = viewController as? FeedabackViewController { feedbacVC.sendButton.active = true } // Show allert let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil)) viewController.presentViewController(alert, animated: true, completion: nil) } } }
35.27551
112
0.696124