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
91b14724ea2eae8dc734830cda68be12ac937720
21,075
// // EventDetailTableViewController.swift // PartyShare // // Created by Ashwin Chakicherla on 4/24/20. // Copyright © 2020 Ashwin Chakicherla. All rights reserved. // [email protected] // import UIKit import Firebase import GooglePlaces class EventDetailCell: UITableViewCell { @IBOutlet weak var eventNameText: UILabel! @IBOutlet weak var eventAddressText: UILabel! @IBOutlet weak var eventDateText: UILabel! @IBOutlet weak var eventDescriptionText: UILabel! @IBOutlet weak var eventAttendeesText: UILabel! } class ItemSignupCell: UITableViewCell { @IBOutlet weak var checkmarkImage: UIImageView! @IBOutlet weak var itemText: UILabel! } class EventDetailTableViewController: UITableViewController { var ref: DatabaseReference! var event: Event? var host = false let currUID = Auth.auth().currentUser?.uid var dateString: String? var placesClient: GMSPlacesClient! var headerTitles = ["Event Details", "Item Signups"] var completionHandler: (() -> Void)? var eventPassed = false @IBOutlet weak var topRightButton: UIBarButtonItem! // for alert var quantityValid = false var itemValid = false // removes current event from DB (and deregisters each attendee) func deleteEvent() { guard let eventID = self.event?.eventID else { return } if let attendees = event?.attending { for (key, _) in attendees { ref.child("users").child(key).child("attending").child(eventID).setValue(nil) } } ref.child("events").child(eventID).setValue(nil) _ = self.navigationController?.popViewController(animated: true) if let cH = self.completionHandler { cH() } } // removes reference to current user attending event from DB func leaveEvent() { guard let eventID = self.event?.eventID, let currUID = self.currUID else { return } ref.child("users").child(currUID).child("attending").child(eventID).setValue(nil) ref.child("events").child(eventID).child("attending").child(currUID).setValue(nil) _ = self.navigationController?.popViewController(animated: true) if let cH = self.completionHandler { cH() } } // displays alert for deleting event (HOST ONLY) func displayDeletePopup() { let alert = UIAlertController(title: "Cancel Event?", message: "Are you sure you want to delete this event?", preferredStyle: .alert) let addAction = UIAlertAction(title: "Remove", style: .destructive, handler: { (action: UIAlertAction) -> Void in self.deleteEvent() alert.dismiss(animated: true, completion: nil) }) alert.addAction(addAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } // displays alert for leaving event (USER ONLY) func displayLeavePopup() { let alert = UIAlertController(title: "Leave Event?", message: "Are you sure you want to leave this event?", preferredStyle: .alert) let addAction = UIAlertAction(title: "Remove", style: .destructive, handler: { (action: UIAlertAction) -> Void in self.leaveEvent() alert.dismiss(animated: true, completion: nil) }) alert.addAction(addAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } // if user pressed the trashcan button, decide what to do @IBAction func trashButtonPressed(_ sender: Any) { if host { self.displayDeletePopup() } else { self.displayLeavePopup() } } override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self ref = Database.database().reference() placesClient = GMSPlacesClient.shared() self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 300 guard let currEvent = event, let date = currEvent.date else { return } host = (currEvent.creatorUID == currUID) eventPassed = (date < Date()) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateEvent() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { if eventPassed { return 1 } guard let num = event?.signups?.count else { if host { return 1 } return 0 } if host { return num + 1 } return num } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section < headerTitles.count { return headerTitles[section] } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // display different cells depending on what section (either event details or item details) switch (indexPath.section) { case 0: // if header section let cell = tableView.dequeueReusableCell(withIdentifier: "EventDetailCell", for: indexPath) as! EventDetailCell let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) | UInt(GMSPlaceField.placeID.rawValue))! guard let currEvent = event, let locID = currEvent.locationID, let date = currEvent.date, let name = currEvent.eventName, let desc = currEvent.description else { return cell } cell.eventNameText.text = name placesClient?.fetchPlace(fromPlaceID: locID, placeFields: fields, sessionToken: nil, callback: { (place: GMSPlace?, error: Error?) in if let error = error { print("An error occurred: \(error.localizedDescription)") return } if let place = place { cell.eventAddressText.text = place.name } }) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none dateFormatter.locale = Locale(identifier: "en_US") let timeFormatter = DateFormatter() timeFormatter.dateStyle = .none timeFormatter.timeStyle = .medium timeFormatter.dateFormat = "HH:MM" cell.eventDateText.text = dateFormatter.string(from: date) + " " + timeFormatter.string(from: date) cell.eventDescriptionText.text = desc if let attendees = currEvent.attending { if attendees.count == 0 { cell.eventAttendeesText.text = "1 person going" } else { cell.eventAttendeesText.text = "\(attendees.count + 1) people going!" } } return cell case 1: // if item signup section let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemSignupCell if eventPassed { cell.checkmarkImage.isHidden = true cell.itemText.text = "See Photos" return cell } guard let num = event?.signups?.count else { cell.checkmarkImage.image = UIImage(named: "plus") cell.checkmarkImage.isHidden = false cell.itemText.text = "Add Item" cell.itemText.center = cell.center return cell } if indexPath.row == num { guard let uID = event?.creatorUID else { return cell } if (currUID == uID) { // if last item, make this the "add item" cell cell.checkmarkImage.image = UIImage(named: "plus") cell.checkmarkImage.isHidden = false cell.itemText.text = "Add Item" cell.itemText.center = cell.center } } else { if let signups = event?.signups { let index = signups.index(signups.startIndex, offsetBy: indexPath.row) let itemKey = signups.keys[index] if let item = signups[itemKey] { cell.itemText.text = "\(item["Quantity"] ?? "1") \(itemKey)" cell.checkmarkImage.isHidden = item["userID"] == "null" } } } return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) return cell } } // query DB for new event info (after adding, to update signups map) func updateEvent() { print("QUERYING UPDATED EVENT INFO") let eventRef = ref.child("events").queryOrderedByKey() eventRef.observe(.value, with: { snapshot in for child in snapshot.children { if let snapshot = child as? DataSnapshot, let event = Event(snapshot: snapshot) { if event.eventID == self.event?.eventID { self.event = event } } } self.tableView.reloadData() print("FINISHED QUERYING EVENT INFO") }) } // if text in alert box changed, check if valid @objc func textChanged(_ sender: Any) { let tf = sender as! UITextField var resp : UIResponder! = tf while !(resp is UIAlertController) { resp = resp.next } let alert = resp as! UIAlertController itemValid = (tf.text != "") alert.actions[0].isEnabled = itemValid && quantityValid } // if text in quantity box changed, check if valid @objc func quantityChanged(_ sender: Any) { let tf = sender as! UITextField var resp : UIResponder! = tf while !(resp is UIAlertController) { resp = resp.next } let alert = resp as! UIAlertController quantityValid = false if let text = tf.text { if Int(text) != nil { quantityValid = true } } alert.actions[0].isEnabled = itemValid && quantityValid } // prompts event host to add a new item and quantity to bring func promptAddItem() { let alert = UIAlertController(title: "Add Item", message: "Enter Item and Quantity", preferredStyle: .alert) itemValid = false quantityValid = false alert.addTextField { tf in tf.addTarget(self, action: #selector(self.textChanged), for: .editingChanged) tf.placeholder = "Item" } alert.addTextField { tf in tf.addTarget(self, action: #selector(self.quantityChanged), for: .editingChanged) tf.placeholder = "Quantity" } let addAction = UIAlertAction(title: "Add", style: .default, handler: { (action: UIAlertAction) -> Void in guard let quantity = alert.textFields![1].text else { return } if let q = Int(quantity) { if let i = alert.textFields![0].text { self.addItem(item: i, quantity: q) } } }) alert.addAction(addAction) alert.actions[0].isEnabled = false let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } // adds new item to list in database func addItem(item: String, quantity: Int) { guard let event = self.event, let eventID = event.eventID else { return } let signupsRef = ref.child("events").child(eventID).child("signups") let signup : [AnyHashable : Any] = ["Quantity" : String(quantity), "userID" : "null"] signupsRef.child(item).updateChildValues(signup) } // removes item from database func removeItem(key: String) { if let event = self.event { if let eventID = event.eventID { let itemRef = ref.child("events").child(eventID).child("signups") itemRef.child(key).removeValue() } } } // prompts host to remove given item func promptRemoveItem(key: String) { let alert = UIAlertController(title: "Remove Item?", message: "Are you sure you want to remove \(key)?", preferredStyle: .alert) let addAction = UIAlertAction(title: "Remove", style: .destructive, handler: { (action: UIAlertAction) -> Void in self.removeItem(key: key) alert.dismiss(animated: true, completion: nil) }) alert.addAction(addAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } // explains what to do when a cell is selected override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let row = indexPath.row let section = indexPath.section if eventPassed { if section == 0 { return } if section > 0 { // go to photos performSegue(withIdentifier: "photosPage", sender: self) return } } // only item cells can be clicked if section > 0 { guard let itemCount = event?.signups?.count else { // default, add item only cell (index 1, 1) promptAddItem() return } if (row == itemCount) { promptAddItem() } else { // otherwise we'll need to prompt removing item? if (host) { if let signups = event?.signups { let index = signups.index(signups.startIndex, offsetBy: indexPath.row) let itemKey = signups.keys[index] self.promptRemoveItem(key: itemKey) } } else { if let signups = event?.signups { let index = signups.index(signups.startIndex, offsetBy: indexPath.row) let itemKey = signups.keys[index] if let currUID = self.currUID { if signups[itemKey]?["userID"] == "null" { self.promptSignUpForItem(key: itemKey) } else if signups[itemKey]?["userID"] == currUID { self.promptUnSignUpForItem(key: itemKey) } } } } } } } // registers user as bringing given item func registerItem(key: String) { if let event = self.event { if let currUID = self.currUID { if let eventID = event.eventID { let dbRef = ref.child("events").child(eventID).child("signups").child(key) dbRef.updateChildValues(["userID": currUID]) } } } } // prompts user to register to bring given item func promptSignUpForItem(key: String) { let alert = UIAlertController(title: "Sign Up For Item?", message: "Are you sure you want to sign up for \(key)?", preferredStyle: .alert) let addAction = UIAlertAction(title: "Sign Up", style: .default, handler: { (action: UIAlertAction) -> Void in self.registerItem(key: key) alert.dismiss(animated: true, completion: nil) }) alert.addAction(addAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } // unregisters user from bringing given item func unregisterItem(key: String) { if let event = self.event { if let eventID = event.eventID { let dbRef = ref.child("events").child(eventID).child("signups").child(key) dbRef.updateChildValues(["userID": "null"]) } } } // prompts user to unregister for bringing given item func promptUnSignUpForItem(key: String) { let alert = UIAlertController(title: "Remove Item?", message: "Are you sure you don't want to bring \(key)?", preferredStyle: .alert) let addAction = UIAlertAction(title: "Remove", style: .destructive, handler: { (action: UIAlertAction) -> Void in self.unregisterItem(key: key) alert.dismiss(animated: true, completion: nil) }) alert.addAction(addAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) updateEvent() self.tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. segue.destination.modalPresentationStyle = .fullScreen if segue.identifier == "editEvent" { let createEventViewController = segue.destination as! CreateEventViewController if let event = self.event, let eventName = event.eventName, let desc = event.description, let locID = event.locationID, let date = event.date { createEventViewController.userIsEditing = true // createEventViewController.doneButton.setTitle("Save Changes", for: .normal) createEventViewController.eventName = eventName createEventViewController.eventDesc = desc createEventViewController.locationID = locID createEventViewController.eventDate = date } } else if segue.identifier == "photosPage" { let imageCollectionViewController = segue.destination as! ImageCollectionViewController imageCollectionViewController.eventID = event?.eventID } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if !eventPassed && identifier == "editEvent" { return true } else if identifier == "photosPage" { return true } return false } }
36.149228
155
0.55777
2f9338eeb33625fef663aff4318ade1959132a75
6,423
// // ViewController.swift // TipTastic // // Created by YINYEE LAI on 9/17/16. // Copyright © 2016 Yin Yee Lai. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var totalTitleLabel: UILabel! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var tipPlusLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billTipView: UIView! @IBOutlet weak var totalView: UIView! @IBOutlet weak var NavItem: UIBarButtonItem! var defaults = UserDefaults.standard var tipPercentages = [0.18, 0.20, 0.25] override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.onApplicationDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.onApplicationWillResignActive), name: .UIApplicationWillResignActive, object: nil) totalView.transform = CGAffineTransform(translationX: 0, y: 500) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let intValue = defaults.integer(forKey: "defaultTipIndex") tipControl.selectedSegmentIndex = intValue updateTipAndTotalAmounts() billField.becomeFirstResponder() let isDarkTheme = defaults.bool(forKey: "darkThemeOn") setTheme(isDark: isDarkTheme) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func onApplicationDidBecomeActive(){ let savedDate = defaults.object(forKey: "saveDate") as? Date ?? Date.init() if isResetAmount(lastSavedDate: savedDate) { resetAmount() } else { loadState() updateTipAndTotalAmounts() } } func onApplicationWillResignActive() { saveState(bill: billField.text!, tipPercentageIndex: tipControl.selectedSegmentIndex) } deinit { NotificationCenter.default.removeObserver(self, name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: .UIApplicationWillResignActive, object: nil) } @IBAction func calculateTip(_ sender: AnyObject) { animateTotalView() updateTipAndTotalAmounts() } func animateTotalView() { let bill = Double(billField.text!) ?? 0 if (bill == 0) { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.totalView.transform = CGAffineTransform(translationX: 0, y: 500)}, completion: nil) } else { UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseOut, animations: { self.totalView.transform = CGAffineTransform.init(scaleX: 1, y: 1)}, completion: nil) } } func updateTipAndTotalAmounts() { let bill = Double(billField.text!) ?? 0 let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip tipLabel.text = formatAmount(amt: tip) totalLabel.text = formatAmount(amt: total) } func saveState(bill: String, tipPercentageIndex: Int) { defaults.setValue(Date.init(), forKeyPath: "dateSaved") defaults.setValue(bill, forKeyPath: "bill") defaults.setValue(tipPercentageIndex, forKeyPath: "tipPercentageIndex") defaults.synchronize(); } func loadState() { let bill = defaults.string(forKey: "bill") let tipPercentage = defaults.integer(forKey: "tipPercentageIndex") billField.text = bill tipControl.selectedSegmentIndex = tipPercentage } func formatAmount(amt: Double) -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency numberFormatter.usesGroupingSeparator = true return numberFormatter.string(from: NSNumber.init(value: amt))! } func isResetAmount(lastSavedDate: Date) -> Bool { let dateNow = Date.init() let calendar = Calendar.current let minBetween = calendar.dateComponents([.minute], from: lastSavedDate, to: dateNow) return minBetween.minute! > 10 } func resetAmount() { billField.text = "" updateTipAndTotalAmounts() } @IBAction func onTap(_ sender: AnyObject) { view.endEditing(true) } func setTheme(isDark: Bool) { if (isDark) { let BGColor = UIColor.darkGray let TotalBG = UIColor(red:0.25, green:0.25, blue:0.25, alpha:1.0) let TealTint = UIColor(red:0.13, green:0.86, blue:1.00, alpha:1.0) let TextColor = UIColor.white self.view.backgroundColor = BGColor billField.tintColor = TealTint billTipView.backgroundColor = BGColor billField.textColor = TextColor tipLabel.textColor = TextColor tipPlusLabel.textColor = TextColor tipControl.tintColor = TealTint totalView.backgroundColor = TotalBG totalLabel.textColor = TextColor totalTitleLabel.textColor = TextColor } else { let OrangeTint = UIColor(red:1.00, green:0.60, blue:0.00, alpha:1.0) let BGColor = UIColor.white let TotalBG = UIColor(red:1.00, green:0.85, blue:0.65, alpha:1.0) let TextColor = UIColor.black self.view.backgroundColor = BGColor billField.tintColor = UIColor.black billTipView.backgroundColor = BGColor billField.textColor = TextColor tipLabel.textColor = TextColor tipPlusLabel.textColor = TextColor tipControl.tintColor = OrangeTint totalView.backgroundColor = TotalBG totalLabel.textColor = TextColor totalTitleLabel.textColor = TextColor } } }
33.805263
160
0.621672
c1a3e1136b7d15dee6d6f2295686d3ce54acf245
6,286
// // CreateProfileViewController.swift // Duke Shares Lunch // // Created by Paul Dellinger on 12/6/19. // Copyright © 2019 July Guys. All rights reserved. // import UIKit class CreateProfileViewController: UIViewController { @IBOutlet weak var invalidLabel: UILabel! var user: User? @IBOutlet weak var venmoField: UITextField! @IBOutlet weak var majorField: UITextField! @IBOutlet weak var dormField: UITextField! @IBAction func submitAction(_ sender: Any) { validate(completion: { valid in // user = User(name: nameField.text!, email: emailField.text!, password: passwordField.text!, venmo: venmoField.text!, major: majorField.text, dorm: dormField.text) if valid{ DispatchQueue.main.async { self.user?.venmo = self.venmoField.text self.user?.major = self.majorField.text self.user?.dorm = self.dormField.text self.user?.addUser(completion: { user, error in if let error = error{ print(error) return } self.user = user if (self.user?.uid) != nil{ DispatchQueue.main.async{ self.handleSuccessfulCreate() } } else{ DispatchQueue.main.async{ self.showError(error: error ?? "Error creating user in database") } } }) } }else{ DispatchQueue.main.async{ self.showError(error: "Invalid fields\nDo you have an uppercase letter and digit in your password?") } } }) } override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target:self.view, action: #selector(self.view.endEditing)) view.addGestureRecognizer(tap) // Do any additional setup after loading the view. } func validate(completion: @escaping (_ ok: Bool)-> ()){ let venmo = venmoField.text ?? "" let dorm = dormField.text ?? "No dorm" let major = majorField.text ?? "No Major" /* if password != passwordConfirm { return false } */ /* if !regexIt(text: email, regex: try! NSRegularExpression(pattern: "^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$")){ //invalid email return false } if !regexIt(text: password, regex: try! NSRegularExpression(pattern:"^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z-_\\d]{6,30}$")){ //invalid password return false } */ if !regexIt(text: venmo, regex: try! NSRegularExpression(pattern:"^(?=.*[a-z])[a-zA-Z-_\\d]{6,30}$")){ //invalid venmo completion(false) return } if !dorm.isEmpty{ if !regexIt(text: dorm, regex: try! NSRegularExpression(pattern:"^(?=.*[a-z])[ a-zA-Z-_\\d]{0,50}$")){ //invalid dorm completion(false) return } } if !major.isEmpty{ if !regexIt(text: major, regex: try! NSRegularExpression(pattern:"^(?=.*[a-z])[ a-zA-Z-_\\d]{0,50}$")){ //invalid name completion(false) return } } var request = URLRequest(url: URL(string: "https://venmo.com/\(venmo)")!,timeoutInterval: Double.infinity) request.httpMethod = "HEAD" let task = URLSession.shared.dataTask(with: request) { data, response, error in if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200{ //user exists on venmo completion(true) return } else{ completion(false) return } } else{ completion(false) return } } task.resume() // TODO: verify venmo account exists } func regexIt(text: String, regex: NSRegularExpression)-> Bool{ //returns true if the string matches the regex let range = NSRange(location: 0, length: text.utf16.count) if regex.firstMatch(in: text, options: [], range: range) == nil { return false } return true } func handleSuccessfulCreate(){ //print(user?.token, "Token create page received") performSegue(withIdentifier: "createProfileSegue", sender: self) } func handleDatabaseCreateFail(){ showError(error: "Couldn't create user in database") } func showError(error: String) { let animationDuration = 0.25 // Fade in the view self.invalidLabel.text = error UIView.animate(withDuration: animationDuration, animations: { () -> Void in self.invalidLabel.alpha = 1 }) { (Bool) -> Void in // After the animation completes, fade out the view after a delay UIView.animate(withDuration: animationDuration, delay: 5, animations: { () -> Void in self.invalidLabel.alpha = 0 }, completion: nil) } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. guard let nextController = segue.destination as? TabController else { return } nextController.user = user } }
35.314607
201
0.505886
64902c9f719de236dfaa56fdb4a6a4c2415b1898
721
// // Notifications.swift // HackIllinois // // Created by HackIllinois Team on 1/4/19. // Copyright © 2019 HackIllinois. All rights reserved. // This file is part of the Hackillinois iOS App. // The Hackillinois iOS App is open source software, released under the University of // Illinois/NCSA Open Source License. You should have received a copy of // this license in a file with the distribution. // import Foundation extension Notification.Name { static let themeDidChange = Notification.Name("HINotificationThemeDidChange") static let loginUser = Notification.Name("HIApplicationStateControllerLoginUser") static let logoutUser = Notification.Name("HIApplicationStateControllerLogoutUser") }
36.05
87
0.769764
abbfa52d3c73eaff88c5276cdd417af92c7e6de9
544
// // ViewController.swift // ORCommonUI-Swift // // Created by Egor Lindberg on 12/29/2020. // Copyright (c) 2020 Egor Lindberg. All rights reserved. // import UIKit import ORCommonUI_Swift 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. } }
20.923077
80
0.685662
4869b7efd16889141ac5ac21d7c1e70aa266c6e6
5,014
// // SearchViewModel.swift // MVVM Movie App // // Created by Rafsan Ahmad on 18/04/2021. // Copyright © 2021 R.Ahmad. All rights reserved. // import RxSwift import RxCocoa final class SearchViewModel: ViewModelType { struct Input { let searchText: Driver<String> let selectedCategoryIndex: Driver<Int> let selected: Driver<IndexPath> } struct Output { let switchHidden: Driver<Bool> let loading: Driver<Bool> let results: Driver<[SearchResultItemViewModel]> let selectedDone: Driver<Void> } struct Dependencies { let api: TMDBApiProvider let navigator: SearchNavigatable } private let dependencies: Dependencies init(dependencies: Dependencies) { self.dependencies = dependencies } func transform(input: SearchViewModel.Input) -> SearchViewModel.Output { let activityIndicator = ActivityIndicator() let loading = activityIndicator.asDriver() let query = input.searchText .asObservable() .filter { $0.count >= 3 } .throttle(0.5, scheduler: MainScheduler.instance) let selectedCategoryIndex = input.selectedCategoryIndex .asObservable() .map { index in return index == 0 ? SearchResultItemType.movies : SearchResultItemType.people } let results = Observable.combineLatest(query, selectedCategoryIndex) .flatMapLatest { pair -> Observable<[SearchResultItem]> in let (query, type) = pair switch type { case .movies: return self.dependencies.api.searchMovies(forQuery: query) .trackActivity(activityIndicator) .map { movies -> [SearchResultItem] in guard let movies = movies else { return [] } return movies.map { SearchResultItem(movie: $0) } } case .people: return self.dependencies.api.searchPeople(forQuery: query) .trackActivity(activityIndicator) .map { people -> [SearchResultItem] in guard let people = people else { return [] } return people.map { SearchResultItem(person: $0) } } } } let emptyResults = input.searchText .asObservable() .filter { $0.count < 3 } .map { _ in return [SearchResultItem]() } let mappedResults = Observable.merge(results, emptyResults) .map { $0.map { SearchResultItemViewModel(searchResultItem: $0) }} .asDriver(onErrorJustReturn: []) let switchHidden = input.searchText .map { $0.count < 3 } let selectedDone = input.selected .asObservable() .withLatestFrom(Observable.merge(results, emptyResults)) { indexPath, results in return results[indexPath.row] } .do(onNext: { [weak self] result in guard let strongSelf = self else { return } switch result.type { case .movies: strongSelf.dependencies.navigator.navigateToMovieDetailScreen(withMovieId: result.id, api: strongSelf.dependencies.api) case .people: print("Not implemented.") } }) .map { _ in return () } .asDriver(onErrorJustReturn: ()) return Output(switchHidden: switchHidden, loading: loading, results: mappedResults, selectedDone: selectedDone) } } enum SearchResultItemType { case movies, people } struct SearchResultItem { let id: Int let title: String let subtitle: String let imageUrl: String? let type: SearchResultItemType } struct SearchResultItemViewModel { let title: String let subtitle: String let imageUrl: String? } extension SearchResultItem { init(movie: Movie) { self.id = movie.id self.title = movie.title self.subtitle = movie.overview self.imageUrl = movie.posterUrl.flatMap { "http://image.tmdb.org/t/p/w185/" + $0 } self.type = .movies } init(person: Person) { self.id = person.id self.title = person.name self.subtitle = person.knownForTitles?.first ?? " " self.imageUrl = person.profileUrl.flatMap { "http://image.tmdb.org/t/p/w185/" + $0 } self.type = .people } } extension SearchResultItemViewModel { init(searchResultItem: SearchResultItem) { self.title = searchResultItem.title self.subtitle = searchResultItem.subtitle self.imageUrl = searchResultItem.imageUrl } }
33.426667
125
0.565816
3306fb525fa92adce709ab04b1e21a43fd697612
7,888
// // SelectSavingsOptionsViewController.swift // cryptolin // // Created by Olayemi Abimbola on 24/10/2021. // import UIKit import SwiftUI class SelectSavingsOptionsViewController: UIViewController { @IBOutlet weak var largeContentContainerView: UIView! @IBOutlet weak var smallContentContainerView: UIView! @IBOutlet weak var faqTextLabel: UILabel! @IBOutlet weak var earningRatingBadgeLabel: UIView! @IBOutlet weak var segmentedCtrl: UISegmentedControl! @IBOutlet weak var proceedBtn: UIButton! @IBOutlet weak var percentageViewTop: UILabel! @IBOutlet weak var percentageViewBottom: UILabel! static let storyboardId = String(describing: SelectSavingsOptionsViewController.self) let attributedOriginalText = NSMutableAttributedString(string: "Take a look at the frequently asked questions (FAQs) about our savings option Click here") lazy var linkRange = attributedOriginalText.mutableString.range(of: "Click here") lazy var fullRange = NSMakeRange(0, attributedOriginalText.length) let backgroundImage: UIImage = { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(UIColor(named: "myDarkYellow")?.cgColor ?? UIColor.yellow.cgColor) context!.fill(rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image! }() let separatorBackgroundImage: UIImage = { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(UIColor.black.cgColor); context!.fill(rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image! }() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Select Savings Option" let backBarButtton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) navigationController?.navigationBar.topItem?.backBarButtonItem = backBarButtton setUpUI() let tapGR = UITapGestureRecognizer(target: self, action: #selector(self.tapLabel(gesture:))) faqTextLabel.addGestureRecognizer(tapGR) proceedBtn.addTarget(self, action: #selector(presentAddFundsView(button:)), for: .touchUpInside) } @objc func presentAddFundsView(button: UIButton){ guard let vc = storyboard?.instantiateViewController(withIdentifier: SavingsAddFundsViewController.storyboardId) as? SavingsAddFundsViewController else{ fatalError("Couldn't create SavingsAddFundsViewController view") } navigationController?.pushViewController(vc, animated: true) } func setUpUI(){ largeContentContainerView.layer.cornerRadius = 8 largeContentContainerView.layer.borderWidth = 1 largeContentContainerView.layer.borderColor = UIColor.lightGray.cgColor largeContentContainerView.clipsToBounds = true proceedBtn.layer.cornerRadius = 4 smallContentContainerView.layer.cornerRadius = 4 customizeSegmentedCtrl() roundViewBottom() setUpfaqTextLabel() } func customizeSegmentedCtrl(){ segmentedCtrl.layer.borderColor = UIColor.black.cgColor segmentedCtrl.layer.cornerRadius = 2 segmentedCtrl.layer.borderWidth = 1 segmentedCtrl.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner] segmentedCtrl.backgroundColor = .clear segmentedCtrl.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default) segmentedCtrl.setBackgroundImage(backgroundImage, for: .selected, barMetrics: .default) segmentedCtrl.setDividerImage(separatorBackgroundImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default) UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 2 segmentedCtrl.addTarget(self, action: #selector(segmentedControlValueChanged(sender:)), for: .valueChanged) } func roundViewBottom(){ earningRatingBadgeLabel.layer.cornerRadius = 6 earningRatingBadgeLabel.layer.maskedCorners = [.layerMinXMaxYCorner] } @objc func segmentedControlValueChanged(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { setPercentage("+0.8%") } if sender.selectedSegmentIndex == 1 { setPercentage("+3.0%") } if sender.selectedSegmentIndex == 2 { setPercentage("+7.0%") } if sender.selectedSegmentIndex == 3 { setPercentage("+15.0%") } } func setPercentage(_ percentage: String){ percentageViewTop.text = percentage percentageViewBottom.text = percentage } func setUpfaqTextLabel(){ let style = NSMutableParagraphStyle() style.alignment = .left attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: "", range: linkRange) attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange) attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: linkRange) attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 14), range: fullRange) self.faqTextLabel.attributedText = attributedOriginalText } @objc func tapLabel(gesture: UITapGestureRecognizer) { if gesture.didTapAttributedTextInLabel(label: faqTextLabel, inRange: linkRange) { print("Tapped targetRange1") navigationController?.pushViewController(SavingsFAQCollectionViewController(), animated: true) }else { print("Tapped none") } } } extension UITapGestureRecognizer { func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool { // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage let layoutManager = NSLayoutManager() let textContainer = NSTextContainer(size: CGSize.zero) let textStorage = NSTextStorage(attributedString: label.attributedText!) // Configure layoutManager and textStorage layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) // Configure textContainer textContainer.lineFragmentPadding = 0.0 textContainer.lineBreakMode = label.lineBreakMode textContainer.maximumNumberOfLines = label.numberOfLines let labelSize = label.bounds.size textContainer.size = labelSize // Find the tapped character location and compare it to the specified range let locationOfTouchInLabel = self.location(in: label) let textBoundingBox = layoutManager.usedRect(for: textContainer) let textContainerOffset = CGPoint( x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y ) let locationOfTouchInTextContainer = CGPoint( x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y ) let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) return NSLocationInRange(indexOfCharacter, targetRange) } }
42.637838
162
0.700304
ffc6a8eaf3db3c079e849d1aeb7f58e3ce5dd7e7
7,159
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: ARC.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ //https://developers.google.com/protocol-buffers/docs/proto3 //https://github.com/apple/swift-protobuf/blob/master/Documentation/PLUGIN.md import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } enum ARC_ImageEncoding: SwiftProtobuf.Enum { typealias RawValue = Int case h264 // = 0 ///aka H265 case hevc // = 1 case jpg // = 2 case png // = 3 case rawYuv // = 4 case rawRgb // = 5 case rawYcbcr // = 6 case UNRECOGNIZED(Int) init() { self = .h264 } init?(rawValue: Int) { switch rawValue { case 0: self = .h264 case 1: self = .hevc case 2: self = .jpg case 3: self = .png case 4: self = .rawYuv case 5: self = .rawRgb case 6: self = .rawYcbcr default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .h264: return 0 case .hevc: return 1 case .jpg: return 2 case .png: return 3 case .rawYuv: return 4 case .rawRgb: return 5 case .rawYcbcr: return 6 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension ARC_ImageEncoding: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [ARC_ImageEncoding] = [ .h264, .hevc, .jpg, .png, .rawYuv, .rawRgb, .rawYcbcr, ] } #endif // swift(>=4.2) struct ARC_WrappedMessage { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var wrappedMessage: ARC_WrappedMessage.OneOf_WrappedMessage? = nil var colorImage: ARC_ColorImage { get { if case .colorImage(let v)? = wrappedMessage {return v} return ARC_ColorImage() } set {wrappedMessage = .colorImage(newValue)} } var unknownFields = SwiftProtobuf.UnknownStorage() enum OneOf_WrappedMessage: Equatable { case colorImage(ARC_ColorImage) #if !swift(>=4.1) static func ==(lhs: ARC_WrappedMessage.OneOf_WrappedMessage, rhs: ARC_WrappedMessage.OneOf_WrappedMessage) -> Bool { switch (lhs, rhs) { case (.colorImage(let l), .colorImage(let r)): return l == r } } #endif } init() {} } struct ARC_ColorImage { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var imageEncoding: ARC_ImageEncoding = .h264 var imageHeader: [Data] = [] var imageData: Data = SwiftProtobuf.Internal.emptyData var timestampInSeconds: Double = 0 var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. extension ARC_ImageEncoding: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "H264"), 1: .same(proto: "HEVC"), 2: .same(proto: "JPG"), 3: .same(proto: "PNG"), 4: .same(proto: "RAW_YUV"), 5: .same(proto: "RAW_RGB"), 6: .same(proto: "RAW_YCBCR"), ] } extension ARC_WrappedMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "ARC_WrappedMessage" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "color_image"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: var v: ARC_ColorImage? if let current = self.wrappedMessage { try decoder.handleConflictingOneOf() if case .colorImage(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {self.wrappedMessage = .colorImage(v)} default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if case .colorImage(let v)? = self.wrappedMessage { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ARC_WrappedMessage, rhs: ARC_WrappedMessage) -> Bool { if lhs.wrappedMessage != rhs.wrappedMessage {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension ARC_ColorImage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "ARC_ColorImage" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "image_encoding"), 2: .standard(proto: "image_header"), 3: .standard(proto: "image_data"), 4: .standard(proto: "timestamp_in_seconds"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularEnumField(value: &self.imageEncoding) case 2: try decoder.decodeRepeatedBytesField(value: &self.imageHeader) case 3: try decoder.decodeSingularBytesField(value: &self.imageData) case 4: try decoder.decodeSingularDoubleField(value: &self.timestampInSeconds) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.imageEncoding != .h264 { try visitor.visitSingularEnumField(value: self.imageEncoding, fieldNumber: 1) } if !self.imageHeader.isEmpty { try visitor.visitRepeatedBytesField(value: self.imageHeader, fieldNumber: 2) } if !self.imageData.isEmpty { try visitor.visitSingularBytesField(value: self.imageData, fieldNumber: 3) } if self.timestampInSeconds != 0 { try visitor.visitSingularDoubleField(value: self.timestampInSeconds, fieldNumber: 4) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ARC_ColorImage, rhs: ARC_ColorImage) -> Bool { if lhs.imageEncoding != rhs.imageEncoding {return false} if lhs.imageHeader != rhs.imageHeader {return false} if lhs.imageData != rhs.imageData {return false} if lhs.timestampInSeconds != rhs.timestampInSeconds {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
30.594017
130
0.697164
0a5a60bd76dd61bbf614d4f2abe9c04f62ed5a85
1,157
// // Extensions.swift // CookieCrunch // // Created by Matthijs on 19-06-14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import Foundation //扩展 extension Dictionary { // Loads a JSON file from the app bundle into a new dictionary static func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? { if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") { var error: NSError? let data: NSData? = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error) if let data = data { let dictionary: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error) if let dictionary = dictionary as? Dictionary<String, AnyObject> { return dictionary } else { println("Level file '\(filename)' is not valid JSON: \(error!)") return nil } } else { println("Could not load level file: \(filename), error: \(error!)") return nil } } else { println("Could not find level file: \(filename)") return nil } } }
29.666667
129
0.639585
e4084cdf3c487ac6f292a3bc6709ae0c8d8eef69
864
// // SZHomeViewController.swift // RxDMXMLY // // Created by chaobi on 2018/4/16. // Copyright © 2018年 Sidney. All rights reserved. // import UIKit class SZHomeViewController: SZBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24
106
0.672454
3805e2dab47f0e1ef34b56be3829dcdaa0b6ba9e
1,539
// // WaterSoftenerSettingsViewModel.swift // i2app // // Created by Arcus Team on 6/19/17. /* * Copyright 2019 Arcus Project * * 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 Cornea /* `WaterSoftenerSettingViewModel` struct which conforms to `DeviceMoreItemViewModel` **/ struct WaterSoftenerSettingViewModel: DeviceMoreItemViewModel { var title: String var description: String var info: String? var actionType: DeviceMoreActionType var actionIdentifier: String var cellIdentifier: String var metaData: [String: AnyObject]? init(_ title: String, description: String, info: String?, actionType: DeviceMoreActionType, actionIdentifier: String, cellIdentifier: String, metaData: [String: AnyObject]?) { self.title = title self.description = description self.info = info self.actionType = actionType self.actionIdentifier = actionIdentifier self.cellIdentifier = cellIdentifier self.metaData = metaData } }
28.5
83
0.728395
1a4aa53a88229515f4860b57265e4882f39fde08
4,639
// // AppDelegate.swift // WorkoutMotivation // // Created by Tarang khanna on 5/13/15. // Copyright (c) 2015 Tarang khanna. All rights reserved. // import UIKit import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Parse.setApplicationId("8HWVCwLAEWaLHmXBQ9hKl77YhmfHKPAoiZFJM4Ds", clientKey:"LbugyjO6Pr2GPM5m4JexSCahNMG5e4qjFBq85Yec") // let userNotificationTypes = (UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound) // let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil) // application.registerUserNotificationSettings(settings) // application.registerForRemoteNotifications() PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions) return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { UIApplication.sharedApplication().registerForRemoteNotifications() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // Store the deviceToken in the current Installation and save it to Parse let installation = PFInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) if let userID = PFUser.currentUser()?.objectId { installation["user"] = userID } installation.saveInBackground() } // // func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { // if error.code == 3010 { // println("Push notifications are not supported in the iOS Simulator.") // } else { // println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error) // println(error.localizedDescription) // } // } // // func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // PFPush.handlePush(userInfo) // } // 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. FBSDKAppEvents.activateApp() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
47.824742
285
0.729036
8aa6feb07a2d3bb36923c58fb12bc0c1326c901c
4,747
// // AppDelegate.swift // Beer List // // Created by Amadeu Cavalcante on 05/12/2017. // Copyright © 2017 Amadeu Cavalcante. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let beerList = BeerListWireFrame.createBeerListModule() window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = beerList window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Beer_List") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
48.438776
285
0.686328
f9fb3901f30129d4e851c8c819dacc631ed750b0
2,331
import Foundation /// An endpoint path public struct Path: Decodable { /// The raw path public let path: String /// Type info about the path public let info: Info /// Operations available on the path public var operations: [Operation] /// Path parameters public let parameters: [Parameter]? private static let methodKeys: [CodingKeys] = [.get, .patch, .post, .delete] private enum CodingKeys: String, CodingKey { case get case patch case post case delete case parameters } /** Initialize a new path - Parameters: - path: The raw path - info: Type info about the path - operations: Operations available on the path - parameters: Path parameters */ public init(path: String, info: Info, operations: [Operation], parameters: [Parameter]? = nil) { self.path = path self.info = info self.operations = operations self.parameters = parameters } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let path = container.codingPath.last!.stringValue let operations = try Self.methodKeys.compactMap { try container.decodeIfPresent(Operation.self, forKey: $0) } let parameters = try container.decodeIfPresent([Parameter].self, forKey: .parameters) let pathComponents = path.components(separatedBy: "/") let mainType = pathComponents.first { $0 != "v1" && $0 != "" }! .capitalizingFirstLetter() .singularized() let isRelationship = pathComponents.count > 4 let info = Info(mainType: mainType, isRelationship: isRelationship) self.init(path: path, info: info, operations: operations, parameters: parameters) } /// Type info about a path public struct Info: Equatable { /// The main type of the path public let mainType: String /// Is the path accessing a relationship public let isRelationship: Bool } /// A parameter for a path public struct Parameter: Decodable, Equatable { /// The name of the paramter public let name: String /// A short description of what the parameter is public let description: String } }
33.3
117
0.634492
615c7c2199994f73729afd8d03e9be72882be531
5,314
// // GKBasePageViewController.swift // GKPageScrollViewSwift // // Created by gaokun on 2019/2/21. // Copyright © 2019 gaokun. All rights reserved. // import UIKit import JXSegmentedView import GKPageScrollView public let kRefreshDuration = 0.5 public let kBaseHeaderHeight = kScreenW * 385.0 / 704.0 public let kBaseSegmentHeight: CGFloat = 40.0 class GKBasePageViewController: GKDemoBaseViewController { lazy var headerView: UIImageView! = { let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kBaseHeaderHeight)) imgView.contentMode = .scaleAspectFill imgView.clipsToBounds = true imgView.image = UIImage(named: "test") return imgView }() lazy var pageView: UIView! = { let pageView = UIView() pageView.addSubview(self.segmentedView) pageView.addSubview(self.contentScrollView) return pageView }() lazy var childVCs: [GKBaseListViewController] = { var childVCs = [GKBaseListViewController]() childVCs.append(GKBaseListViewController(listType: .UITableView)) childVCs.append(GKBaseListViewController(listType: .UICollectionView)) childVCs.append(GKBaseListViewController(listType: .UIScrollView)) childVCs.append(GKBaseListViewController(listType: .WKWebView)) return childVCs }() var titleDataSource = JXSegmentedTitleDataSource() public var pageScrollView: GKPageScrollView! public lazy var segmentedView: JXSegmentedView = { titleDataSource.titles = ["TableView", "CollectionView", "ScrollView", "WebView"] titleDataSource.titleNormalColor = UIColor.gray titleDataSource.titleSelectedColor = UIColor.red titleDataSource.titleNormalFont = UIFont.systemFont(ofSize: 15.0) titleDataSource.titleSelectedFont = UIFont.systemFont(ofSize: 15.0) titleDataSource.reloadData(selectedIndex: 0) var segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kBaseSegmentHeight)) segmentedView.delegate = self segmentedView.dataSource = titleDataSource let lineView = JXSegmentedIndicatorLineView() lineView.lineStyle = .normal lineView.indicatorHeight = ADAPTATIONRATIO * 4.0 lineView.verticalOffset = ADAPTATIONRATIO * 2.0 segmentedView.indicators = [lineView] segmentedView.contentScrollView = self.contentScrollView let btmLineView = UIView() btmLineView.backgroundColor = UIColor.grayColor(g: 110) segmentedView.addSubview(btmLineView) btmLineView.snp.makeConstraints({ (make) in make.left.right.bottom.equalTo(segmentedView) make.height.equalTo(ADAPTATIONRATIO * 2.0) }) return segmentedView }() lazy var contentScrollView: UIScrollView = { let scrollW = kScreenW let scrollH = kScreenH - GKPage_NavBar_Height - kBaseSegmentHeight let scrollView = UIScrollView(frame: CGRect(x: 0, y: kBaseSegmentHeight, width: scrollW, height: scrollH)) scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.bounces = false if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } for (index, vc) in self.childVCs.enumerated() { self.addChild(vc) scrollView.addSubview(vc.view) vc.view.frame = CGRect(x: CGFloat(index) * scrollW, y: 0, width: scrollW, height: scrollH) } scrollView.contentSize = CGSize(width: CGFloat(self.childVCs.count) * scrollW, height: 0) return scrollView }() override func viewDidLoad() { super.viewDidLoad() self.gk_navTitleColor = UIColor.white self.gk_navTitleFont = UIFont.boldSystemFont(ofSize: 18) self.gk_navBackgroundColor = UIColor.clear self.gk_statusBarStyle = .lightContent pageScrollView = GKPageScrollView(delegate: self) self.view.addSubview(pageScrollView) pageScrollView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } } } extension GKBasePageViewController: JXSegmentedViewDelegate { } extension GKBasePageViewController: GKPageScrollViewDelegate { func headerView(in pageScrollView: GKPageScrollView) -> UIView { return headerView } func pageView(in pageScrollView: GKPageScrollView) -> UIView { return pageView } func listView(in pageScrollView: GKPageScrollView) -> [GKPageListViewDelegate] { return childVCs } } extension GKBasePageViewController: UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.pageScrollView.horizonScrollViewWillBeginScroll() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.pageScrollView.horizonScrollViewDidEndedScroll() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.pageScrollView.horizonScrollViewDidEndedScroll() } }
34.732026
115
0.672375
1de73b767e5ba1ea6dda6bed0f52aa5644011305
2,532
// // SceneDelegate.swift // BackgroundTasksPOC // // Created by iragam reddy, sreekanth reddy on 11/22/20. // import UIKit import BackgroundTasks class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // flushDataBackground() (UIApplication.shared.delegate as! AppDelegate).startBGProcessingTask() (UIApplication.shared.delegate as! AppDelegate).startBGAppRefreshTask() } }
46.036364
147
0.718404
6140e572d2ab8be3ce2d35b0b8548656bb1c7999
18,950
/* © Copyright 2020, The Great Rift Valley Software Company LICENSE: MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The Great Rift Valley Software Company: https://riftvalleysoftware.com */ import Cocoa import RVS_BlueThoth_MacOS /* ###################################################################################################################################### */ // MARK: - The Characteristic Screen View Controller - /* ###################################################################################################################################### */ /** This controls the screen for a selected Characteristic. It appears in the screen just to the right of the Peripheral Screen. */ class RVS_BlueThoth_Test_Harness_MacOS_CharacteristicViewController: RVS_BlueThoth_MacOS_Test_Harness_Base_SplitView_ViewController { /* ################################################################## */ /** This is the storyboard ID that we use to create an instance of this view. */ static let storyboardID = "characteristic-view-controller" /* ################################################################## */ /** This is a carriage return/linefeed pair, which will always be used in place of a simple CR or LF, alone. */ private static let _crlf = "\r\n" /* ################################################################## */ /** This is the initial width of the new section. */ static let minimumThickness: CGFloat = 400 /* ################################################################## */ /** This is the read button. Selecting this, sends a read command to the Peripheral. */ @IBOutlet weak var readButton: NSButton! /* ################################################################## */ /** This checkbox controls the notification state for the Characteristic. */ @IBOutlet weak var notifyButton: NSButton! /* ################################################################## */ /** This is an indicator for indication. */ @IBOutlet weak var indicateLabel: NSTextField! /* ################################################################## */ /** This is the label that says there are extended attributes in a Descriptor. */ @IBOutlet weak var extendedLabel: NSTextField! /* ################################################################## */ /** This is the stack view that wraps the read header items. */ @IBOutlet weak var readHeaderStackView: NSStackView! /* ################################################################## */ /** This is the label for the Read Value text area. */ @IBOutlet weak var valueTextFieldLabel: NSTextFieldCell! /* ################################################################## */ /** This is the wrapper for the value text area. */ @IBOutlet weak var valueTextViewContainer: NSTextField! /* ################################################################## */ /** This is the actual text item for the value text area. */ @IBOutlet weak var valueTextView: NSTextFieldCell! /* ################################################################## */ /** This wraps the write text entry area label. */ @IBOutlet weak var writeTextFieldLabelContainer: NSTextField! /* ################################################################## */ /** This is the actual text item for the write text label. */ @IBOutlet weak var writeTextFieldLabel: NSTextFieldCell! /* ################################################################## */ /** This wraps the text entry text view. */ @IBOutlet weak var writeTextViewContainer: NSScrollView! /* ################################################################## */ /** This is the text entry text view. */ @IBOutlet var writeTextView: NSTextView! /* ################################################################## */ /** This wraps the send buttons. */ @IBOutlet weak var sendButtonContainer: NSView! /* ################################################################## */ /** This is the send (no response) button text. */ @IBOutlet weak var sendButtonText: NSButtonCell! /* ################################################################## */ /** This is the send (with response) button text. */ @IBOutlet weak var sendResponseButtonText: NSButtonCell! /* ################################################################## */ /** This allows you to wipe the value, and start over. */ @IBOutlet weak var refreshButton: NSButton! /* ################################################################## */ /** This stack view will contain any Descriptors. */ @IBOutlet weak var descriptorStackView: NSStackView! /* ################################################################## */ /** This is the Characteristic instance associated with this screen. When this is changed, we wipe the cache. */ var characteristicInstance: CGA_Bluetooth_Characteristic? { didSet { updateUI() } } } /* ###################################################################################################################################### */ // MARK: - IBAction Methods - /* ###################################################################################################################################### */ extension RVS_BlueThoth_Test_Harness_MacOS_CharacteristicViewController { /* ################################################################## */ /** - parameter: ignored */ @IBAction func readButtonHit(_: Any) { valueTextView?.title = "" characteristicInstance?.clearConcatenate(newValue: true) characteristicInstance?.readValue() } /* ################################################################## */ /** - parameter inButton: The Notify checkbox button */ @IBAction func notifyButtonChanged(_ inButton: NSButton) { valueTextView?.title = "" if .on == inButton.state { characteristicInstance?.clearConcatenate(newValue: true) characteristicInstance?.startNotifying() } else { characteristicInstance?.stopNotifying() } } /* ################################################################## */ /** - parameter inButton: used as a flag. If nil, then we are sending with response. */ @IBAction func sendButtonHit(_ inButton: Any! = nil) { if var textToSend = writeTextView?.string { // See if we are to send CRLF as line endings. if prefs.alwaysUseCRLF { textToSend = textToSend.replacingOccurrences(of: "\n", with: Self._crlf).replacingOccurrences(of: "\r", with: Self._crlf) } if let data = textToSend.data(using: .utf8) { let responseValue = nil == inButton #if DEBUG print("Sending \"\(textToSend)\" to the Device") if responseValue { print("\tAnd asking for a response, if possible.") } #endif characteristicInstance?.writeValue(data, withResponseIfPossible: responseValue) } } } /* ################################################################## */ /** - parameter: ignored. */ @IBAction func sendButtonResponseHit(_: Any) { sendButtonHit() } /* ################################################################## */ /** - parameter: ignored. */ @IBAction func refreshButtonHit(_: Any) { characteristicInstance?.clearConcatenate(newValue: true) updateUI() } } /* ###################################################################################################################################### */ // MARK: - Instance Methods - /* ###################################################################################################################################### */ extension RVS_BlueThoth_Test_Harness_MacOS_CharacteristicViewController { /* ################################################################## */ /** This sets up the Descriptor list (if any). */ func setUpDescriptors() { func createLabel(_ inText: String, isHeader: Bool = false) -> NSView { let ret = NSTextField() ret.textColor = .white ret.drawsBackground = false ret.isBordered = false ret.isBezeled = false ret.isEditable = false if isHeader { ret.font = .boldSystemFont(ofSize: 16) } else { ret.font = .systemFont(ofSize: 14) } ret.stringValue = inText return ret } if let characteristicInstance = characteristicInstance, 0 < characteristicInstance.count { descriptorStackView?.arrangedSubviews.forEach { $0.removeFromSuperview() } for descriptor in characteristicInstance { descriptorStackView?.addArrangedSubview(createLabel(descriptor.id.localizedVariant, isHeader: true)) var labelText = "" if let characteristic = descriptor as? CGA_Bluetooth_Descriptor_ClientCharacteristicConfiguration { labelText = "SLUG-ACC-DESCRIPTOR-CLIENTCHAR-NOTIFY-\(characteristic.isNotifying ? "YES" : "NO")".localizedVariant labelText += "SLUG-ACC-DESCRIPTOR-CLIENTCHAR-INDICATE-\(characteristic.isIndicating ? "YES" : "NO")".localizedVariant } if let characteristic = descriptor as? CGA_Bluetooth_Descriptor_Characteristic_Extended_Properties { labelText = "SLUG-ACC-DESCRIPTOR-EXTENDED-RELIABLE-WR-\(characteristic.isReliableWriteEnabled ? "YES" : "NO")".localizedVariant labelText += "SLUG-ACC-DESCRIPTOR-EXTENDED-AUX-WR-\(characteristic.isWritableAuxiliariesEnabled ? "YES" : "NO")".localizedVariant } if let characteristic = descriptor as? CGA_Bluetooth_Descriptor_PresentationFormat { labelText = "SLUG-CHAR-PRESENTATION-\(characteristic.stringValue ?? "255")".localizedVariant } descriptorStackView?.addArrangedSubview(createLabel(labelText)) } descriptorStackView?.isHidden = false } else { descriptorStackView?.isHidden = true } } /* ################################################################## */ /** This sets up the buttons and labels at the top of the screen. */ func setButtonsAndLabelsVisibility() { readButton?.isHidden = !(characteristicInstance?.canRead ?? false) notifyButton?.isHidden = !(characteristicInstance?.canNotify ?? false) indicateLabel?.isHidden = !(characteristicInstance?.canIndicate ?? false) extendedLabel?.isHidden = !(characteristicInstance?.hasExtendedProperties ?? false) } /* ################################################################## */ /** This either shows or hides the read items. */ func setReadItemsVisibility() { if (characteristicInstance?.canNotify ?? false) || (characteristicInstance?.canRead ?? false) { refreshButton?.isHidden = (valueTextView?.title ?? "").isEmpty readHeaderStackView?.isHidden = false valueTextView?.title = characteristicInstance?.stringValue ?? "" } else { readHeaderStackView?.isHidden = true refreshButton?.isHidden = true valueTextViewContainer?.isHidden = true } } /* ################################################################## */ /** This either shows or hides the write items. */ func setWriteItemsVisibility() { if characteristicInstance?.canWrite ?? false { writeTextFieldLabelContainer?.isHidden = false writeTextViewContainer?.isHidden = false sendButtonContainer?.isHidden = false if characteristicInstance?.canWriteWithResponse ?? false { sendResponseButtonText?.controlView?.isHidden = false } else { sendResponseButtonText?.controlView?.isHidden = true } if characteristicInstance?.canWriteWithoutResponse ?? false { sendButtonText?.controlView?.isHidden = false } else { sendButtonText?.controlView?.isHidden = true } } else { writeTextFieldLabelContainer?.isHidden = true writeTextViewContainer?.isHidden = true sendButtonContainer?.isHidden = true } } } /* ###################################################################################################################################### */ // MARK: - Base Class Overrides - /* ###################################################################################################################################### */ extension RVS_BlueThoth_Test_Harness_MacOS_CharacteristicViewController { /* ################################################################## */ /** Called when the view hierachy has loaded. */ override func viewDidLoad() { super.viewDidLoad() readButton?.title = (readButton?.title ?? "ERROR").localizedVariant notifyButton?.title = (notifyButton?.title ?? "ERROR").localizedVariant indicateLabel?.stringValue = (indicateLabel?.stringValue ?? "ERROR").localizedVariant extendedLabel?.stringValue = (extendedLabel?.stringValue ?? "ERROR").localizedVariant sendButtonText?.title = (sendButtonText?.title ?? "ERROR").localizedVariant sendResponseButtonText?.title = (sendResponseButtonText?.title ?? "ERROR").localizedVariant valueTextFieldLabel?.stringValue = (valueTextFieldLabel?.stringValue ?? "ERROR").localizedVariant writeTextFieldLabel?.stringValue = (writeTextFieldLabel?.stringValue ?? "ERROR").localizedVariant notifyButton?.state = (characteristicInstance?.isNotifying ?? false) ? .on : .off setUpAccessibility() } /* ################################################################## */ /** Called just before the screen appears. We use this to register with the app delegate. */ override func viewWillAppear() { super.viewWillAppear() appDelegateObject.screenList.addScreen(self) updateUI() } /* ################################################################## */ /** Called just before the screen disappears. We use this to un-register with the app delegate. */ override func viewWillDisappear() { super.viewWillDisappear() appDelegateObject.screenList.removeScreen(self) } /* ################################################################## */ /** Sets up the various accessibility labels. */ override func setUpAccessibility() { readButton?.setAccessibilityTitle("SLUG-ACC-CHARACTERISTIC-ROW-SLUG-PROPERTIES-READ".localizedVariant) readButton?.toolTip = readButton?.accessibilityTitle() indicateLabel?.setAccessibilityTitle("SLUG-ACC-CHARACTERISTIC-ROW-SLUG-PROPERTIES-INDICATE".localizedVariant) indicateLabel?.toolTip = indicateLabel?.accessibilityTitle() extendedLabel?.setAccessibilityTitle("SLUG-ACC-CHARACTERISTIC-ROW-SLUG-PROPERTIES-EXTENDED".localizedVariant) extendedLabel?.toolTip = extendedLabel?.accessibilityTitle() sendButtonText?.setAccessibilityTitle("SLUG-ACC-SEND-BUTTON".localizedVariant) sendResponseButtonText?.setAccessibilityTitle("SLUG-ACC-SEND-BUTTON-RESPONSE".localizedVariant) valueTextFieldLabel?.setAccessibilityTitle("SLUG-ACC-VALUE".localizedVariant) writeTextFieldLabel?.setAccessibilityTitle("SLUG-ACC-WRITE-VALUE".localizedVariant) refreshButton?.setAccessibilityTitle("SLUG-ACC-REFRESH".localizedVariant) refreshButton?.toolTip = refreshButton?.accessibilityTitle() notifyButton?.setAccessibilityTitle(("SLUG-ACC-CHARACTERISTIC-ROW-SLUG-PROPERTIES-NOTIFY-O" + ((characteristicInstance?.isNotifying ?? false) ? "N" : "FF")).localizedVariant) notifyButton?.toolTip = notifyButton?.accessibilityTitle() } } /* ###################################################################################################################################### */ // MARK: - RVS_BlueThoth_Test_Harness_MacOS_Base_ViewController_Protocol Conformance - /* ###################################################################################################################################### */ extension RVS_BlueThoth_Test_Harness_MacOS_CharacteristicViewController: RVS_BlueThoth_Test_Harness_MacOS_ControllerList_Protocol { /* ################################################################## */ /** This is a String key that uniquely identifies this screen. */ var key: String { characteristicInstance?.id ?? "ERROR" } /* ################################################################## */ /** This forces the UI elements to be updated. */ func updateUI() { setButtonsAndLabelsVisibility() setReadItemsVisibility() setWriteItemsVisibility() setUpDescriptors() setUpAccessibility() } }
43.563218
182
0.510079
1c41e34b2e5789420109489cbaa00f9356ddac7d
212
import Foundation import QuatreD struct ViewState: Equatable { var urls: Favorites.Value } extension ViewState { static func state(_ state: State) -> ViewState { .init(urls: state.urls) } }
16.307692
52
0.679245
f5c4d8ced6689c23295b2d4f1b2db6cd1d564104
3,414
// // Program.swift // Kronos // // Created by Alsey Coleman Miller on 1/20/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(iOS) || os(tvOS) import OpenGLES #endif /// OpenGL Program public struct Program { // MARK: - Properties public let name: GLuint // MARK: - Initialization /// Creates an empty program object. /// ///A program object is an object to which shader objects can be attached. This provides a mechanism to specify the shader objects that will be linked to create a program. It also provides a means for checking the compatibility of the shaders that will be used to create a program (for instance, checking the compatibility between a vertex shader and a fragment shader). When no longer needed as part of a program object, shader objects can be detached. @inline(__always) public init() { self.name = glCreateProgram() assert(self.name != 0, "Could not create program. Error: \(OpenGLError.currentError)") } @inline(__always) public init(name: GLuint) { assert(name != 0) assert(glIsProgram(name).boolValue) self.name = name } // MARK: - Methods /// Installs a program object as part of current rendering state. @inline(__always) static public func setCurrent(program: Program) { glUseProgram(program.name) } /// Attaches a shader to the program. @inline(__always) public func attach(shader: Shader) { glAttachShader(name, shader.name) } /// Detaches a shader from the program. @inline(__always) public func detach(shader: Shader) { glDetachShader(name, shader.name) } /// Links the program object specified by program. /// /// Shader objects of type `GL_VERTEX_SHADER` attached to program are used to create an executable that will run on the programmable vertex processor. /// Shader objects of type `GL_FRAGMENT_SHADER` attached to program are used to create an executable that will run on the programmable fragment processor. /// /// The status of the link operation will be stored as part of the program object's state. /// This value will be set to `GL_TRUE` if the program object was linked without errors and is ready for use, and /// `GL_FALSE` otherwise. It can be queried by calling glGetProgramiv with arguments program and `GL_LINK_STATUS`. @inline(__always) public func link() { glLinkProgram(name) } // MARK: - Accessors /// Get the link status of the program. public var linked: Bool { var linkStatus: GLint = 0 glGetProgramiv(name, GLenum(GL_LINK_STATUS), &linkStatus) return (linkStatus != 0) } /// Gets the info log. public var log: String? { var logLength: GLint = 0 glGetProgramiv(name, GLenum(GL_LINK_STATUS), &logLength) guard logLength > 0 else { return nil } let cString = UnsafeMutablePointer<CChar>(allocatingCapacity: Int(logLength)) defer { cString.deallocateCapacity(Int(logLength)) } glGetProgramInfoLog(name, GLsizei(logLength), nil, cString) return String.init(utf8String: cString)! } }
31.321101
456
0.634446
f48008bd448f2f06753553a1f1458af948630bde
323
// // NSObject+ClassName.swift // Blay // // Created by 張家齊 on 2018/9/10. // Copyright © 2018 Archie All rights reserved. // import Foundation public extension NSObject { public class var className: String { return String(describing: self) } public var className: String { return type(of: self).className } }
21.533333
74
0.69969
28396931493282c3ac09cfdbe86649d6c3ddb38d
548
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `MenuTableViewController` subclass for the "Controls" section of the app. */ import UIKit class ControlsMenuViewController: MenuTableViewController { // MARK: Properties override var segueIdentifierMap: [[String]] { return [ [ "ShowButtons", "ShowProgressViews", "ShowSegmentedControls" ] ] } }
21.92
81
0.594891
e63c1cccd1a4b18b9353e25bc419594061132fe0
1,667
// // DAppViewController.swift // Multi // // Created by Andrew Gold on 7/4/18. // Copyright © 2018 Distributed Systems, Inc. All rights reserved. // import UIKit import WebKit class DAppViewController: UIViewController, WKUIDelegate, WKNavigationDelegate { let dApp: DApp! var webView: WKWebView? init(dApp: DApp) { self.dApp = dApp super.init(nibName: nil, bundle: nil) self.title = dApp.name } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let view = self.view view?.backgroundColor = UIColor.white let webViewConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: CGRect.zero, configuration: webViewConfiguration) webView?.translatesAutoresizingMaskIntoConstraints = false webView?.uiDelegate = self webView?.navigationDelegate = self view!.addSubview(webView!) self.initializeConstraints() webView?.load(URLRequest(url: URL(string: dApp.url!)!)) } private func initializeConstraints() { let layoutGuide = self.view.safeAreaLayoutGuide webView?.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true webView?.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true webView?.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true webView?.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true } }
29.767857
95
0.665267
accc32cde42b514afbebd102644a6cbc3dbd30a9
10,743
// // Button.swift // // // Created by Admin on 8/12/21. // import Foundation import SwiftUI public struct PgUiButton<Label>: View where Label : View { public enum PgUiButtonSize { case small case `default` case large public var FontSize: CGFloat { switch self { case .default: return 20 case .small: return 16 case .large: return 23 } } public var Height: CGFloat { switch self { case .default: return 40 case .small: return 36 case .large: return 44 } } } public enum PgUiButtonWidth: CustomStringConvertible { case `default` case block case full public var description: String{ switch self { case .default: return "Button Default." case .block: return "Button Block width." case .full: return "Button Full display." } } } public enum PgUiButtonStyle: CustomStringConvertible { case `default` case light case lightFill case lightOutline public var description: String{ switch self { case .default: return "" case .light: return "" case .lightOutline: return "" case .lightFill: return "" } } } private var Label: () -> Label private var ColorType: PgUiColor = .default private var Size: PgUiButtonSize = .default private var Width: PgUiButtonWidth = .default private var Style: PgUiButtonStyle = .default private var action: () -> Void private let UISize = UIScreen.main.bounds private var _cornerRadius: CGFloat = 10 public init(action: @escaping () -> Void, ColorType: PgUiColor = .default, Size: PgUiButtonSize = .default, Width: PgUiButtonWidth = .default, Style: PgUiButtonStyle = .default, Radius: CGFloat = 10, @ViewBuilder label: @escaping () -> Label){ self.Label = label self.ColorType = ColorType self.Size = Size self.Width = Width self.Style = Style self._cornerRadius = Radius self.action = action } public var body: some View{ if(self.Width == .default){ if(self.Style == .default){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(height: self.Size.Height, alignment: .center) .background(self.ColorType.Background) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .light){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .lightOutline){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Text, lineWidth: 2)) } if(self.Style == .lightFill){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(height: self.Size.Height, alignment: .center) .background(self.ColorType.Text) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Text, lineWidth: 2)) } } if(self.Width == .block){ GeometryReader { geo in if(self.Style == .default){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(width: geo.size.width, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .light){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(width: geo.size.width, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .lightOutline){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(width: geo.size.width, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Text, lineWidth: 2)) } if(self.Style == .lightFill){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(width: geo.size.width, height: self.Size.Height, alignment: .center) .background(self.ColorType.Text) .cornerRadius(self._cornerRadius) .overlay(RoundedRectangle(cornerRadius: self._cornerRadius) .stroke(self.ColorType.Text, lineWidth: 2)) } } } if(self.Width == .full){ if(self.Style == .default){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(width: UISize.width-10, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background) .overlay(RoundedRectangle(cornerRadius: 0) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .light){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(width: UISize.width-10, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .overlay(RoundedRectangle(cornerRadius: 0) .stroke(self.ColorType.Background, lineWidth: 2)) } if(self.Style == .lightOutline){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Text) .frame(width: UISize.width-10, height: self.Size.Height, alignment: .center) .background(self.ColorType.Background.opacity(0)) .overlay(RoundedRectangle(cornerRadius: 0) .stroke(self.ColorType.Text, lineWidth: 2)) } if(self.Style == .lightFill){ Button(action: self.action){ self.Label() } .font(.system(size: self.Size.FontSize)) .padding(.horizontal, 16) .foregroundColor(self.ColorType.Background) .frame(width: UISize.width-10, height: self.Size.Height, alignment: .center) .background(self.ColorType.Text) .overlay(RoundedRectangle(cornerRadius: 0) .stroke(self.ColorType.Text, lineWidth: 2)) } } } }
38.367857
99
0.488876
f823ee2353520a2779e406827d39759109cd86bc
12,284
/* This source file is part of the Swift.org open source project Copyright (c) 2020-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 Basics @testable import PackageCollections import TSCBasic import TSCTestSupport import TSCUtility import XCTest class PackageCollectionsStorageTests: XCTestCase { func testHappyCase() throws { try testWithTemporaryDirectory { tmpPath in let path = tmpPath.appending(component: "test.db") let storage = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage.close()) } let mockSources = makeMockSources() try mockSources.forEach { source in XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: .init(from: source), callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) } let mockCollections = makeMockCollections(count: 50) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } do { let list = try tsc_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } do { let count = Int.random(in: 1 ..< mockCollections.count) let list = try tsc_await { callback in storage.list(identifiers: mockCollections.prefix(count).map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, count) } do { _ = try tsc_await { callback in storage.remove(identifier: mockCollections.first!.identifier, callback: callback) } let list = try tsc_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1) } XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) guard case .path(let storagePath) = storage.location else { return XCTFail("invalid location \(storage.location)") } XCTAssertTrue(storage.fileSystem.exists(storagePath), "expected file to be written") } } func testFileDeleted() throws { try testWithTemporaryDirectory { tmpPath in let path = tmpPath.appending(component: "test.db") let storage = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } guard case .path(let storagePath) = storage.location else { return XCTFail("invalid location \(storage.location)") } XCTAssertTrue(storage.fileSystem.exists(storagePath), "expected file to exist at \(storagePath)") try storage.fileSystem.removeFileTree(storagePath) storage.resetCache() XCTAssertThrowsError(try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert(error is NotFoundError, "Expected NotFoundError") }) XCTAssertNoThrow(try tsc_await { callback in storage.put(collection: mockCollections.first!, callback: callback) }) let retVal = try tsc_await { callback in storage.get(identifier: mockCollections.first!.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, mockCollections.first!.identifier) XCTAssertTrue(storage.fileSystem.exists(storagePath), "expected file to exist at \(storagePath)") } } func testFileCorrupt() throws { try testWithTemporaryDirectory { tmpPath in let path = tmpPath.appending(component: "test.db") let storage = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } try mockCollections.forEach { collection in let retVal = try tsc_await { callback in storage.get(identifier: collection.identifier, callback: callback) } XCTAssertEqual(retVal.identifier, collection.identifier) } guard case .path(let storagePath) = storage.location else { return XCTFail("invalid location \(storage.location)") } try storage.close() XCTAssertTrue(storage.fileSystem.exists(storagePath), "expected file to exist at \(path)") try storage.fileSystem.writeFileContents(storagePath, bytes: ByteString("blah".utf8)) let storage2 = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage2.close()) } XCTAssertThrowsError(try tsc_await { callback in storage2.get(identifier: mockCollections.first!.identifier, callback: callback) }, "expected error", { error in XCTAssert("\(error)".contains("is not a database"), "Expected file is not a database error") }) XCTAssertThrowsError(try tsc_await { callback in storage2.put(collection: mockCollections.first!, callback: callback) }, "expected error", { error in XCTAssert("\(error)".contains("is not a database"), "Expected file is not a database error") }) } } func testListLessThanBatch() throws { var configuration = SQLitePackageCollectionsStorage.Configuration() configuration.batchSize = 10 let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration) defer { XCTAssertNoThrow(try storage.close()) } let count = configuration.batchSize / 2 let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } let list = try tsc_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } func testListNonBatching() throws { var configuration = SQLitePackageCollectionsStorage.Configuration() configuration.batchSize = 10 let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration) defer { XCTAssertNoThrow(try storage.close()) } let count = Int(Double(configuration.batchSize) * 2.5) let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } let list = try tsc_await { callback in storage.list(callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } func testListBatching() throws { var configuration = SQLitePackageCollectionsStorage.Configuration() configuration.batchSize = 10 let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration) defer { XCTAssertNoThrow(try storage.close()) } let count = Int(Double(configuration.batchSize) * 2.5) let mockCollections = makeMockCollections(count: count) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } let list = try tsc_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } func testPutUpdates() throws { let storage = SQLitePackageCollectionsStorage(location: .memory) defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } let list = try tsc_await { callback in storage.list(identifiers: mockCollections.map { $0.identifier }, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) _ = try tsc_await { callback in storage.put(collection: mockCollections.last!, callback: callback) } XCTAssertEqual(list.count, mockCollections.count) } func testPopulateTargetTrie() throws { try testWithTemporaryDirectory { tmpPath in let path = tmpPath.appending(component: "test.db") let storage = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) try mockCollections.forEach { collection in _ = try tsc_await { callback in storage.put(collection: collection, callback: callback) } } let version = mockCollections.last!.packages.last!.versions.last! let targetName = version.defaultManifest!.targets.last!.name do { let searchResult = try tsc_await { callback in storage.searchTargets(query: targetName, type: .exactMatch, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") } // Create another instance, which should read existing data and populate target trie with it. // Since we are not calling `storage2.put`, there is no other way for target trie to get populated. let storage2 = SQLitePackageCollectionsStorage(path: path) defer { XCTAssertNoThrow(try storage2.close()) } // populateTargetTrie is called in `.init`; call it again explicitly so we know when it's finished do { try tsc_await { callback in storage2.populateTargetTrie(callback: callback) } let searchResult = try tsc_await { callback in storage2.searchTargets(query: targetName, type: .exactMatch, callback: callback) } XCTAssert(searchResult.items.count > 0, "should get results") } catch { // It's possible that some platforms don't have support FTS XCTAssertEqual(false, storage2.useSearchIndices.get(), "populateTargetTrie should fail only if FTS is not available") } } } } extension SQLitePackageCollectionsStorage { convenience init(location: SQLite.Location? = nil, configuration: Configuration = .init()) { self.init(location: location, configuration: configuration, observabilityScope: ObservabilitySystem.NOOP) } convenience init(path: AbsolutePath) { self.init(location: .path(path), observabilityScope: ObservabilitySystem.NOOP) } }
48.172549
172
0.660127
d973b81eb08217cf539df00bb05a420c532abc8d
330
// // DocExampleApp.swift // Shared // // Created by Aaron Wright on 7/25/20. // import SwiftUI @main struct DocExampleApp: App { var body: some Scene { DocumentGroup(newDocument: { DocExampleDocument() }) { file in ContentView(document: file.document) } } }
15
48
0.560606
d53bd186c7af7530ded0f4c5bf5a0691d3650fe8
5,878
// Copyright © 2020 Carousell. All rights reserved. // import SwiftUI import GeofenceKit import Combine struct HomeView: View { @ObservedObject var viewModel: HomeViewModel @State var currentHeight: CGFloat = 0 var body: some View { List { Section(header: Text(viewModel.sectionGeofenceHeader)) { HStack() { Text(viewModel.wifiSsidTitle) TextField(viewModel.wifiSsidPlaceholder, text: $viewModel.wifiSsid) .disabled(viewModel.monitoring) } VStack { Text(viewModel.latitudeTitle) HStack { Text(viewModel.minLatitudeText) Slider( value: $viewModel.latitude, in: viewModel.validLatitudeRanges) .disabled(viewModel.monitoring) Text(viewModel.maxLatitudeText) } } VStack { Text(viewModel.longitudeTitle) HStack { Text(viewModel.minLongitudeText) Slider( value: $viewModel.longitude, in: viewModel.validLongitudeRanges) .disabled(viewModel.monitoring) Text(viewModel.maxLongitudeText) } } VStack { Text(viewModel.radiusTitle) HStack { Text(viewModel.minRadiusText) Slider( value: $viewModel.radius, in: viewModel.validRadiusRanges) .disabled(viewModel.monitoring) Text(viewModel.maxRadiusText) } } Button(viewModel.monitorButtonTitle) { self.viewModel.onTapMonitor() } Button(viewModel.copyUserLocationButtonTitle) { self.viewModel.onTapCopyUserLocation() } } Section(header: Text(viewModel.sectionUserHeader)) { VStack() { Toggle(isOn: $viewModel.userLocationOverride) { Text(viewModel.userOverrideTitle) } HStack() { Text(viewModel.wifiSsidTitle) TextField(viewModel.wifiSsidPlaceholder, text: $viewModel.userWifi) .disabled(!viewModel.userLocationOverride) } VStack { Text(viewModel.userLatitudeTitle) HStack { Text(viewModel.minLatitudeText) Slider( value: $viewModel.userLatitude, in: viewModel.validLatitudeRanges) .disabled(!viewModel.userLocationOverride) Text(viewModel.maxLatitudeText) } } VStack { Text(viewModel.userLongitudeTitle) HStack { Text(viewModel.minLongitudeText) Slider( value: $viewModel.userLongitude, in: viewModel.validLongitudeRanges) .disabled(!viewModel.userLocationOverride) Text(viewModel.maxLongitudeText) } } } if viewModel.title.count > 0 { Text(viewModel.title) } } } .listStyle(GroupedListStyle()) .alert(isPresented: $viewModel.showAlert) { () -> Alert in Alert( title: Text(viewModel.alertType.title), message: Text(viewModel.alertType.text), dismissButton: .cancel(Text("Ok"))) } .padding(.bottom, currentHeight).animation(.easeOut(duration: 0.25)) .edgesIgnoringSafeArea(currentHeight == 0 ? Edge.Set() : .bottom) .onAppear(perform: subscribeToKeyboardChanges) } /* Snippet for Keyboard handling https://forums.developer.apple.com/thread/120763 */ //MARK: - Keyboard Height private let keyboardHeightOnOpening = NotificationCenter.default .publisher(for: UIResponder.keyboardWillShowNotification) .map { $0.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect } .map { $0.height > 333 ? $0.height : 333 } private let keyboardHeightOnHiding = NotificationCenter.default .publisher(for: UIResponder.keyboardWillHideNotification) .map {_ in return CGFloat(0) } //MARK: - Subscriber to Keyboard's changes private func subscribeToKeyboardChanges() { _ = Publishers.Merge(keyboardHeightOnOpening, keyboardHeightOnHiding) .subscribe(on: RunLoop.main) .sink { height in print("Height: \(height)") if self.currentHeight == 0 || height == 0 { self.currentHeight = height } } } } struct HomeView_Previews: PreviewProvider { static var previews: some View { HomeView(viewModel: HomeViewModel( policy: DefaultPolicy(), userLocationProvider: DefaultUserLocationProvider(), overrideUserLocationProvider: DefaultUserLocationProvider())) } }
39.986395
91
0.485029
0a2a383fb65086246acae484422cf6f56baea808
5,998
// // MailBoxViewController.swift // iZSM // // Created by Naitong Yu on 2016/11/23. // Copyright © 2016年 Naitong Yu. All rights reserved. // import UIKit import SmthConnection class MailBoxViewController: BaseTableViewController { private let kMailListCellIdentifier = "MailListCell" var inbox: Bool = true { didSet { title = inbox ? "收件箱" : "发件箱" } } private var mailCountLoaded = 0 private let mailCountPerSection = 20 private var mailRange: NSRange { if mailCountLoaded - mailCountPerSection > 0 { return NSMakeRange(mailCountLoaded - mailCountPerSection, mailCountPerSection) } else { return NSMakeRange(0, mailCountLoaded) } } private var mails: [[SMMail]] = [[SMMail]]() { didSet { tableView?.reloadData() } } override func clearContent() { mails.removeAll() } override func viewDidLoad() { super.viewDidLoad() tableView.register(MailListCell.self, forCellReuseIdentifier: kMailListCellIdentifier) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composeEmail(_:))) } override func fetchDataDirectly(showHUD: Bool, completion: (() -> Void)? = nil) { let completion: SmthCompletion<[SMMail]> = { (result) in DispatchQueue.main.async { networkActivityIndicatorStop(withHUD: showHUD) completion?() switch result { case .success(let mails): self.mailCountLoaded -= mails.count self.mails.removeAll() self.mails.append(mails.reversed()) case .failure(let error): error.display() } } } networkActivityIndicatorStart(withHUD: showHUD) if inbox { api.getMailCount { (result) in if let (totalCount, _, _) = try? result.get() { self.mailCountLoaded = totalCount self.api.getMailList(in: self.mailRange, completion: completion) } } } else { api.getMailCountSent { (result) in if let totalCount = try? result.get() { self.mailCountLoaded = totalCount self.api.getMailSentList(in: self.mailRange, completion: completion) } } } } override func fetchMoreData() { let completion: SmthCompletion<[SMMail]> = { (result) in DispatchQueue.main.async { networkActivityIndicatorStop() switch result { case .success(let mails): self.mailCountLoaded -= mails.count let indexPath = self.tableView.indexPathForSelectedRow self.mails.append(mails.reversed()) if let indexPath = indexPath { self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } case .failure(let error): error.display() } } } networkActivityIndicatorStart() if inbox { api.getMailList(in: mailRange, completion: completion) } else { api.getMailSentList(in: mailRange, completion: completion) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return mails.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mails[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kMailListCellIdentifier, for: indexPath) as! MailListCell let mail = mails[indexPath.section][indexPath.row] // Configure the cell... cell.mail = mail return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if mails.isEmpty { return } if indexPath.section == mails.count - 1 && indexPath.row == mails[indexPath.section].count / 3 * 2 { if mailCountLoaded > 0 { fetchMoreData() } } } @objc private func composeEmail(_ sender: UIBarButtonItem) { let cec = ComposeEmailController() if !inbox { cec.completionHandler = { [unowned self] in self.fetchDataDirectly(showHUD: false) } } let navigationController = NTNavigationController(rootViewController: cec) navigationController.modalPresentationStyle = .formSheet present(navigationController, animated: true) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mcvc = MailContentViewController() let mail = mails[indexPath.section][indexPath.row] mcvc.mail = mail mcvc.inbox = inbox if mail.flags.hasPrefix("N") { var readMail = mail readMail.flags = " " mails[indexPath.section][indexPath.row] = readMail tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) // restore selection let allRead = mails.allSatisfy { $0.allSatisfy { !$0.flags.hasPrefix("N") } } if allRead { MessageCenter.shared.readAllMail() } } showDetailViewController(mcvc, sender: self) } }
35.702381
122
0.565355
deab1fdb5cfd8a56b3f22e4d69544a3108665e14
839
import XCTest import SwiftSyntax import SwiftSyntaxBuilder final class BooleanLiteralTests: XCTestCase { func testBooleanLiteral() { let leadingTrivia = Trivia.garbageText("␣") let testCases: [UInt: (BooleanLiteralExpr, String)] = [ #line: (BooleanLiteralExpr(booleanLiteral: .true), "␣true "), #line: (BooleanLiteralExpr(booleanLiteral: .false), "␣false "), #line: (BooleanLiteralExpr(true), "␣true "), #line: (BooleanLiteralExpr(false), "␣false "), #line: (true, "␣true "), #line: (false, "␣false ") ] for (line, testCase) in testCases { let (builder, expected) = testCase let syntax = builder.buildSyntax(format: Format(), leadingTrivia: leadingTrivia) var text = "" syntax.write(to: &text) XCTAssertEqual(text, expected, line: line) } } }
27.966667
86
0.643623
9cf81b68a82bb8242251ccad751b569150f22886
1,435
// // TudoNossoUITests.swift // TudoNossoUITests // // Created by Joao Flores on 04/11/19. // Copyright © 2019 Joao Flores. All rights reserved. // import XCTest class TudoNossoUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
32.613636
182
0.653659
69de3c23f2afff901457d917f5a126e13bae89b0
540
// // MyView.swift // HelloLayout // // Created by arjuna sky kok on 15/1/19. // Copyright © 2019 PT. Langit Biru Arjuna. All rights reserved. // import UIKit class MyView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func layoutSubviews() { super.layoutSubviews() self.center = CGPoint(x: 300, y: 300) } }
20
78
0.625926
1e2cf8ae0cb8385a51bad45e879fb45976f61855
3,916
// // BloomTest.swift // SwiftStructures // // Created by Wayne Bishop on 9/3/15. // Copyright © 2015 Arbutus Software Inc. All rights reserved. // import XCTest @testable import SwiftStructures //simple structure to group value pairs struct Pairset { var first: Int var second: Int init() { self.first = 0 self.second = 0 } } class BloomTest: XCTestCase { override func setUp() { super.setUp() } //test filter for contained strings func testContainsString() { /* notes: the inclusion of "Seattle" overlap with "Sour" at the second position index */ let filter: Bloom<String>! = Bloom(items: ["Seal", "Sour", "Seattle", "Seat", "Sat", "Sell"]) //test included words XCTAssertTrue(filter.contains("Seal"), "word not in set..") XCTAssertTrue(filter.contains("Sour"), "word not in set..") XCTAssertTrue(filter.contains("Seattle"), "word not in set..") //test excluded words XCTAssertFalse(filter.contains("Sea"), "word included in set..") XCTAssertFalse(filter.contains("Sunk"), "word included in set..") XCTAssertFalse(filter.contains("Sick"), "word included in set..") } //conduct pair-sum test with 5 func testPairSumFive() { let valueList: Array<Int> = [5, 3, 7, 0, 1, 4, 2] let sumtotal: Int = 5 let sumList: Array<Pairset> = self.printPairs(valueList, sum: sumtotal) //conduct final test for s in sumList { if s.first + s.second != sumtotal { XCTFail("test failed") } else { print("pair: (\(s.first),\(s.second))") } } } //conduct pair-sum test with 10 func testPairSumTen() { let valueList: Array<Int> = [8, 3, 7, 0, 1, 4, 2, 6, 5] let sumtotal: Int = 10 let sumList: Array<Pairset> = self.printPairs(valueList, sum: sumtotal) //conduct final test for s in sumList { if s.first + s.second != sumtotal { XCTFail("test failed") } else { print("pair: (\(s.first),\(s.second))") } } } //MARK: //helper functions //calculate unique pairs - O(n) func printPairs(valueList: Array<Int>, sum: Int) -> Array<Pairset>! { var sumList: Array<Pairset> = Array<Pairset>() let filter: Bloom<Int> = Bloom() for s in 0...valueList.count - 1 { print("s is: \(s)") //calculate result let results = sum - valueList[s] if valueList.contains(results) { var valpair: Pairset! = Pairset() //assign pair valpair.first = valueList[s] valpair.second = results //test for bloom membership if !filter.contains(valpair.first) { filter.addElement(valpair.first) } if !filter.contains(valpair.second) { filter.addElement(valpair.second) //add the unique pair to the final list sumList.append(valpair) } } } return sumList } //end function }
21.635359
101
0.452503
62b63dd5f2703db063029d6618b6ada645bd1024
1,238
// // Repository.swift // SwitfHub // // Created by Elias Medeiros on 24/10/20. // import Foundation struct Repository: Decodable, Identifiable { let id: Int let owner: Owner let name: String let description: String? let starCount: Int let language: String let webPage: String? let watchers: Int let openIssues: Int let forks: Int let license: License? let created: Date let lastUpdated: Date enum CodingKeys: String, CodingKey { case id case owner case name case description case starCount = "stargazers_count" case language case webPage = "homepage" case watchers case openIssues = "open_issues" case forks case license case created = "created_at" case lastUpdated = "updated_at" } struct Owner: Decodable { let name: String let pictureURL: String let profileURL: String enum CodingKeys: String, CodingKey { case name = "login" case pictureURL = "avatar_url" case profileURL = "url" } } struct License: Decodable { let name: String? let url: String? } }
20.983051
44
0.588853
1d654e26351b2138a3ee245caf0be8ea8eabc9b9
985
// // MoyaMoreDemoTests.swift // MoyaMoreDemoTests // // Created by WhatsXie on 2018/4/12. // Copyright © 2018年 WhatsXie. All rights reserved. // import XCTest @testable import MoyaMoreDemo class MoyaMoreDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.621622
111
0.639594
72842fa7a82125f19182e9aa7527b95c4c829dca
1,193
// // NSMutableURLRequest+Resource.swift // Insights // // Copyright © 2018 Algolia. All rights reserved. // import Foundation extension URLRequest { init<A, E>(resource: Resource<A, E>) { var requestParams: [URLQueryItem]? = nil var requestBody: Data? = nil switch resource.method { case .get(let params): requestParams = params case .post(let params, let data): requestParams = params requestBody = data case .put(let params, let data): requestParams = params requestBody = data case .delete(let params): requestParams = params } var requestComponents = URLComponents() requestComponents.host = resource.url.host requestComponents.scheme = resource.url.scheme requestComponents.path = resource.url.path requestComponents.port = resource.url.port requestComponents.queryItems = requestParams self.init(url:(requestComponents.url)!) httpMethod = resource.method.method httpBody = requestBody setValue(resource.contentType, forHTTPHeaderField: "Content-Type") for (key, value) in resource.aditionalHeaders { setValue(value, forHTTPHeaderField: key) } } }
27.744186
70
0.690696
9b44ab94b875c44d44d3d8ddb04ac3d6bfd76f3f
707
// // Calculator.swift // Calculator // // Created by Yan Gao on 6/15/15. // Copyright (c) 2015 ___THOUGHTWORKS___. All rights reserved. // import Foundation class Calculator { init() { } func calculate(oprand_left: Int, oprand_right: Int, _operator: String) -> Int { switch _operator { case "-": return oprand_left - oprand_right case "x": return oprand_left * oprand_right case "/": if (oprand_right != 0) { return oprand_left / oprand_right }else { return -1; } default: return oprand_left + oprand_right } } }
20.794118
83
0.520509
71377b39d28e4ca259e4b29a1f75adbaf6f3844e
2,287
// // SceneDelegate.swift // Prework // // Created by Hamzah Khan on 2/2/22. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.150943
147
0.712287
22a7962867fd369636f62a1bc59dae3587784ec4
18,308
// // PaymentProtocol.swift // breadwallet // // Created by Aaron Voisine on 5/01/17. // Copyright (c) 2017 breadwallet LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import BRCore // BIP70 payment protocol: https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki // bitpay json payment protocol: https://github.com/bitpay/jsonPaymentProtocol/blob/master/specification.md class PaymentProtocolDetails { internal let cPtr: UnsafeMutablePointer<BRPaymentProtocolDetails> internal var isManaged: Bool internal init(_ cPtr: UnsafeMutablePointer<BRPaymentProtocolDetails>) { self.cPtr = cPtr self.isManaged = false } init?(network: String = "main", outputs: [BRTxOutput], time: UInt64, expires: UInt64, memo: String? = nil, paymentURL: String? = nil, merchantData: [UInt8]? = nil) { guard let cPtr = BRPaymentProtocolDetailsNew(network, outputs, outputs.count, time, expires, memo, paymentURL, merchantData, merchantData?.count ?? 0) else { return nil } cPtr.pointee.outCount = outputs.count self.cPtr = cPtr self.isManaged = true } init?(data: Data) { let bytes = [UInt8](data) guard let cPtr = BRPaymentProtocolDetailsParse(bytes, bytes.count) else { return nil } self.cPtr = cPtr self.isManaged = true } var bytes: [UInt8] { var bytes = [UInt8](repeating: 0, count: BRPaymentProtocolDetailsSerialize(cPtr, nil, 0)) BRPaymentProtocolDetailsSerialize(cPtr, &bytes, bytes.count) return bytes } var network: String { // main / test / regtest, default is "main" return String(cString: cPtr.pointee.network) } var currency: String = "BTC" // three digit currency code representing which coin the request is based on (bitpay) var requiredFeeRate: Double = 0.0 // the minimum fee per byte required on this transaction (bitpay) var outputs: [BRTxOutput] { // where to send payments, outputs[n].amount defaults to 0 return [BRTxOutput](UnsafeBufferPointer(start: cPtr.pointee.outputs, count: cPtr.pointee.outCount)) } var time: UInt64 { // request creation time, seconds since unix epoch, optional return cPtr.pointee.time } var expires: UInt64 { // when this request should be considered invalid, optional return cPtr.pointee.expires } var memo: String? { // human-readable description of request for the customer, optional guard cPtr.pointee.memo != nil else { return nil } return String(cString: cPtr.pointee.memo) } var paymentURL: String? { // url to send payment and get payment ack, optional guard cPtr.pointee.paymentURL != nil else { return nil } return String(cString: cPtr.pointee.paymentURL) } var paymentId: String? = nil // the invoice ID, can be kept for records (bitpay) var merchantData: [UInt8]? { // arbitrary data to include in the payment message, optional guard cPtr.pointee.merchantData != nil else { return nil } return [UInt8](UnsafeBufferPointer(start: cPtr.pointee.merchantData, count: cPtr.pointee.merchDataLen)) } deinit { if isManaged { BRPaymentProtocolDetailsFree(cPtr) } } } class PaymentProtocolRequest { internal struct Request: Decodable { internal struct Output: Decodable { let amount: UInt64 let address: String let data:String } let network: String let currency: String let requiredFeeRate: Double let outputs: [Output] let time: Date let expires: Date let memo: String let paymentUrl: URL let paymentId: String } internal let cPtr: UnsafeMutablePointer<BRPaymentProtocolRequest> internal var isManaged: Bool private var cName: String? private var errMsg: String? private var didValidate: Bool = false internal init(_ cPtr: UnsafeMutablePointer<BRPaymentProtocolRequest>) { self.details = PaymentProtocolDetails(cPtr.pointee.details) self.details.isManaged = false self.cPtr = cPtr self.isManaged = false } init?(version: UInt32 = 1, pkiType: String = "none", pkiData: [UInt8]? = nil, details: PaymentProtocolDetails, signature: [UInt8]? = nil) { guard details.isManaged else { return nil } // request must be able take over memory management of details self.details = details guard let cPtr = BRPaymentProtocolRequestNew(version, pkiType, pkiData, pkiData?.count ?? 0, details.cPtr, signature, signature?.count ?? 0) else { return nil } details.isManaged = false self.cPtr = cPtr self.isManaged = true } init?(data: Data) { let bytes = [UInt8](data) guard let cPtr = BRPaymentProtocolRequestParse(bytes, bytes.count) else { return nil } self.details = PaymentProtocolDetails(cPtr.pointee.details) self.details.isManaged = false self.cPtr = cPtr self.isManaged = true } init?(json: String) { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) guard let req = try? decoder.decode(Request.self, from: json.data(using: .utf8)!) else { return nil } let outputs = req.outputs.map { BRTxOutput(req.currency == "BCH" ? $0.address.bitcoinAddr : $0.address, $0.amount) } guard outputs.count > 0 && outputs[0].amount > 0 && outputs[0].scriptLen > 0 else { return nil } guard let details = PaymentProtocolDetails(network: req.network, outputs: outputs, time: UInt64(req.time.timeIntervalSince1970), expires: UInt64(req.expires.timeIntervalSince1970), memo: req.memo, paymentURL: req.paymentUrl.absoluteString) else { return nil } details.currency = req.currency details.requiredFeeRate = req.requiredFeeRate details.paymentId = req.paymentId mimeType = "application/payment-request" guard let cPtr = BRPaymentProtocolRequestNew(1, "none", nil, 0, details.cPtr, nil, 0) else { return nil } details.isManaged = false self.details = details self.cPtr = cPtr self.isManaged = true } var bytes: [UInt8] { var bytes = [UInt8](repeating: 0, count: BRPaymentProtocolRequestSerialize(cPtr, nil, 0)) BRPaymentProtocolRequestSerialize(cPtr, &bytes, bytes.count) return bytes } var version: UInt32 { // default is 1 return cPtr.pointee.version } var pkiType: String { // none / x509+sha256 / x509+sha1, default is "none" return String(cString: cPtr.pointee.pkiType) } var pkiData: [UInt8]? { // depends on pkiType, optional guard cPtr.pointee.pkiData != nil else { return nil } return [UInt8](UnsafeBufferPointer(start: cPtr.pointee.pkiData, count: cPtr.pointee.pkiDataLen)) } var details: PaymentProtocolDetails // required var signature: [UInt8]? { // pki-dependent signature, optional guard cPtr.pointee.signature != nil else { return nil } return [UInt8](UnsafeBufferPointer(start: cPtr.pointee.signature, count: cPtr.pointee.sigLen)) } var certs: [[UInt8]] { // array of DER encoded certificates var certs = [[UInt8]]() var idx = 0 while BRPaymentProtocolRequestCert(cPtr, nil, 0, idx) > 0 { certs.append([UInt8](repeating: 0, count: BRPaymentProtocolRequestCert(cPtr, nil, 0, idx))) BRPaymentProtocolRequestCert(cPtr, UnsafeMutablePointer(mutating: certs[idx]), certs[idx].count, idx) idx = idx + 1 } return certs } var digest: [UInt8] { // hash of the request needed to sign or verify the request let digest = [UInt8](repeating: 0, count: BRPaymentProtocolRequestDigest(cPtr, nil, 0)) BRPaymentProtocolRequestDigest(cPtr, UnsafeMutablePointer(mutating: digest), digest.count) return digest } func isValid() -> Bool { defer { didValidate = true } if pkiType != "none" { var certs = [SecCertificate]() let policies = [SecPolicy](repeating: SecPolicyCreateBasicX509(), count: 1) var trust: SecTrust? var trustResult = SecTrustResultType.invalid for c in self.certs { if let cert = SecCertificateCreateWithData(nil, Data(bytes: c) as CFData) { certs.append(cert) } } if certs.count > 0 { cName = SecCertificateCopySubjectSummary(certs[0]) as String? } SecTrustCreateWithCertificates(certs as CFTypeRef, policies as CFTypeRef, &trust) if let trust = trust { SecTrustEvaluate(trust, &trustResult) } // verify certificate chain // .unspecified indicates a positive result that wasn't decided by the user guard trustResult == .unspecified || trustResult == .proceed else { errMsg = certs.count > 0 ? S.PaymentProtocol.Errors.untrustedCertificate : S.PaymentProtocol.Errors.missingCertificate if let trust = trust, let properties = SecTrustCopyProperties(trust) { for prop in properties as! [Dictionary<AnyHashable, Any>] { if prop["type"] as? String != kSecPropertyTypeError as String { continue } errMsg = errMsg! + " - " + (prop["value"] as! String) break } } return false } var status = errSecUnimplemented var pubKey: SecKey? = nil if let trust = trust { pubKey = SecTrustCopyPublicKey(trust) } if let pubKey = pubKey, let signature = signature { if pkiType == "x509+sha256" { status = SecKeyRawVerify(pubKey, .PKCS1SHA256, digest, digest.count, signature, signature.count) } else if pkiType == "x509+sha1" { status = SecKeyRawVerify(pubKey, .PKCS1SHA1, digest, digest.count, signature, signature.count) } } guard status == errSecSuccess else { if status == errSecUnimplemented { errMsg = S.PaymentProtocol.Errors.unsupportedSignatureType print(errMsg!) } else { errMsg = NSError(domain: NSOSStatusErrorDomain, code: Int(status)).localizedDescription print("SecKeyRawVerify error: " + errMsg!) } return false } } else if (self.certs.count > 0) { // non-standard extention to include an un-certified request name cName = String(data: Data(self.certs[0]), encoding: .utf8) } guard details.expires == 0 || NSDate.timeIntervalSinceReferenceDate <= Double(details.expires) else { errMsg = S.PaymentProtocol.Errors.requestExpired return false } return true } var amount: UInt64 { return details.outputs.map { $0.amount }.reduce(0, +) } var commonName: String? { if !didValidate { _ = self.isValid() } return cName } var errorMessage: String? { if !didValidate { _ = self.isValid() } return errMsg } var address: String { return details.outputs.first!.swiftAddress } var mimeType: String = "application/bitcoin-paymentrequest" deinit { if isManaged { BRPaymentProtocolRequestFree(cPtr) } } } class PaymentProtocolPayment { internal struct Payment: Decodable, Encodable { let currency: String let transactions: [String] } internal let cPtr: UnsafeMutablePointer<BRPaymentProtocolPayment> internal var isManaged: Bool internal init(_ cPtr: UnsafeMutablePointer<BRPaymentProtocolPayment>) { self.cPtr = cPtr self.isManaged = false } init?(merchantData: [UInt8]? = nil, transactions: [BRTxRef?], refundTo: [(address: String, amount: UInt64)], memo: String? = nil) { var txRefs = transactions guard let cPtr = BRPaymentProtocolPaymentNew(merchantData, merchantData?.count ?? 0, &txRefs, txRefs.count, refundTo.map { $0.amount }, refundTo.map { BRAddress(string: $0.address) ?? BRAddress() }, refundTo.count, memo) else { return nil } self.cPtr = cPtr self.isManaged = true } init?(data: Data) { let bytes = [UInt8](data) guard let cPtr = BRPaymentProtocolPaymentParse(bytes, bytes.count) else { return nil } self.cPtr = cPtr self.isManaged = true } var bytes: [UInt8] { var bytes = [UInt8](repeating: 0, count: BRPaymentProtocolPaymentSerialize(cPtr, nil, 0)) BRPaymentProtocolPaymentSerialize(cPtr, &bytes, bytes.count) return bytes } var currency: String = "BTC" // three digit currency code representing which coin the request is based on (bitpay) var merchantData: [UInt8]? { // from request->details->merchantData, optional guard cPtr.pointee.merchantData != nil else { return nil } return [UInt8](UnsafeBufferPointer(start: cPtr.pointee.merchantData, count: cPtr.pointee.merchDataLen)) } var transactions: [BRTxRef?] { // array of signed BRTxRef to satisfy outputs from details return [BRTxRef?](UnsafeBufferPointer(start: cPtr.pointee.transactions, count: cPtr.pointee.txCount)) } var refundTo: [BRTxOutput] { // where to send refunds, if a refund is necessary, refundTo[n].amount defaults to 0 return [BRTxOutput](UnsafeBufferPointer(start: cPtr.pointee.refundTo, count: cPtr.pointee.refundToCount)) } var memo: String? { // human-readable message for the merchant, optional guard cPtr.pointee.memo != nil else { return nil } return String(cString: cPtr.pointee.memo) } var json: String? { let tx = transactions.compactMap { $0?.bytes?.reduce("") { $0 + String(format: "%02x", $1) } } guard let data = try? JSONEncoder().encode(Payment(currency: currency, transactions: tx)) else { return nil } return String(data: data, encoding: .utf8) } deinit { if isManaged { BRPaymentProtocolPaymentFree(cPtr) } } } class PaymentProtocolACK { internal struct Ack: Decodable { let payment: PaymentProtocolPayment.Payment let memo: String? } internal let cPtr: UnsafeMutablePointer<BRPaymentProtocolACK> internal var isManaged: Bool internal init(_ cPtr: UnsafeMutablePointer<BRPaymentProtocolACK>) { self.cPtr = cPtr self.isManaged = false } init?(payment: PaymentProtocolPayment, memo: String? = nil) { guard payment.isManaged else { return nil } // ack must be able to take over memory management of payment guard let cPtr = BRPaymentProtocolACKNew(payment.cPtr, memo) else { return nil } payment.isManaged = false self.cPtr = cPtr self.isManaged = true } init?(data: Data) { let bytes = [UInt8](data) guard let cPtr = BRPaymentProtocolACKParse(bytes, bytes.count) else { return nil } self.cPtr = cPtr self.isManaged = true } init?(json: String) { guard let ack = try? JSONDecoder().decode(Ack.self, from: json.data(using: .utf8)!) else { return nil } guard let payment = PaymentProtocolPayment(transactions: [], refundTo: []) else { return nil } payment.currency = ack.payment.currency guard let cPtr = BRPaymentProtocolACKNew(payment.cPtr, ack.memo) else { return nil } self.cPtr = cPtr self.isManaged = true } var bytes: [UInt8] { var bytes = [UInt8](repeating: 0, count: BRPaymentProtocolACKSerialize(cPtr, nil, 0)) BRPaymentProtocolACKSerialize(cPtr, &bytes, bytes.count) return bytes } var payment: PaymentProtocolPayment { // payment message that triggered this ack, required return PaymentProtocolPayment(cPtr.pointee.payment) } var memo: String? { // human-readable message for customer, optional guard cPtr.pointee.memo != nil else { return nil } return String(cString: cPtr.pointee.memo) } deinit { if isManaged { BRPaymentProtocolACKFree(cPtr) } } }
40.504425
134
0.620821
503a5b1414f7e7979cda155a57eb9296ed20df16
4,718
// // QuerySelector.swift // Created by Gabe Shahbazian 2020 // import CGumboParser public protocol QuerySelector { func match(node: Node) -> Bool } public extension Node { func findAll(matching: QuerySelector) -> [Node] { var matches = [Node]() var queue: [Node] = [self] while !queue.isEmpty { let currentNode = queue.removeFirst() if matching.match(node: currentNode) { matches.append(currentNode) } switch currentNode.type { case .element(let element): queue.append(contentsOf: element.children) default: break } } return matches } func findFirst(matching: QuerySelector) -> Node? { var queue: [Node] = [self] while !queue.isEmpty { let currentNode = queue.removeFirst() if matching.match(node: currentNode) { return currentNode } switch currentNode.type { case .element(let element): queue.append(contentsOf: element.children) default: break } } return nil } } struct BinarySelector: QuerySelector { enum Operator { case union case intersection case child case descendant case adjacent case sibling } let op: Operator let first: QuerySelector let second: QuerySelector func match(node: Node) -> Bool { switch op { case .union: return first.match(node: node) || second.match(node: node) case .intersection: return first.match(node: node) && second.match(node: node) case .child: guard let parent = node.parent else { return false } return first.match(node: parent) && second.match(node: node) case .descendant: if !second.match(node: node) { return false } var nextParent = node.parent while let parent = nextParent { if first.match(node: parent) { return true} nextParent = parent.parent } return false case .adjacent, .sibling: if !second.match(node: node) { return false } guard let parentElement = node.parent?.element else { return false } let siblingEnd = parentElement.children.index(parentElement.children.startIndex, offsetBy: node.indexWithinParent) for siblingNode in parentElement.children[parentElement.children.startIndex..<siblingEnd].reversed() { guard siblingNode.element != nil else { continue } if op == .adjacent { return first.match(node: siblingNode) } else if first.match(node: siblingNode) { return true } } return false } } } struct TagSelector: QuerySelector { let tag: GumboTag func match(node: Node) -> Bool { node.element?.element.tag == tag } } struct AttributeSelector: QuerySelector { enum Operator { case exists case equals case listed case prefix case suffix case contains } let op: Operator let name: String let value: String init(op: Operator, name: String, value: String = "") { self.op = op self.name = name self.value = value } func match(node: Node) -> Bool { guard let element = node.element else { return false } guard let attribute = element.attributes.first(where: { $0.name == name }) else { return false } switch op { case .exists: return true case .equals: return attribute.value == value case .listed: let splitValue = attribute.value.components(separatedBy: .whitespacesAndNewlines) return splitValue.contains(value) case .prefix: guard !value.isEmpty else { return false } return attribute.value.hasPrefix(value) case .suffix: guard !value.isEmpty else { return false } return attribute.value.hasSuffix(value) case .contains: guard !value.isEmpty else { return false } return attribute.value.contains(value) } } } struct NotSelector: QuerySelector { let notMatching: QuerySelector func match(node: Node) -> Bool { guard node.isElement else { return false } return !notMatching.match(node: node) } } struct EmptySelector: QuerySelector { func match(node: Node) -> Bool { node.isElement } }
27.114943
126
0.567613
11fc4fda3a4bd77420b5d4eb399722ea604f993a
2,300
// // EAggregateControlInterface.swift // Muzzley-iOS // // Created by Hugo Sousa on 6/11/14. // Copyright (c) 2014 Muzzley. All rights reserved. // import Foundation class EAggregateControlInterface: NSObject { enum EAggregateControlInterfaceKey: NSString { case uuid = "uuid" case name = "name" case description = "description" case icon = "icon" case source = "src" case channels = "channels" } // MARK: Properties var uuid: String = "" var name: String = "" var aggregateDescription: String = "" var iconUrlString: String = "" var sourceUrlString: String = "" var childChannels: NSMutableDictionary = NSMutableDictionary() // MARK: Class Initializers class func aggregateInterfaceWithDictionaryRepresentation(_ dictionary : NSDictionary) -> EAggregateControlInterface { // Create channel interface let interface:EAggregateControlInterface = EAggregateControlInterface() // Validate values if let uuid = dictionary[EAggregateControlInterfaceKey.uuid.rawValue] as? String { interface.uuid = uuid } if let name = dictionary[EAggregateControlInterfaceKey.name.rawValue] as? String { interface.name = name } if let description = dictionary[EAggregateControlInterfaceKey.description.rawValue] as? String { interface.aggregateDescription = description } if let icon = dictionary[EAggregateControlInterfaceKey.icon.rawValue] as? String { interface.iconUrlString = icon } if let source = dictionary[EAggregateControlInterfaceKey.source.rawValue] as? String { interface.sourceUrlString = source } if let channelsArray = dictionary[EAggregateControlInterfaceKey.channels.rawValue] as? NSArray { for item in channelsArray { if let channelDictionary = item as? NSDictionary { if let channel: MZChannel = MZChannel (dictionary: channelDictionary) { interface.childChannels.setObject(channel, forKey: channel.identifier as NSCopying) } } } } return interface } }
35.384615
122
0.636957
f8d30622e457cc3d0d1f6449247d38cc1e70be21
244
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSData { struct S { enum B { func d { { } var d = { class case ,
17.428571
87
0.721311
febfd50ec48e1a7c70b55e4e99f0d57810c596ae
635
// // StyleDictionarySize.swift // // Do not edit directly // Generated on Mon, 03 Aug 2020 20:48:28 GMT // import UIKit public enum StyleDictionarySize { public static let fontBody = CGFloat(224.00) public static let fontHeading1 = CGFloat(448.00) public static let fontHeading2 = CGFloat(400.00) public static let fontHeading3 = CGFloat(352.00) public static let fontHeading4 = CGFloat(320.00) public static let fontHeading5 = CGFloat(320.00) public static let fontHeading6 = CGFloat(256.00) public static let fontMasthead1 = CGFloat(576.00) public static let fontMasthead2 = CGFloat(512.00) }
28.863636
53
0.727559
4838dc903cfca88422808dec80a4c29144444511
2,081
// // AreaToolbar.swift // test // // Created by quan on 2017/1/12. // Copyright © 2017年 langxi.Co.Ltd. All rights reserved. // import UIKit protocol AreaToolbarDelegate: class { func sure(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) func cancel(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) } class AreaToolbar: UIToolbar { weak var barDelegate: AreaToolbarDelegate? var textField: UITextField! static func bar<T: UIViewController>(for controller: T, textField: UITextField, barTintColor: UIColor, tintColor: UIColor) -> AreaToolbar where T: AreaToolbarDelegate { let toolBar = AreaToolbar() toolBar.textField = textField toolBar.barDelegate = controller let cancelItem = UIBarButtonItem(title: "取消", style: .plain, target: toolBar, action: #selector(areaPickerCancel(_:))) let flexibleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let sureItem = UIBarButtonItem(title: "确定", style: .plain, target: toolBar, action: #selector(areaPickerSure(_:))) toolBar.items = [cancelItem, flexibleItem, sureItem] toolBar.barTintColor = barTintColor toolBar.tintColor = tintColor return toolBar } private init(){ super.init(frame: CGRect(x: 0, y: 0, width: APMAIN_WIDTH, height: 44)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func areaPickerCancel(_ item: UIBarButtonItem) { textField.resignFirstResponder() barDelegate?.cancel(areaToolbar: self, textField: textField, locate: locate, item: item) } func areaPickerSure(_ item: UIBarButtonItem) { textField.resignFirstResponder() barDelegate?.sure(areaToolbar: self, textField: textField, locate: locate, item: item) } // MARK: - lazy lazy var locate: Location = { return Location() }() }
33.564516
172
0.674195
9b1543194bfb775f6684fe04cc68226d4e1c2f71
19,308
// Copyright 2021 David Sansome // // 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 WaniKaniAPI private let kSectionHeaderHeight: CGFloat = 38.0 private let kSectionFooterHeight: CGFloat = 0.0 private let kFontSize: CGFloat = 14.0 private let kMeaningSynonymColor = UIColor(red: 0.231, green: 0.6, blue: 0.988, alpha: 1) private let kFont = TKMStyle.japaneseFont(size: kFontSize) private func join(_ arr: [NSAttributedString], with joinString: String) -> NSAttributedString { let ret = NSMutableAttributedString() let count = arr.count for i in 0 ..< count { ret.append(arr[i]) if i != count - 1 { ret.append(attrString(joinString)) } } return ret } private func renderMeanings(subject: TKMSubject, studyMaterials: TKMStudyMaterials?) -> NSAttributedString { var strings = [NSAttributedString]() for meaning in subject.meanings { if meaning.type == .primary { strings.append(attrString(meaning.meaning)) } } if let studyMaterials = studyMaterials { for meaning in studyMaterials.meaningSynonyms { strings.append(attrString(meaning, attrs: [.foregroundColor: kMeaningSynonymColor])) } } for meaning in subject.meanings { if meaning.type != .primary, meaning.type != .blacklist, meaning.type != .auxiliaryWhitelist || !subject.hasRadical || Settings.showOldMnemonic { let font = UIFont.systemFont(ofSize: kFontSize, weight: .light) strings.append(attrString(meaning.meaning, attrs: [.font: font])) } } return join(strings, with: ", ") } private func renderReadings(readings: [TKMReading], primaryOnly: Bool) -> NSAttributedString { var strings = [NSAttributedString]() for reading in readings { if reading.isPrimary { var font = TKMStyle.japaneseFontLight(size: kFontSize) if !primaryOnly, readings.count > 1 { font = TKMStyle.japaneseFontBold(size: kFontSize) } strings .append(attrString(reading.displayText(useKatakanaForOnyomi: Settings.useKatakanaForOnyomi), attrs: [.font: font])) } } if !primaryOnly { let font = TKMStyle.japaneseFontLight(size: kFontSize) for reading in readings { if !reading.isPrimary { strings .append(attrString(reading .displayText(useKatakanaForOnyomi: Settings.useKatakanaForOnyomi), attrs: [.font: font])) } } } return join(strings, with: ", ") } private func renderNotes(studyMaterials: TKMStudyMaterials?, isMeaning: Bool) -> NSAttributedString? { let font = UIFont.systemFont(ofSize: kFontSize, weight: .regular) if let studyMaterials = studyMaterials { if isMeaning, studyMaterials.hasMeaningNote { return attrString(studyMaterials.meaningNote, attrs: [.font: font]) } else if !isMeaning, studyMaterials.hasReadingNote { return attrString(studyMaterials.readingNote, attrs: [.font: font]) } } return nil } private func attrString(_ string: String, attrs: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString { let combinedAttrs = defaultStringAttrs().merging(attrs ?? [:]) { _, new in new } return NSAttributedString(string: string, attributes: combinedAttrs) } private func defaultStringAttrs() -> [NSAttributedString.Key: Any] { [.foregroundColor: TKMStyle.Color.label, .backgroundColor: TKMStyle.Color.cellBackground] } private func dateFormatter(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> DateFormatter { let ret = DateFormatter() ret.dateStyle = dateStyle ret.timeStyle = timeStyle return ret } @objc(TKMSubjectDetailsView) class SubjectDetailsView: UITableView, SubjectChipDelegate { private let statsDateFormatter = dateFormatter(dateStyle: .medium, timeStyle: .short) required init?(coder: NSCoder) { super.init(coder: coder) sectionHeaderHeight = kSectionHeaderHeight estimatedSectionHeaderHeight = kSectionHeaderHeight sectionFooterHeight = kSectionFooterHeight estimatedSectionFooterHeight = kSectionFooterHeight } private var services: TKMServices! private weak var subjectDelegate: SubjectDelegate! private var readingItem: ReadingModelItem? private var tableModel: TKMTableModel? private var lastSubjectChipTapped: SubjectChip? private var subject: TKMSubject! private var studyMaterials: TKMStudyMaterials? private var assignment: TKMAssignment? private var task: ReviewItem? public func setup(services: TKMServices, delegate: SubjectDelegate) { self.services = services subjectDelegate = delegate } private func addMeanings(_ subject: TKMSubject, studyMaterials: TKMStudyMaterials?, toModel model: TKMMutableTableModel) { let text = renderMeanings(subject: subject, studyMaterials: studyMaterials) .string(withFontSize: kFontSize) let item = AttributedModelItem(text: text) model.addSection("Meaning") model.add(item) if let notesText = renderNotes(studyMaterials: studyMaterials, isMeaning: true) { let notesItem = AttributedModelItem(text: notesText.string(withFontSize: kFontSize)) model.addSection("Meaning Note") model.add(notesItem) } if Settings.enableNoteEditing || task == nil { let hasMeaningNote = !(studyMaterials?.meaningNote ?? "").isEmpty model.add(TKMBasicModelItem(style: .default, title: "\(hasMeaningNote ? "Edit" : "Create") meaning note", subtitle: nil, accessoryType: .none, target: self, action: #selector(editMeaningNote))) } } private func addReadings(_ subject: TKMSubject, studyMaterials: TKMStudyMaterials?, toModel model: TKMMutableTableModel) { let primaryOnly = subject.hasKanji && !Settings.showAllReadings let text = renderReadings(readings: subject.readings, primaryOnly: primaryOnly).string(withFontSize: kFontSize) let item = ReadingModelItem(text: text) if subject.hasVocabulary, !subject.vocabulary.audio.isEmpty { item.setAudio(services.audio, subjectID: subject.id) } readingItem = item model.addSection("Reading") model.add(item) if let notesText = renderNotes(studyMaterials: studyMaterials, isMeaning: false) { let notesItem = AttributedModelItem(text: notesText.string(withFontSize: kFontSize)) model.addSection("Reading Note") model.add(notesItem) } if Settings.enableNoteEditing || task == nil { let hasReadingNote = !(studyMaterials?.readingNote ?? "").isEmpty model.add(TKMBasicModelItem(style: .default, title: "\(hasReadingNote ? "Edit" : "Create") reading note", subtitle: nil, accessoryType: .none, target: self, action: #selector(editReadingNote))) } } private func addComponents(_ subject: TKMSubject, title: String, toModel model: TKMMutableTableModel) { let item = SubjectCollectionModelItem(subjects: subject.componentSubjectIds, localCachingClient: services.localCachingClient, delegate: self) model.addSection(title) model.add(item) } private func addSimilarKanji(_ subject: TKMSubject, toModel model: TKMMutableTableModel) { let currentLevel = services.localCachingClient!.getUserInfo()!.level var addedSection = false for similar in subject.kanji.visuallySimilarKanji { guard let subject = services.localCachingClient.getSubject(japanese: String(similar)) else { continue } if subject.level > currentLevel || subject.subjectType != .kanji { continue } if !addedSection { model.addSection("Visually Similar Kanji") addedSection = true } let item = SubjectModelItem(subject: subject, delegate: subjectDelegate) model.add(item) } } private func addAmalgamationSubjects(_ subject: TKMSubject, toModel model: TKMMutableTableModel) { var subjects = [TKMSubject]() for subjectID in subject.amalgamationSubjectIds { if let subject = services.localCachingClient.getSubject(id: subjectID) { subjects.append(subject) } } if subjects.isEmpty { return } subjects.sort { (a, b) -> Bool in a.level < b.level } model.addSection("Used in") for subject in subjects { model.add(SubjectModelItem(subject: subject, delegate: subjectDelegate)) } } private func addFormattedText(_ text: String, isHint: Bool, toModel model: TKMMutableTableModel) { if text.isEmpty { return } let parsedText = parseFormattedText(text) var attributes = defaultStringAttrs() if isHint { attributes[.foregroundColor] = TKMStyle.Color.grey33 } let formattedText = render(formattedText: parsedText, standardAttributes: attributes) .replaceFontSize(kFontSize) model.add(AttributedModelItem(text: formattedText)) } private func addContextSentences(_ subject: TKMSubject, toModel model: TKMMutableTableModel) { if subject.vocabulary.sentences.isEmpty { return } model.addSection("Context Sentences") for sentence in subject.vocabulary.sentences { model.add(ContextSentenceModelItem(sentence, highlightSubject: subject, defaultAttributes: defaultStringAttrs(), fontSize: kFontSize)) } } private func addPartsOfSpeech(_ vocab: TKMVocabulary, toModel model: TKMMutableTableModel) { let text = vocab.commaSeparatedPartsOfSpeech if text.isEmpty { return } model.addSection("Part of Speech") let item = TKMBasicModelItem(style: .default, title: text, subtitle: nil) item.titleFont = UIFont.systemFont(ofSize: kFontSize) model.add(item) } @objc private func showAllFields() { update(withSubject: subject, studyMaterials: studyMaterials, assignment: assignment, task: nil) } public func update(withSubject subject: TKMSubject, studyMaterials: TKMStudyMaterials?, assignment: TKMAssignment?, task: ReviewItem?) { let model = TKMMutableTableModel(tableView: self), isReview = task != nil readingItem = nil self.subject = subject self.studyMaterials = studyMaterials self.assignment = assignment self.task = task let meaningAttempted = task?.answeredMeaning == true || task?.answer.meaningWrong == true, readingAttempted = task?.answeredReading == true || task?.answer.readingWrong == true, meaningShown = !isReview || meaningAttempted, readingShown = !isReview || readingAttempted, showMeaningItem = TKMBasicModelItem(style: .default, title: "Show meaning & explanations", subtitle: nil, accessoryType: .none, target: self, action: #selector(showAllFields)), showReadingItem = TKMBasicModelItem(style: .default, title: "Show reading & explanation", subtitle: nil, accessoryType: .none, target: self, action: #selector(showAllFields)) showMeaningItem.textColor = .systemRed showReadingItem.textColor = .systemRed if subject.hasRadical { if meaningShown { addMeanings(subject, studyMaterials: studyMaterials, toModel: model) model.addSection("Mnemonic") addFormattedText(subject.radical.mnemonic, isHint: false, toModel: model) if Settings.showOldMnemonic, !subject.radical.deprecatedMnemonic.isEmpty { model.addSection("Old Mnemonic") addFormattedText(subject.radical.deprecatedMnemonic, isHint: false, toModel: model) } } else { model.add(showMeaningItem) } addAmalgamationSubjects(subject, toModel: model) } if subject.hasKanji { if meaningShown { addMeanings(subject, studyMaterials: studyMaterials, toModel: model) } else { model.add(showMeaningItem) } if readingShown { addReadings(subject, studyMaterials: studyMaterials, toModel: model) } else { model.add(showReadingItem) } addComponents(subject, title: "Radicals", toModel: model) if meaningShown { model.addSection("Meaning Explanation") addFormattedText(subject.kanji.meaningMnemonic, isHint: false, toModel: model) addFormattedText(subject.kanji.meaningHint, isHint: true, toModel: model) } if meaningShown, readingShown { model.addSection("Reading Explanation") addFormattedText(subject.kanji.readingMnemonic, isHint: false, toModel: model) addFormattedText(subject.kanji.readingHint, isHint: true, toModel: model) } addSimilarKanji(subject, toModel: model) addAmalgamationSubjects(subject, toModel: model) } if subject.hasVocabulary { if meaningShown { addMeanings(subject, studyMaterials: studyMaterials, toModel: model) } else { model.add(showMeaningItem) } if readingShown { addReadings(subject, studyMaterials: studyMaterials, toModel: model) } else { model.add(showReadingItem) } addComponents(subject, title: "Kanji", toModel: model) if meaningShown { model.addSection("Meaning Explanation") addFormattedText(subject.vocabulary.meaningExplanation, isHint: false, toModel: model) } // Reading explanations often contain the meaning, so require it as well if meaningShown, readingShown { model.addSection("Reading Explanation") addFormattedText(subject.vocabulary.readingExplanation, isHint: false, toModel: model) } addPartsOfSpeech(subject.vocabulary, toModel: model) if meaningShown { addContextSentences(subject, toModel: model) } } // Your progress, SRS level, next review, first started, reached guru if let subjectAssignment = assignment, Settings.showStatsSection { model.addSection("Stats") model.add(TKMBasicModelItem(style: .value1, title: "WaniKani Level", subtitle: String(subjectAssignment.level))) if subjectAssignment.hasStartedAt { if subjectAssignment.hasSrsStageNumber { model.add(TKMBasicModelItem(style: .value1, title: "SRS Stage", subtitle: subjectAssignment.srsStage.description)) } model.add(TKMBasicModelItem(style: .value1, title: "Started", subtitle: statsDateFormatter .string(from: subjectAssignment.startedAtDate))) if subjectAssignment.hasAvailableAt { model.add(TKMBasicModelItem(style: .value1, title: "Next Review", subtitle: statsDateFormatter .string(from: subjectAssignment.availableAtDate))) } if subjectAssignment.hasPassedAt { model.add(TKMBasicModelItem(style: .value1, title: "Passed", subtitle: statsDateFormatter .string(from: subjectAssignment.passedAtDate))) } if subjectAssignment.hasBurnedAt { model.add(TKMBasicModelItem(style: .value1, title: "Burned", subtitle: statsDateFormatter .string(from: subjectAssignment.burnedAtDate))) } } // TODO: When possible in the API, add a resurrect button. } tableModel = model model.reloadTable() } @objc public func deselectLastSubjectChipTapped() { lastSubjectChipTapped?.backgroundColor = nil } @objc public func playAudio() { readingItem?.playAudio() } @objc public func editMeaningNote() { editNote(subject: subject, studyMaterials: studyMaterials, isMeaningNote: true) } @objc public func editReadingNote() { editNote(subject: subject, studyMaterials: studyMaterials, isMeaningNote: false) } func editNote(subject: TKMSubject, studyMaterials: TKMStudyMaterials?, isMeaningNote: Bool) { var materials = studyMaterials ?? TKMStudyMaterials() if studyMaterials == nil { materials.subjectID = subject.id } let hasNote = isMeaningNote ? !materials.meaningNote.isEmpty : !materials.readingNote.isEmpty let ac = UIAlertController(title: "\(hasNote ? "Edit" : "Create") note", message: "\(hasNote ? "Edit" : "Create") the \(isMeaningNote ? "meaning" : "reading") note", preferredStyle: .alert) ac.addTextField(configurationHandler: { textField in textField.placeholder = "Type \(isMeaningNote ? "meaning" : "reading") note here" if hasNote { textField.text = isMeaningNote ? materials.meaningNote : materials.readingNote } }) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in let noteText = ac.textFields?.first?.text ?? "" if isMeaningNote { materials.meaningNote = noteText } else { materials.readingNote = noteText } _ = self.services.localCachingClient.updateStudyMaterial(materials) self.update(withSubject: subject, studyMaterials: materials, assignment: self.assignment, task: self.task) })) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) let vc = UIApplication.shared.keyWindow!.rootViewController! vc.present(ac, animated: true, completion: nil) } // MARK: - SubjectChipDelegate func didTapSubjectChip(_ chip: SubjectChip) { lastSubjectChipTapped = chip chip.backgroundColor = TKMStyle.Color.grey80 if let subject = chip.subject { subjectDelegate.didTapSubject(subject) } } }
38.309524
123
0.643412
2695e367dfcf804732e92dbac08c0975e5fdbf60
1,247
// // ImageContent.swift // AnKit // // Created by Anvipo on 29.08.2021. // import UIKit /// Enumeration for image content types. public enum ImageContent { /// Content will be provided by remote provider. case remoteURL( urlProvider: URLProvider, imageDownloader: ImageDownloader, imageModifiers: [ComplexUIImageProvider.Modifier] = [] ) /// Content will be provided by local provider. case localImage(uiImageProvider: UIImageProvider) } extension ImageContent: Equatable { public static func == (lhs: ImageContent, rhs: ImageContent) -> Bool { switch (lhs, rhs) { case let ( .remoteURL(lhsURLProvider, _, lhsImageModifiers), .remoteURL(rhsURLProvider, _, rhsImageModifiers) ): return lhsURLProvider.url == rhsURLProvider.url && lhsImageModifiers == rhsImageModifiers case let (.localImage(lhs), .localImage(rhs)): return lhs.uiImage == rhs.uiImage default: return false } } } extension ImageContent: Hashable { public func hash(into hasher: inout Hasher) { switch self { case let .remoteURL(urlProvider, _, imageModifiers): hasher.combine(urlProvider.url) hasher.combine(imageModifiers) case let .localImage(uiImageProvider): hasher.combine(uiImageProvider.uiImage) } } }
23.092593
71
0.726544
bbb3a6acdfa31ce7ed65206a82acbba0923bb079
3,347
// // Created by Александр Цикин on 2018-11-20. // import Foundation import RxSwift import RxCocoa import RichHarvest_Core_Core public class TimerViewController: NSViewController { @IBOutlet weak var projectsPopUpButton: NSPopUpButton! @IBOutlet weak var tasksPopUpButton: NSPopUpButton! @IBOutlet weak var urlLabel: NSTextField! @IBOutlet weak var notesTextField: NSTextField! @IBOutlet weak var startButton: NSButton! var viewModel: TimerViewModel! private let dispose = DisposeBag() public override func viewDidLoad() { super.viewDidLoad() guard let viewModel = self.viewModel else { return } // TODO: generalize NSPopUpButton binding viewModel.projects .drive(onNext: { [weak self] (projects: [String]) in guard let `self` = self else { return } self.projectsPopUpButton.removeAllItems() self.projectsPopUpButton.addItems(withTitles: projects) }) .disposed(by: dispose) viewModel.projects .flatMap { _ in viewModel.selectedProject.asDriver() } .drive(onNext: { [weak self] (position: Int) in guard let `self` = self else { return } self.projectsPopUpButton.selectItem(at: position) }) .disposed(by: dispose) viewModel.tasks .drive(onNext: { [weak self] (projects: [String]) in guard let `self` = self else { return } self.tasksPopUpButton.removeAllItems() self.tasksPopUpButton.addItems(withTitles: projects) }) .disposed(by: dispose) viewModel.tasks .flatMap { _ in viewModel.selectedTask.asDriver() } .drive(onNext: { [weak self] (position: Int) in guard let `self` = self else { return } self.tasksPopUpButton.selectItem(at: position) }) .disposed(by: dispose) viewModel.url.drive(urlLabel.rx.text).disposed(by: dispose) viewModel.notes .filter { [unowned self] in self.notesTextField.stringValue != $0 } .bind(to: notesTextField.rx.text) .disposed(by: dispose) notesTextField.rx.text .map { $0 ?? "" } .filter { [unowned self] in self.viewModel.notes.value != $0 } .bind(to: viewModel.notes) .disposed(by: dispose) startButton.rx.tap.bind(to: viewModel.startTap).disposed(by: dispose) } public override func viewWillAppear() { super.viewWillAppear() viewModel.viewWillAppear() } @IBAction func projectSelected(_ sender: Any) { guard let item = projectsPopUpButton.selectedItem, let index = projectsPopUpButton.menu?.items.firstIndex(of: item) else { return } viewModel.selectedProject.accept(index) } @IBAction func taskSelected(_ sender: Any) { guard let item = tasksPopUpButton.selectedItem, let index = tasksPopUpButton.menu?.items.firstIndex(of: item) else { return } viewModel.selectedTask.accept(index) } } extension TimerViewController { func inject(viewModel: TimerViewModel) { self.viewModel = viewModel } }
30.990741
79
0.606513
16409be5561fbed50368caeab6366ba51391ecbb
1,411
// // AppDelegate.swift // Instafilter // // Created by Brian Sipple on 11/27/19. // Copyright © 2019 CypherPoet. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
45.516129
179
0.751949
d7a07edc36db7ab065c531c30a6625066eca9d35
2,186
// // AppDelegate.swift // tip calc spring // // Created by Buitrago, Uriel on 1/23/19. // Copyright © 2019 Buitrago, Uriel. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.510638
285
0.754803
7101098518bbe1e33b1a5d334f3c560ab5b7f6b2
17,719
import Foundation import CoreLocation import MapboxNavigationNative import MapboxMobileEvents import MapboxDirections import Polyline import Turf /** A `RouteController` tracks the user’s progress along a route, posting notifications as the user reaches significant points along the route. On every location update, the route controller evaluates the user’s location, determining whether the user remains on the route. If not, the route controller calculates a new route. `RouteController` is responsible for the core navigation logic whereas `NavigationViewController` is responsible for displaying a default drop-in navigation UI. */ open class RouteController: NSObject { public enum DefaultBehavior { public static let shouldRerouteFromLocation: Bool = true public static let shouldDiscardLocation: Bool = true public static let didArriveAtWaypoint: Bool = true public static let shouldPreventReroutesWhenArrivingAtWaypoint: Bool = true public static let shouldDisableBatteryMonitoring: Bool = true } let navigator = Navigator() public var route: Route { get { return routeProgress.route } set { routeProgress = RouteProgress(route: newValue, options: routeProgress.routeOptions) updateNavigator(with: routeProgress) } } private var _routeProgress: RouteProgress { willSet { resetObservation(for: _routeProgress) } didSet { movementsAwayFromRoute = 0 updateNavigator(with: _routeProgress) updateObservation(for: _routeProgress) } } var movementsAwayFromRoute = 0 var routeTask: URLSessionDataTask? var lastRerouteLocation: CLLocation? var didFindFasterRoute = false var isRerouting = false var userSnapToStepDistanceFromManeuver: CLLocationDistance? var previousArrivalWaypoint: Waypoint? var isFirstLocation: Bool = true public var config: NavigatorConfig? { get { return navigator.getConfig() } set { navigator.setConfigFor(newValue) } } /** Details about the user’s progress along the current route, leg, and step. */ public var routeProgress: RouteProgress { get { return _routeProgress } set { if let location = self.location { delegate?.router(self, willRerouteFrom: location) } _routeProgress = newValue announce(reroute: routeProgress.route, at: rawLocation, proactive: didFindFasterRoute) } } /** The raw location, snapped to the current route. - important: If the rawLocation is outside of the route snapping tolerances, this value is nil. */ var snappedLocation: CLLocation? { let status = navigator.getStatusForTimestamp(Date()) guard status.routeState == .tracking || status.routeState == .complete else { return nil } return CLLocation(status.location) } var heading: CLHeading? /** The most recently received user location. - note: This is a raw location received from `locationManager`. To obtain an idealized location, use the `location` property. */ public var rawLocation: CLLocation? { didSet { if isFirstLocation == true { isFirstLocation = false } } } public var reroutesProactively: Bool = true var lastProactiveRerouteDate: Date? /** The route controller’s delegate. */ public weak var delegate: RouterDelegate? /** The route controller’s associated location manager. */ public unowned var dataSource: RouterDataSource /** The Directions object used to create the route. */ public var directions: Directions /** The idealized user location. Snapped to the route line, if applicable, otherwise raw. - seeAlso: snappedLocation, rawLocation */ public var location: CLLocation? { return snappedLocation ?? rawLocation } required public init(along route: Route, options: RouteOptions, directions: Directions = Directions.shared, dataSource source: RouterDataSource) { self.directions = directions self._routeProgress = RouteProgress(route: route, options: options) self.dataSource = source UIDevice.current.isBatteryMonitoringEnabled = true super.init() updateNavigator(with: _routeProgress) updateObservation(for: _routeProgress) } deinit { resetObservation(for: _routeProgress) } func resetObservation(for progress: RouteProgress) { progress.legIndexHandler = nil } func updateObservation(for progress: RouteProgress) { progress.legIndexHandler = { [weak self] (oldValue, newValue) in guard newValue != oldValue else { return } self?.updateRouteLeg(to: newValue) } } /// updateNavigator is used to pass the new progress model onto nav-native. private func updateNavigator(with progress: RouteProgress) { let encoder = JSONEncoder() encoder.userInfo[.options] = progress.routeOptions guard let routeData = try? encoder.encode(progress.route), let routeJSONString = String(data: routeData, encoding: .utf8) else { return } // TODO: Add support for alternative route navigator.setRouteForRouteResponse(routeJSONString, route: 0, leg: UInt32(routeProgress.legIndex)) } /// updateRouteLeg is used to notify nav-native of the developer changing the active route-leg. private func updateRouteLeg(to value: Int) { let legIndex = UInt32(value) navigator.changeRouteLeg(forRoute: 0, leg: legIndex) let newStatus = navigator.changeRouteLeg(forRoute: 0, leg: legIndex) updateIndexes(status: newStatus, progress: routeProgress) } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } guard delegate?.router(self, shouldDiscard: location) ?? DefaultBehavior.shouldDiscardLocation else { return } rawLocation = locations.last locations.forEach { navigator.updateLocation(for: FixLocation($0)) } let status = navigator.getStatusForTimestamp(location.timestamp) // Notify observers if the step’s remaining distance has changed. update(progress: routeProgress, with: CLLocation(status.location), rawLocation: location) let willReroute = !userIsOnRoute(location, status: status) && delegate?.router(self, shouldRerouteFrom: location) ?? DefaultBehavior.shouldRerouteFromLocation updateIndexes(status: status, progress: routeProgress) updateRouteLegProgress(status: status) updateSpokenInstructionProgress(status: status, willReRoute: willReroute) updateVisualInstructionProgress(status: status) if willReroute { reroute(from: location, along: routeProgress) } // Check for faster route proactively (if reroutesProactively is enabled) checkForFasterRoute(from: location, routeProgress: routeProgress) } func updateIndexes(status: NavigationStatus, progress: RouteProgress) { let newLegIndex = Int(status.legIndex) let newStepIndex = Int(status.stepIndex) let newIntersectionIndex = Int(status.intersectionIndex) if (newLegIndex != progress.legIndex) { progress.legIndex = newLegIndex } if (newStepIndex != progress.currentLegProgress.stepIndex) { progress.currentLegProgress.stepIndex = newStepIndex } if (newIntersectionIndex != progress.currentLegProgress.currentStepProgress.intersectionIndex) { progress.currentLegProgress.currentStepProgress.intersectionIndex = newIntersectionIndex } if let spokenIndexPrimitive = status.voiceInstruction?.index, progress.currentLegProgress.currentStepProgress.spokenInstructionIndex != Int(spokenIndexPrimitive) { progress.currentLegProgress.currentStepProgress.spokenInstructionIndex = Int(spokenIndexPrimitive) } if let visualInstructionIndex = status.bannerInstruction?.index, routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex != Int(visualInstructionIndex) { routeProgress.currentLegProgress.currentStepProgress.visualInstructionIndex = Int(visualInstructionIndex) } } func updateSpokenInstructionProgress(status: NavigationStatus, willReRoute: Bool) { let didUpdate = status.voiceInstruction?.index != nil // Announce voice instruction if it was updated and we are not going to reroute if didUpdate && !willReRoute, let spokenInstruction = routeProgress.currentLegProgress.currentStepProgress.currentSpokenInstruction { announcePassage(of: spokenInstruction, routeProgress: routeProgress) } } func updateVisualInstructionProgress(status: NavigationStatus) { let didUpdate = status.bannerInstruction != nil // Announce visual instruction if it was updated or it is the first location being reported if didUpdate || isFirstLocation { if let instruction = routeProgress.currentLegProgress.currentStepProgress.currentVisualInstruction { announcePassage(of: instruction, routeProgress: routeProgress) } } } func updateRouteLegProgress(status: NavigationStatus) { let legProgress = routeProgress.currentLegProgress guard let currentDestination = legProgress.leg.destination else { preconditionFailure("Route legs used for navigation must have destinations") } let remainingVoiceInstructions = legProgress.currentStepProgress.remainingSpokenInstructions ?? [] // We are at least at the "You will arrive" instruction if legProgress.remainingSteps.count <= 2 && remainingVoiceInstructions.count <= 2 { let willArrive = status.routeState == .tracking let didArrive = status.routeState == .complete && currentDestination != previousArrivalWaypoint if willArrive { delegate?.router(self, willArriveAt: currentDestination, after: legProgress.durationRemaining, distance: legProgress.distanceRemaining) } else if didArrive { previousArrivalWaypoint = currentDestination legProgress.userHasArrivedAtWaypoint = true let advancesToNextLeg = delegate?.router(self, didArriveAt: currentDestination) ?? DefaultBehavior.didArriveAtWaypoint guard !routeProgress.isFinalLeg && advancesToNextLeg else { return } let legIndex = Int(status.legIndex + 1) updateRouteLeg(to: legIndex) } } } private func update(progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { let stepProgress = progress.currentLegProgress.currentStepProgress let step = stepProgress.step //Increment the progress model guard let polyline = step.shape else { preconditionFailure("Route steps used for navigation must have shape data") } if let closestCoordinate = polyline.closestCoordinate(to: rawLocation.coordinate) { let remainingDistance = polyline.distance(from: closestCoordinate.coordinate)! let distanceTraveled = step.distance - remainingDistance stepProgress.distanceTraveled = distanceTraveled //Fire the delegate method delegate?.router(self, didUpdate: progress, with: location, rawLocation: rawLocation) //Fire the notification (for now) NotificationCenter.default.post(name: .routeControllerProgressDidChange, object: self, userInfo: [ NotificationUserInfoKey.routeProgressKey: progress, NotificationUserInfoKey.locationKey: location, //guaranteed value NotificationUserInfoKey.rawLocationKey: rawLocation, //raw ]) } } private func announcePassage(of spokenInstructionPoint: SpokenInstruction, routeProgress: RouteProgress) { delegate?.router(self, didPassSpokenInstructionPoint: spokenInstructionPoint, routeProgress: routeProgress) let info: [NotificationUserInfoKey: Any] = [ .routeProgressKey: routeProgress, .spokenInstructionKey: spokenInstructionPoint, ] NotificationCenter.default.post(name: .routeControllerDidPassSpokenInstructionPoint, object: self, userInfo: info) } private func announcePassage(of visualInstructionPoint: VisualInstructionBanner, routeProgress: RouteProgress) { delegate?.router(self, didPassVisualInstructionPoint: visualInstructionPoint, routeProgress: routeProgress) let info: [NotificationUserInfoKey: Any] = [ .routeProgressKey: routeProgress, .visualInstructionKey: visualInstructionPoint, ] NotificationCenter.default.post(name: .routeControllerDidPassVisualInstructionPoint, object: self, userInfo: info) } /** Returns an estimated location at a given timestamp. The timestamp must be a future timestamp compared to the last location received by the location manager. */ public func projectedLocation(for timestamp: Date) -> CLLocation { return CLLocation(navigator.getStatusForTimestamp(timestamp).location) } public func advanceLegIndex(location: CLLocation) { let status = navigator.getStatusForTimestamp(location.timestamp) routeProgress.legIndex = Int(status.legIndex) } public func enableLocationRecording() { navigator.toggleHistoryFor(onOff: true) } public func disableLocationRecording() { navigator.toggleHistoryFor(onOff: false) } public func locationHistory() -> String? { return navigator.getHistory() } } extension RouteController: Router { public func userIsOnRoute(_ location: CLLocation) -> Bool { return userIsOnRoute(location, status: nil) } public func userIsOnRoute(_ location: CLLocation, status: NavigationStatus?) -> Bool { guard let destination = routeProgress.currentLeg.destination else { preconditionFailure("Route legs used for navigation must have destinations") } // If the user has arrived, do not continue monitor reroutes, step progress, etc if routeProgress.currentLegProgress.userHasArrivedAtWaypoint && (delegate?.router(self, shouldPreventReroutesWhenArrivingAt: destination) ?? DefaultBehavior.shouldPreventReroutesWhenArrivingAtWaypoint) { return true } let status = status ?? navigator.getStatusForTimestamp(location.timestamp) let offRoute = status.routeState == .offRoute return !offRoute } public func reroute(from location: CLLocation, along progress: RouteProgress) { if let lastRerouteLocation = lastRerouteLocation { guard location.distance(from: lastRerouteLocation) >= RouteControllerMaximumDistanceBeforeRecalculating else { return } } delegate?.router(self, willRerouteFrom: location) NotificationCenter.default.post(name: .routeControllerWillReroute, object: self, userInfo: [ NotificationUserInfoKey.locationKey: location, ]) self.lastRerouteLocation = location // Avoid interrupting an ongoing reroute if isRerouting { return } isRerouting = true getDirections(from: location, along: progress) { [weak self] (session, result) in self?.isRerouting = false guard let strongSelf: RouteController = self else { return } switch result { case let .success(response): guard let route = response.routes?.first else { return } guard case let .route(routeOptions) = response.options else { return } //TODO: Can a match hit this codepoint? strongSelf._routeProgress = RouteProgress(route: route, options: routeOptions, legIndex: 0) strongSelf._routeProgress.currentLegProgress.stepIndex = 0 strongSelf.announce(reroute: route, at: location, proactive: false) case let .failure(error): strongSelf.delegate?.router(strongSelf, didFailToRerouteWith: error) NotificationCenter.default.post(name: .routeControllerDidFailToReroute, object: self, userInfo: [ NotificationUserInfoKey.routingErrorKey: error, ]) return } } } } extension RouteController: InternalRouter { }
40.088235
322
0.659518
7aeb4d5442e904d05879cb3b71de88fbe6fe8395
2,154
// // AppDelegate.swift // JNBWebView // // Created by Michael De Wolfe on 2015-05-07. // Copyright (c) 2015 acmethunder. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.829787
285
0.75441
232f894f444ed29a2ffd17fd4634f903c46f7a39
2,248
import Foundation import UIKit import PromiseKit import Alamofire public class AlertController : UIAlertController { var window: UIWindow? static var current: AlertController? public static func show(message: String = "Something went wrong.", title: String? = "Error") { if current == nil { let alert = AlertController(title: title, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { (_) in } alert.addAction(ok) alert.show() current = alert } } public static func show(error: Error, title: String? = "Error") { switch error { case DocResponseError.noJSON(let response): #if DEBUG let status = response.response?.statusCode ?? 0 let data = response.data.flatMap({ String(data: $0, encoding: String.Encoding.utf8) }) ?? "" print(status, data) #endif AlertController.show(title: title) case DocResponseError.serialization(_, let json): #if DEBUG print(json) #endif AlertController.show(title: title) case let nserr as NSError: AlertController.show(message: nserr.localizedDescription, title: title) default: AlertController.show(title: title) } } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) window?.isHidden = true window = nil AlertController.current = nil } func show() { let controller = AlertBackgroundController() let win = UIWindow(frame: UIScreen.main.bounds) win.rootViewController = controller win.backgroundColor = UIColor.clear win.windowLevel = UIWindowLevelAlert + 10 win.makeKeyAndVisible() self.window = win controller.present(self, animated: true, completion: nil) } } class AlertBackgroundController : UIViewController { override func loadView() { view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = UIColor.clear } }
29.578947
108
0.597865
1e8c03204b2b638860639629e685cd18720a3875
1,772
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public class AppInfosResponse: APIModel { public var data: [AppInfo] public var links: PagedDocumentLinks public var included: [Included]? public var meta: PagingInformation? public init(data: [AppInfo], links: PagedDocumentLinks, included: [Included]? = nil, meta: PagingInformation? = nil) { self.data = data self.links = links self.included = included self.meta = meta } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArray("data") links = try container.decode("links") included = try container.decodeArrayIfPresent("included") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(data, forKey: "data") try container.encode(links, forKey: "links") try container.encodeIfPresent(included, forKey: "included") try container.encodeIfPresent(meta, forKey: "meta") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? AppInfosResponse else { return false } guard self.data == object.data else { return false } guard self.links == object.links else { return false } guard self.included == object.included else { return false } guard self.meta == object.meta else { return false } return true } public static func == (lhs: AppInfosResponse, rhs: AppInfosResponse) -> Bool { return lhs.isEqual(to: rhs) } }
31.642857
122
0.663657
f76e516cb935000529d63f3ac71aee5d692ef0e9
1,306
// Copyright SIX DAY LLC. All rights reserved. import UIKit class LockEnterPasscodeCoordinator: Coordinator { var coordinators: [Coordinator] = [] let window: UIWindow = UIWindow() private let model: LockEnterPasscodeViewModel private let lock: LockInterface private lazy var lockEnterPasscodeViewController: LockEnterPasscodeViewController = { return LockEnterPasscodeViewController(model: model) }() init(model: LockEnterPasscodeViewModel, lock: LockInterface = Lock()) { self.window.windowLevel = UIWindowLevelStatusBar + 1.0 self.model = model self.lock = lock lockEnterPasscodeViewController.unlockWithResult = { [weak self] (state, bioUnlock) in if state { self?.stop() } } } func start() { guard lock.isPasscodeSet() else { return } window.rootViewController = lockEnterPasscodeViewController window.makeKeyAndVisible() } func showAuthentication() { guard lock.isPasscodeSet() else { return } lockEnterPasscodeViewController.showKeyboard() lockEnterPasscodeViewController.showBioMerickAuth() lockEnterPasscodeViewController.cleanUserInput() } func stop() { window.isHidden = true } }
30.372093
94
0.673813
72120d121552a99dbcb85e5a4ad512872b4c1371
757
// // AppDelegate.swift // Brastlewark // // Created by Gabriel Z on 18/07/20. // Copyright © 2020 Zempoalteca. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } // MARK: - Functions func goToDashboard() { let dashboard = DashboardViewController() let navController = UINavigationController(rootViewController: dashboard) window?.rootViewController = navController window?.makeKeyAndVisible() } }
22.939394
81
0.68428
2084462afd17f0e3e5580fe0701e8979d31f2ab1
782
// // Observable.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** A type-erased `ObservableType`. It represents a push style sequence. */ public class Observable<Element> : ObservableType { /** Type of elements in sequence. */ public typealias E = Element public init() { #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif } public func subscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable { return abstractMethod() } public func asObservable() -> Observable<E> { return self } deinit { #if TRACE_RESOURCES OSAtomicDecrement32(&resourceCount) #endif } }
18.619048
86
0.63555
8a2c0af9184b3de84bb0bdc9e96b75e51ec46df2
1,576
// // WorkspaceMember.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class WorkspaceMember: Codable { public enum MemberType: String, Codable { case user = "USER" case group = "GROUP" } /** The globally unique identifier for the object. */ public var _id: String? public var name: String? public var workspace: DomainEntityRef? /** The workspace member type. */ public var memberType: MemberType? public var member: DomainEntityRef? public var user: User? public var group: Group? public var securityProfile: SecurityProfile? /** The URI for this object */ public var selfUri: String? public init(_id: String?, name: String?, workspace: DomainEntityRef?, memberType: MemberType?, member: DomainEntityRef?, user: User?, group: Group?, securityProfile: SecurityProfile?, selfUri: String?) { self._id = _id self.name = name self.workspace = workspace self.memberType = memberType self.member = member self.user = user self.group = group self.securityProfile = securityProfile self.selfUri = selfUri } public enum CodingKeys: String, CodingKey { case _id = "id" case name case workspace case memberType case member case user case group case securityProfile case selfUri } }
23.176471
207
0.602792
465d2375563a5b7ebf4b2f9aebca46a0247a44a6
4,133
import Foundation struct Vein { let x1: Int let x2: Int let y1: Int let y2: Int } func createVein(str: String) -> Vein { let elems = str.components(separatedBy: ", ") let v1 = Int(String(elems[0].dropFirst(2))) let rangeElems = String(elems[1].dropFirst(2)).components(separatedBy: "..") let v21 = Int(rangeElems[0]) let v22 = Int(rangeElems[1]) if (elems[0].prefix(1) == "x") { return Vein(x1: v1!, x2: v1!, y1: v21!, y2: v22!) } return Vein(x1: v21!, x2: v22!, y1: v1!, y2: v1!) } func waterReach(veins: [Vein], x: Int, y: Int) -> (Int, Int) { let minY = veins.min { a, b in a.y1 < b.y1 }!.y1 let maxY = veins.max { a, b in a.y2 < b.y2 }!.y2 let minX = veins.min { a, b in a.x1 < b.x1 }!.x1 - 1 let maxX = veins.max { a, b in a.x2 < b.x2 }!.x2 + 1 let H = maxY - minY + 1 let W = maxX - minX + 1 var grid = Array(repeating: Array(repeating: ".", count: W), count: H) var drops = Array(repeating: Array(repeating: false, count: W), count: H) func fill(vein: Vein) { for y in vein.y1...vein.y2 { let i = y - minY for x in vein.x1...vein.x2 { let j = x - minX grid[i][j] = "#" } } } veins.forEach(fill) func drop(x: Int, y: Int) -> Int { if (x < 0 || x >= W || y < 0 || y >= H) { return 0 } var s = 0 var i = y while (i < H && (grid[i][x] == "." || grid[i][x] == "|")) { if (grid[i][x] == ".") { s += 1 } grid[i][x] = "|" i += 1 } if (i < H && i - 1 >= 0) { i -= 1 var hasDrop = false var lj = x while (lj >= 0 && (grid[i][lj] == "." || grid[i][lj] == "|") && (grid[i + 1][lj] == "#" || grid[i + 1][lj] == "~")) { if (grid[i][lj] == ".") { s += 1 } grid[i][lj] = "|" lj -= 1 } if (lj >= 0 && grid[i][lj] != "#" && (grid[i + 1][lj] == "." || grid[i + 1][lj] == "|")) { if (grid[i][lj] == ".") { s += 1 } grid[i][lj] = "|" hasDrop = true if (!drops[i + 1][lj]) { drops[i + 1][lj] = true s += drop(x: lj, y: i + 1) } } var rj = x while (rj >= 0 && (grid[i][rj] == "." || grid[i][rj] == "|") && (grid[i + 1][rj] == "#" || grid[i + 1][rj] == "~")) { if (grid[i][rj] == ".") { s += 1 } grid[i][rj] = "|" rj += 1 } if (rj < W && grid[i][rj] != "#" && (grid[i + 1][rj] == "." || grid[i + 1][rj] == "|")) { if (grid[i][rj] == ".") { s += 1 } grid[i][rj] = "|" hasDrop = true if (!drops[i + 1][rj]) { drops[i + 1][rj] = true s += drop(x: rj, y: i + 1) } } if (!hasDrop) { for j in (lj + 1)...(rj - 1) { grid[i][j] = "~" } s += drop(x: x, y: i - 1) } } return s } let reach = drop(x: max(x, minX) - minX, y: max(y, minY) - minY) var remaining = 0 for i in 0..<H { for j in 0..<W { if (grid[i][j] == "~") { remaining += 1 } } } return (reach, remaining) } let filename = "17.input" let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) let url = URL(fileURLWithPath: filename, relativeTo: currentDirectoryURL) let contents = try! String(contentsOfFile: url.path) let lines = contents.split { $0 == "\n" }.map(String.init) let veins = lines.map(createVein) let (part1, part2) = waterReach(veins: veins, x: 500, y: 0) print("Part 1: \(part1)") print("Part 2: \(part2)")
31.310606
129
0.382047
39e9d71fcf52e418916aa39950f63edca7c06a4e
256
import Foundation import CryptoSwift extension Data { init(hex: String) { self.init(Array<UInt8>(hex: hex)) } var bytes: Array<UInt8> { Array(self) } func toHexString() -> String { bytes.toHexString() } }
15.058824
41
0.574219
c122855bad2a2a68950c6939e00d9749b9a91f33
661
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "DBSideMenu", platforms: [ .iOS(.v10) ], products: [ .library( name: "DBSideMenu", targets: ["DBSideMenu"] ) ], dependencies: [ ], targets: [ .target( name: "DBSideMenu", dependencies: [ ], path: "DBSideMenu", exclude: [ "DBSideMenuExample" ] ), ], swiftLanguageVersions: [.v5] )
20.65625
96
0.491679
793982741f0caa2d690b65579db5340cd18fd6aa
1,836
// // GeocodingLocation.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct GeocodingLocation: Codable { public var point: GeocodingPoint? /** The OSM ID of the entity */ public var osmId: String? /** N &#x3D; node, R &#x3D; relation, W &#x3D; way */ public var osmType: String? /** The OSM key of the entity */ public var osmKey: String? /** The name of the entity. Can be a boundary, POI, address, etc */ public var name: String? /** The country of the address */ public var country: String? /** The city of the address */ public var city: String? /** The state of the address */ public var state: String? /** The street of the address */ public var street: String? /** The housenumber of the address */ public var housenumber: String? /** The postcode of the address */ public var postcode: String? public init(point: GeocodingPoint?, osmId: String?, osmType: String?, osmKey: String?, name: String?, country: String?, city: String?, state: String?, street: String?, housenumber: String?, postcode: String?) { self.point = point self.osmId = osmId self.osmType = osmType self.osmKey = osmKey self.name = name self.country = country self.city = city self.state = state self.street = street self.housenumber = housenumber self.postcode = postcode } public enum CodingKeys: String, CodingKey { case point case osmId = "osm_id" case osmType = "osm_type" case osmKey = "osm_key" case name case country case city case state case street case housenumber case postcode } }
25.150685
215
0.610022
cc3c99c07c0b2d4c30f4fad68d91cebb22590e28
511
// // ViewController.swift // BlinkingLabel // // Created by zhongxueyu on 01/30/2019. // Copyright (c) 2019 zhongxueyu. 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. } }
20.44
80
0.675147
8f95f68d2b1843debd99ad0ce4a087eb03e0fc39
940
import Foundation /* This method takes an unsorted array in input & returns the third largest number form Array as input Time complexoty: O(n) */ func thirdLargetInArray(arr:[Int]) { var first:Int = arr[0] var second:Int = 0 var third:Int = 0 for i in 0..<arr.count { if arr[i] > first && arr[i] != first { third = second second = first first = arr[i] } else if arr[i] > second && arr[i] != second && arr[i] != first { third = second second = arr[i] } else if arr[i] > third && arr[i] != third && arr[i] != first && arr[i] != second { print(second) third = arr[i] print("Third after changing = \(third)") } } print("Third largest element in array is \(third)") } let inputArr = [4,5,3,2,15,7,6,25,13,14,17,8,9,18,17,17,25,26] thirdLargetInArray(arr: inputArr)
26.857143
100
0.531915
5bd657b01ba484e09aaf3fad25250f4f1af3533e
8,171
// // XCTest+Rx.swift // RxTest // // Created by Krunoslav Zaher on 12/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /** These methods are conceptually extensions of `XCTestCase` but because referencing them in closures would require specifying `self.*`, they are made global. */ //extension XCTestCase { /** Factory method for an `.next` event recorded at a given time with a given value. - parameter time: Recorded virtual time the `.next` event occurs. - parameter element: Next sequence element. - returns: Recorded event in time. */ public func next<T>(_ time: TestTime, _ element: T) -> Recorded<Event<T>> { return Recorded(time: time, value: .next(element)) } /** Factory method for an `.completed` event recorded at a given time. - parameter time: Recorded virtual time the `.completed` event occurs. - parameter type: Sequence elements type. - returns: Recorded event in time. */ public func completed<T>(_ time: TestTime, _ type: T.Type = T.self) -> Recorded<Event<T>> { return Recorded(time: time, value: .completed) } /** Factory method for an `.error` event recorded at a given time with a given error. - parameter time: Recorded virtual time the `.completed` event occurs. */ public func error<T>(_ time: TestTime, _ error: Swift.Error, _ type: T.Type = T.self) -> Recorded<Event<T>> { return Recorded(time: time, value: .error(error)) } //} import XCTest /** Asserts two lists of events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual<T: Equatable>(_ lhs: [Event<T>], _ rhs: [Event<T>], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } /** Asserts two lists of events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual<T: Equatable>(_ lhs: [SingleEvent<T>], _ rhs: [SingleEvent<T>], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } /** Asserts two lists of events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual<T: Equatable>(_ lhs: [MaybeEvent<T>], _ rhs: [MaybeEvent<T>], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } /** Asserts two lists of events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual(_ lhs: [CompletableEvent], _ rhs: [CompletableEvent], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } /** Asserts two lists of Recorded events are equal. Recorded events are equal if times are equal and recoreded events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual<T: Equatable>(_ lhs: [Recorded<Event<T>>], _ rhs: [Recorded<Event<T>>], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } /** Asserts two lists of Recorded events with optional elements are equal. Recorded events are equal if times are equal and recoreded events are equal. Event is considered equal if: * `Next` events are equal if they have equal corresponding elements. * `Error` events are equal if errors have same domain and code for `NSError` representation and have equal descriptions. * `Completed` events are always equal. - parameter lhs: first set of events. - parameter lhs: second set of events. */ public func XCTAssertEqual<T: Equatable>(_ lhs: [Recorded<Event<T?>>], _ rhs: [Recorded<Event<T?>>], file: StaticString = #file, line: UInt = #line) { let leftEquatable = lhs.map { AnyEquatable(target: $0, comparer: ==) } let rightEquatable = rhs.map { AnyEquatable(target: $0, comparer: ==) } #if os(Linux) XCTAssertEqual(leftEquatable, rightEquatable) #else XCTAssertEqual(leftEquatable, rightEquatable, file: file, line: line) #endif if leftEquatable == rightEquatable { return } printSequenceDifferences(lhs, rhs, ==) } func printSequenceDifferences<E>(_ lhs: [E], _ rhs: [E], _ equal: (E, E) -> Bool) { print("Differences:") for (index, elements) in zip(lhs, rhs).enumerated() { let l = elements.0 let r = elements.1 if !equal(l, r) { print("lhs[\(index)]:\n \(l)") print("rhs[\(index)]:\n \(r)") } } let shortest = min(lhs.count, rhs.count) for (index, element) in lhs[shortest ..< lhs.count].enumerated() { print("lhs[\(index + shortest)]:\n \(element)") } for (index, element) in rhs[shortest ..< rhs.count].enumerated() { print("rhs[\(index + shortest)]:\n \(element)") } }
35.526087
150
0.67764
eb1ec828ba524d852cd0015744b874a48020b1b5
6,366
// // CubeByDraggingPlugin.swift // ARPen // // Created by Philipp Wacker on 09.03.18. // Copyright © 2018 RWTH Aachen. All rights reserved. // import Foundation import ARKit class CubeByDraggingPlugin: Plugin { /** The starting point is the point of the pencil where the button was first pressed. If this var is nil, there was no initial point */ private var startingPoint: SCNVector3? ///final box dimensions private var finalBoxWidth: Double? private var finalBoxHeight: Double? private var finalBoxLength: Double? ///final box position private var finalBoxCenterPos: SCNVector3? override init() { super.init() self.pluginImage = UIImage.init(named: "CubeByDraggingPlugin") self.pluginInstructionsImage = UIImage.init(named: "CubePluginInstructions") self.pluginIdentifier = "Cube" self.needsBluetoothARPen = false self.pluginGroupName = "Primitives" self.pluginDisabledImage = UIImage.init(named: "ARMenusPluginDisabled") } override func didUpdateFrame(scene: PenScene, buttons: [Button : Bool]) { guard scene.markerFound else { //Don't reset the previous point to avoid restarting cube if the marker detection failed for some frames //self.startingPoint = nil return } //Check state of the first button -> used to create the cube let pressed = buttons[Button.Button1]! //if the button is pressed -> either set the starting point of the cube (first action) or scale the cube to fit from the starting point to the current point if pressed { if let startingPoint = self.startingPoint { //see if there is an active box node that is currently being drawn. Otherwise create it guard let boxNode = scene.drawingNode.childNode(withName: "currentDragBoxNode", recursively: false) else { let boxNode = SCNNode() boxNode.name = "currentDragBoxNode" scene.drawingNode.addChildNode(boxNode) return } //calculate the dimensions of the box to fit between the starting point and the current pencil position (opposite corners) let boxWidth = abs(scene.pencilPoint.position.x - startingPoint.x) let boxHeight = abs(scene.pencilPoint.position.y - startingPoint.y) let boxLength = abs(scene.pencilPoint.position.z - startingPoint.z) //get the box node geometry (if it is not a SCNBox, create that with the calculated dimensions) guard let boxNodeGeometry = boxNode.geometry as? SCNBox else { boxNode.geometry = SCNBox.init(width: CGFloat(boxWidth), height: CGFloat(boxHeight), length: CGFloat(boxLength), chamferRadius: 0.0) return } //set the dimensions of the box boxNodeGeometry.width = CGFloat(boxWidth) boxNodeGeometry.height = CGFloat(boxHeight) boxNodeGeometry.length = CGFloat(boxLength) //calculate the center position of the box node (halfway between the two corners startingPoint and current pencil position) let boxCenterXPosition = startingPoint.x + (scene.pencilPoint.position.x - startingPoint.x)/2 let boxCenterYPosition = startingPoint.y + (scene.pencilPoint.position.y - startingPoint.y)/2 let boxCenterZPosition = startingPoint.z + (scene.pencilPoint.position.z - startingPoint.z)/2 //set the position of boxNode to the center of the box boxNode.worldPosition = SCNVector3.init(boxCenterXPosition, boxCenterYPosition, boxCenterZPosition) //save dimensions in variables for ARPBox instantiation self.finalBoxWidth = Double(boxWidth) self.finalBoxHeight = Double(boxHeight) self.finalBoxLength = Double(boxLength) } else { //if the button is pressed but no startingPoint exists -> first frame with the button pressed. Set current pencil position as the start point self.startingPoint = scene.pencilPoint.position } } //Button not pressed anymore else { //if the button is not pressed, check if a startingPoint is set -> released button. Reset the startingPoint to nil and set the name of the drawn box to "finished" if self.startingPoint != nil { self.startingPoint = nil if let boxNode = scene.drawingNode.childNode(withName: "currentDragBoxNode", recursively: false) { if (finalBoxLength != nil && finalBoxWidth != nil && finalBoxHeight != nil) { //assign a random name to the boxNode for identification in further process boxNode.name = randomString(length: 32) //remove "SceneKit Box" boxNode.removeFromParentNode() //save position for new ARPBox self.finalBoxCenterPos = boxNode.worldPosition let box = ARPBox(width: self.finalBoxWidth!, height: self.finalBoxHeight!, length: self.finalBoxLength!) DispatchQueue.main.async { self.currentScene?.drawingNode.addChildNode(box) } box.localTranslate(by: self.finalBoxCenterPos!) box.applyTransform() let buildingAction = PrimitiveBuildingAction(occtRef: box.occtReference!, scene: self.currentScene!, box: box) self.undoRedoManager?.actionDone(buildingAction) } } } } } }
45.148936
174
0.574144
1db2ccd5dd6b66b3b52bd73aef6c94ae27973af5
145
/* Block.swift This source file is part of the Headers open source project. Copyright ©[Current Date] the Headers project contributors. */
18.125
61
0.744828
fc2a2fabca2e380c16cfa88cd8a2d4d5a0f8c4c8
518
// // ChangeBodyWidthAction.swift // PrincessGuide // // Created by zzk on 2019/2/28. // Copyright © 2019 zzk. All rights reserved. // import Foundation class ChangeBodyWidthAction: ActionParameter { override func localizedDetail(of level: Int, property: Property, style: CDSettingsViewController.Setting.ExpressionStyle) -> String { let format = NSLocalizedString("Change body width to %@.", comment: "") return String(format: format, actionValue1.roundedString(roundingRule: nil)) } }
28.777778
137
0.722008
67e5905ac337bf2b7559bedf4b675fa0c37c63be
412
// // Hashable+Combined.swift // StyledText // // Created by Ryan Nystrom on 12/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation extension Hashable { public func combineHash<T: Hashable>(with hashableOther: T) -> Int { let ownHash = self.hashValue let otherHash = hashableOther.hashValue return (ownHash << 5) &+ ownHash &+ otherHash } }
20.6
72
0.657767
f57d841081a6b76c9df60643a3f3f71f3818245d
1,718
// // AbstractAnimation.swift // mikutap // // Created by Liuliet.Lee on 6/2/2019. // Copyright © 2019 Liuliet.Lee. All rights reserved. // import MetalKit class AbstractAnimation { internal var renderPipelineState: MTLRenderPipelineState! internal var device: MTLDevice! internal var commandEncoder: MTLRenderCommandEncoder! internal var aspect = Float() internal var vheight = Float() internal var vwidth = Float() internal var color = float4() required init(device: MTLDevice, width: CGFloat, height: CGFloat) { vheight = Float(height) vwidth = Float(width) self.aspect = Float(height / width) self.device = device color = ColorPool.shared.getShaderColor() } internal func registerShaders(vertexFunctionName: String,fragmentFunctionName: String) { let library = device.makeDefaultLibrary()! let vertexFunc = library.makeFunction(name: vertexFunctionName) let fragmentFunc = library.makeFunction(name: fragmentFunctionName) let rpld = MTLRenderPipelineDescriptor() rpld.vertexFunction = vertexFunc rpld.fragmentFunction = fragmentFunc rpld.colorAttachments[0].pixelFormat = .bgra8Unorm do { renderPipelineState = try device.makeRenderPipelineState(descriptor: rpld) } catch let error { fatalError("\(error)") } } @discardableResult func setCommandEncoder(cb: MTLCommandBuffer, rpd: MTLRenderPassDescriptor) -> Bool { commandEncoder = cb.makeRenderCommandEncoder(descriptor: rpd)! commandEncoder.setRenderPipelineState(renderPipelineState!) return true } }
32.415094
92
0.679278
1d465f1bb23fa7da3acb0e51c7367a50a50c019b
4,472
// // PhoneField.swift // LoginTest // // Created by 卢卓桓 on 2019/8/16. // Copyright © 2019 zhineng. All rights reserved. // import UIKit class PhoneField: UITextField { //保存上一次的文本内容 private var _previousText: String! //保持上一次的文本范围 private var _previousRange: UITextRange! override init(frame: CGRect) { super.init(frame: frame) //默认边框样式为圆角矩形 self.borderStyle = UITextField.BorderStyle.roundedRect //使用数字键盘 self.keyboardType = UIKeyboardType.numberPad } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //当本视图的父类视图改变的时候 override func willMove(toSuperview newSuperview: UIView?) { //监听值改变通知事件 if newSuperview != nil { NotificationCenter.default.addObserver(self, selector: #selector(phoneNumberFormat(_:)), name: UITextField.textDidChangeNotification, object: nil) }else{ NotificationCenter.default.removeObserver(self, name: UITextField.textDidChangeNotification, object: nil) } } //输入框内容改变时对其内容做格式化处理 @objc func phoneNumberFormat(_ notification: Notification) { let textField = notification.object as! UITextField if(!textField.isEqual(self)){ return } //输入的第一个数字必需为1 if textField.text != "" && Int(textField.text![0]) != 1 { //第1位输入非1数则使用原来值,且关闭停留在开始位置 textField.text = _previousText let start = textField.beginningOfDocument textField.selectedTextRange = textField.textRange(from: start, to: start) return } //当前光标的位置(后面会对其做修改) var cursorPostion = textField.offset(from: textField.beginningOfDocument, to: textField.selectedTextRange!.start) //过滤掉非数字字符,只保留数字 let digitsText = getDigitsText(string: textField.text!, cursorPosition: &cursorPostion) //避免超过11位的输入 if digitsText.count > 11 { textField.text = _previousText textField.selectedTextRange = _previousRange return } //得到带有分隔符的字符串 let hyphenText = getHyphenText(string: digitsText, cursorPosition: &cursorPostion, isAddSeparation: false) //将最终带有分隔符的字符串显示到textField上 textField.text = hyphenText //让光标停留在正确位置 let targetPostion = textField.position(from: textField.beginningOfDocument, offset: cursorPostion)! textField.selectedTextRange = textField.textRange(from: targetPostion, to: targetPostion) //现在的值和选中范围,供下一次输入使用 _previousText = self.text! _previousRange = self.selectedTextRange! } //除去非数字字符,同时确定光标正确位置 func getDigitsText(string:String, cursorPosition:inout Int) -> String{ //保存开始时光标的位置 let originalCursorPosition = cursorPosition //处理后的结果字符串 var result = "" var i = 0 //遍历每一个字符 for uni in string.unicodeScalars { //如果是数字则添加到返回结果中 if CharacterSet.decimalDigits.contains(uni) { result.append(string[i]) } //非数字则跳过,如果这个非法字符在光标位置之前,则光标需要向前移动 else{ if i < originalCursorPosition { cursorPosition = cursorPosition - 1 } } i = i + 1 } return result } //将分隔符插入现在的string中,同时确定光标正确位置 func getHyphenText(string:String, cursorPosition:inout Int, isAddSeparation: Bool) -> String { //保存开始时光标的位置 let originalCursorPosition = cursorPosition //处理后的结果字符串 var result = "" //遍历每一个字符 for i in 0 ..< string.count { if isAddSeparation{ //如果当前到了第4个、第8个数字,则先添加个分隔符 if i == 3 || i == 7 { result.append("-") //如果添加分隔符位置在光标前面,光标则需向后移动一位 if i < originalCursorPosition { cursorPosition = cursorPosition + 1 } } } result.append(string[i]) } return result } }
31.055556
158
0.551878
f708c48d9c8ab630803cf7f98f327cf7bbb70641
2,224
import BlueprintUI import UIKit public struct AttributedLabel: Element, Hashable { public var attributedText: NSAttributedString public var numberOfLines: Int = 0 /// An offset that will be applied to the rect used by `drawText(in:)`. /// /// This can be used to adjust the positioning of text within each line's frame, such as adjusting /// the way text is distributed within the line height. public var textRectOffset: UIOffset = .zero public init(attributedText: NSAttributedString, configure: (inout Self) -> Void = { _ in }) { self.attributedText = attributedText configure(&self) } public var content: ElementContent { struct Measurer: Measurable { private static let prototypeLabel = LabelView() var model: AttributedLabel func measure(in constraint: SizeConstraint) -> CGSize { let label = Self.prototypeLabel model.update(label: label) return label.sizeThatFits(constraint.maximum) } } return ElementContent( measurable: Measurer(model: self), measurementCachingKey: .init(type: Self.self, input: self) ) } private func update(label: LabelView) { label.attributedText = attributedText label.numberOfLines = numberOfLines label.textRectOffset = textRectOffset } public func backingViewDescription(with context: ViewDescriptionContext) -> ViewDescription? { return LabelView.describe { config in config.apply(update) } } } extension AttributedLabel { private final class LabelView: UILabel { var textRectOffset: UIOffset = .zero { didSet { if oldValue != textRectOffset { setNeedsDisplay() } } } override func drawText(in rect: CGRect) { super.drawText(in: rect.offsetBy(dx: textRectOffset.horizontal, dy: textRectOffset.vertical)) } } } extension UIOffset: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(horizontal) hasher.combine(vertical) } }
29.653333
105
0.62545
18ffd78da6741c47f9b8d42827884c84f9a6734d
1,061
// // SubscriptionsSortingHeaderView.swift // Rocket.Chat // // Created by Samar Sunkaria on 6/20/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit class SubscriptionsSortingHeaderView: UIView { override var theme: Theme? { guard let theme = super.theme else { return nil } return Theme( backgroundColor: theme == .light ? theme.backgroundColor : theme.focusedBackground, focusedBackground: theme.focusedBackground, auxiliaryBackground: theme.auxiliaryBackground, bannerBackground: theme.bannerBackground, titleText: theme.titleText, bodyText: theme.bodyText, controlText: theme.controlText, auxiliaryText: theme.auxiliaryText, tintColor: theme.tintColor, auxiliaryTintColor: theme.auxiliaryTintColor, hyperlink: theme.hyperlink, mutedAccent: theme.mutedAccent, strongAccent: theme.strongAccent, appearence: theme.appearence ) } }
33.15625
95
0.65033
e8cd02b1905d40a33ce53db81c63203903d8aaf8
832
// // SourceCodeTheme.swift // SourceEditor // // Created by Louis D'hauwe on 24/07/2018. // Copyright © 2018 Silver Fox. All rights reserved. // import Foundation public protocol SourceCodeTheme: SyntaxColorTheme { func color(for syntaxColorType: SourceCodeTokenType) -> Color } extension SourceCodeTheme { public func globalAttributes() -> [NSAttributedString.Key: Any] { var attributes = [NSAttributedString.Key: Any]() attributes[.font] = font attributes[.foregroundColor] = color(for: .plain) return attributes } public func attributes(for token: Token) -> [NSAttributedString.Key: Any] { var attributes = [NSAttributedString.Key: Any]() if let token = token as? SimpleSourceCodeToken { attributes[.foregroundColor] = color(for: token.type) } return attributes } }
20.8
76
0.704327
d67b084799c0c92a6957a18a6632ae65fc265841
1,228
// // WeatherAppTests.swift // WeatherAppTests // // Created by Tatu Ketomaa on 24.1.2022. // import XCTest @testable import WeatherApp class WeatherAppTests: 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. } } }
33.189189
130
0.685668
29e9bbdb5cae4d4e65d13cf140e20b79a9698a3f
980
// // weatherappTests.swift // weatherappTests // // Created by MacBook Pro on 12/13/17. // Copyright © 2017 Islam & Co. All rights reserved. // import XCTest @testable import weatherapp class weatherappTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.486486
111
0.633673
c1f7270aa2463a9f5813053ce22882986f0439b9
1,227
/* This file was autogenerated from 02a_why_sqrt5.ipynb If you edit it, be sure that: 1. there is no diff between this file and the corresponding notebook prior to editing 2. you don't touch the comments looking like // cell ## as it would break the way back to the notebook Run *** when you are done to update the notebooks with your change. */ //cell1 import Foundation import TensorFlow import Path //cell17 func leakyRelu<T: TensorFlowFloatingPoint>( _ x: Tensor<T>, negativeSlope: Double = 0.0 ) -> Tensor<T> { return max(0, x) + T(negativeSlope) * min(0, x) } //cell28 extension Tensor where Scalar: TensorFlowFloatingPoint { init(kaimingUniform shape: TensorShape, negativeSlope: Double = 1.0) { // Assumes Leaky ReLU nonlinearity let gain = Scalar.init(TensorFlow.sqrt(2.0 / (1.0 + TensorFlow.pow(negativeSlope, 2)))) let spatialDimCount = shape.count - 2 let receptiveField = shape[0..<spatialDimCount].contiguousSize let fanIn = shape[shape.count - 2] * receptiveField let bound = TensorFlow.sqrt(Scalar(3.0)) * gain / TensorFlow.sqrt(Scalar(fanIn)) self = bound * (2 * Tensor(randomUniform: shape) - 1) } }
34.083333
104
0.679707
67c0d0bd32058903651d34281f56763c97bb36f2
448
// // Created by Kefei Qian on 2022/2/10. // import GNI18N public func getRandomLangExceptCurrentLang() -> GNI18NLang { var randomLang = GNI18N.shared.currentLang let langList = [ GNI18NLang(langName: "zh-Hans"), GNI18NLang(langName: "en"), GNI18NLang(langName: "ja"), ] while randomLang == GNI18N.shared.currentLang { let randomInt = Int.random(in: 0..<3) randomLang = langList[randomInt] } return randomLang }
20.363636
60
0.683036
9ce2a3682c7df18445f86e924ae67b26867cc0c0
787
// // MKRefresh.swift // Refresh // // Created by Mekor on 2016/11/27. // Copyright © 2016年 Mekor. All rights reserved. // import UIKit fileprivate var refreshView: MKRefreshControl? fileprivate var headerBlock: (()->Void)? extension UIScrollView { /// 添加下拉刷新 /// /// - Parameter complete: 完成回调 // func addRedreshHeader(complete: @escaping () -> Void) { func addRefreshHeader(target: Any?, action: Selector) { refreshView = MKRefreshControl() guard let refreshView = refreshView else { return } self.addSubview(refreshView) refreshView.addTarget(target, action: action, for: .valueChanged) } func endRefreshing() { refreshView?.endRefreshing() } }
19.675
73
0.60864
21c7d3268f0d0c1ec499b0c07b7257a4702390fc
278
import Foundation open class CMGyroData: CMLogItem { public let rotationRate: CMRotationRate public init(timestamp: TimeInterval, rotationRate: CMRotationRate) { self.rotationRate = rotationRate super.init(timestamp: timestamp) } }
23.166667
47
0.68705
29a1446e34f8288533f656415a723eb0d10994e6
2,711
// Copyright (c) 2020, OpenEmu Team // // 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 OpenEmu Team 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 OpenEmu Team ''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 OpenEmu Team 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 Cocoa final class HomebrewBlankSlateView: BlankSlateView { override func setupViewForRepresentedObject() { addLeftHeadline(NSLocalizedString("Homebrew Games", comment: "")) if let representedObject = representedObject as? String { setupBox(text: representedObject, imageView: BlankSlateSpinnerView()) addInformationalText(NSLocalizedString("Check out some excellent homebrew games.", comment: "")) } else if let error = representedObject as? Error { let warningImageView = NSImageView() warningImageView.image = NSImage(named: "blank_slate_warning") warningImageView.imageScaling = .scaleNone warningImageView.imageAlignment = .alignTop warningImageView.unregisterDraggedTypes() setupBox(text: NSLocalizedString("No Internet Connection", comment: "Homebrew Blank Slate View Error Info"), imageView: warningImageView) addInformationalText(error.localizedDescription) } else { DLog("Unknown Represented Object!") } } }
48.410714
149
0.700848
f88ce0f845e0840caf946087b87c5e61882ff0d4
5,395
import Foundation import Cncurses public class Keyboard { @discardableResult public static func readKey() -> Key { let code = getch() return Key(code: code) } } public struct Key { public static let yes: Int32 = 0o400 public static let min: Int32 = 0o401 public static let `break`: Int32 = 0o401 public static let softReset: Int32 = 0o530 public static let reset: Int32 = 0o531 public static let down: Int32 = 0o402 public static let up: Int32 = 0o403 public static let left: Int32 = 0o404 public static let right: Int32 = 0o405 public static let home: Int32 = 0o406 public static let backspace: Int32 = 0o407 public static let f0: Int32 = 0o410 public static let f1: Int32 = Key.f0 + 1 public static let f2: Int32 = Key.f0 + 2 public static let f3: Int32 = Key.f0 + 3 public static let f4: Int32 = Key.f0 + 4 public static let f5: Int32 = Key.f0 + 5 public static let f6: Int32 = Key.f0 + 6 public static let f7: Int32 = Key.f0 + 7 public static let f8: Int32 = Key.f0 + 8 public static let f9: Int32 = Key.f0 + 9 public static let f10: Int32 = Key.f0 + 10 public static let f11: Int32 = Key.f0 + 11 public static let f12: Int32 = Key.f0 + 12 public static let deleteLine: Int32 = 0o510 public static let insertLine: Int32 = 0o511 public static let deleteCharacter: Int32 = 0o512 public static let insertCharacter: Int32 = 0o513 public static let eic: Int32 = 0o514 public static let clear: Int32 = 0o515 public static let eos: Int32 = 0o516 public static let eol: Int32 = 0o517 public static let scrollForward: Int32 = 0o520 public static let scrollBackward: Int32 = 0o521 public static let nextPage: Int32 = 0o522 public static let previousPage: Int32 = 0o523 public static let setTab: Int32 = 0o524 public static let clearTab: Int32 = 0o525 public static let clearAllTabs: Int32 = 0o526 public static let enter: Int32 = 0o527 public static let print: Int32 = 0o532 public static let homeDown: Int32 = 0o533 public static let upperLeft: Int32 = 0o534 public static let upperRight: Int32 = 0o535 public static let center: Int32 = 0o536 public static let lowerLeft: Int32 = 0o537 public static let lowerRight: Int32 = 0o540 public static let backTab: Int32 = 0o541 public static let begin: Int32 = 0o542 public static let cancel: Int32 = 0o543 public static let close: Int32 = 0o544 public static let command: Int32 = 0o545 public static let copy: Int32 = 0o546 public static let create: Int32 = 0o547 public static let end: Int32 = 0o550 public static let exit: Int32 = 0o551 public static let find: Int32 = 0o552 public static let help: Int32 = 0o553 public static let mark: Int32 = 0o554 public static let message: Int32 = 0o555 public static let move: Int32 = 0o556 public static let next: Int32 = 0o557 public static let open: Int32 = 0o560 public static let options: Int32 = 0o561 public static let previous: Int32 = 0o562 public static let redo: Int32 = 0o563 public static let reference: Int32 = 0o564 public static let refresh: Int32 = 0o565 public static let replace: Int32 = 0o566 public static let restart: Int32 = 0o567 public static let resume: Int32 = 0o570 public static let save: Int32 = 0o571 public static let shiftedBegin: Int32 = 0o572 public static let shiftedCancel: Int32 = 0o573 public static let shiftedCommand: Int32 = 0o574 public static let shiftedCopy: Int32 = 0o575 public static let shiftedCreate: Int32 = 0o576 public static let shiftedDeleteCharacter: Int32 = 0o577 public static let shiftedDeleteLine: Int32 = 0o600 public static let select: Int32 = 0o601 public static let shiftedEnd: Int32 = 0o602 public static let shiftedEol: Int32 = 0o603 public static let shiftedExit: Int32 = 0o604 public static let shiftedFind: Int32 = 0o605 public static let shiftedHelp: Int32 = 0o606 public static let shiftedHome: Int32 = 0o607 public static let shiftedInsertCharacter: Int32 = 0o610 public static let shiftedLeft: Int32 = 0o611 public static let shiftedMessage: Int32 = 0o612 public static let shiftedMove: Int32 = 0o613 public static let shiftedNext: Int32 = 0o614 public static let shiftedOptions: Int32 = 0o615 public static let shiftedPrevious: Int32 = 0o616 public static let shiftedPrint: Int32 = 0o617 public static let shiftedRedo: Int32 = 0o620 public static let shiftedReplace: Int32 = 0o621 public static let shiftedRight: Int32 = 0o622 public static let shiftedResume: Int32 = 0o623 public static let shiftedSave: Int32 = 0o624 public static let shiftedSuspend: Int32 = 0o625 public static let shiftedUndo: Int32 = 0o626 public static let suspend: Int32 = 0o627 public static let undo: Int32 = 0o630 public static let mouse: Int32 = 0o631 public static let terminalResize: Int32 = 0o632 public static let event: Int32 = 0o633 public static let max: Int32 = 0777 public let code: Int32 public func character() -> Character? { guard let scalar = UnicodeScalar(Int(code)) else { return .none } return Character(scalar) } }
40.871212
59
0.697683
acff8ebea7dc597e11e9da0bc4b7a9bb30fa533e
231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { let end = [ { { case let { protocol a { class case ,
17.769231
87
0.722944
6a77875cc0b80a2164403fd0a2232abd201ec157
415
// // RetryProfile.swift // APIKit_Example // // Created by David on 2019/11/23. // Copyright © 2019 CocoaPods. All rights reserved. // import Mapper public struct RetryProfile { let info: String let username: String } extension RetryProfile: Mappable { public init(map: Mapper) throws { self.info = try map.from("data.info") self.username = try map.from("data.username") } }
18.863636
53
0.660241
89be548b5fb895a701ac9ae80c16915f6412c7cf
10,570
// // HomeScreenCell.swift // ravenwallet // // Created by Adrian Corscadden on 2017-11-28. // Copyright © 2018 Ravenwallet Team. All rights reserved. // import UIKit import QuartzCore class Background : UIView, GradientDrawable { var currency: CurrencyDef? override func layoutSubviews() { super.layoutSubviews() let maskLayer = CAShapeLayer() let corners: UIRectCorner = .allCorners maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: 4.0, height: 4.0)).cgPath layer.mask = maskLayer } override func draw(_ rect: CGRect) { guard let currency = currency else { return } drawGradient(start: currency.colors.0, end: currency.colors.1, rect) } } class HomeScreenCell : UITableViewCell, Subscriber { static let cellIdentifier = "CurrencyCell" private let currencyName = UILabel(font: .customBold(size: 18.0), color: .white) private let price = UILabel(font: .customBold(size: 14.0), color: .transparentWhiteText) private let fiatBalance = UILabel(font: .customBold(size: 18.0), color: .white) private let tokenBalance = UILabel(font: .customBold(size: 14.0), color: .transparentWhiteText) private let chartTitle = UILabel(font: .customMedium(size: 13.0), color: .white) private let syncIndicator = SyncingIndicator(style: .home) private let container = Background() private let aaChartView: AAChartView = AAChartView() private var aaChartModel: AAChartModel = AAChartModel() private let separator = UIView(color: .transparentWhiteText) private let arrow = UIImageView(image: #imageLiteral(resourceName: "RightArrow").withRenderingMode(.alwaysTemplate)) private var isSyncIndicatorVisible: Bool = false { didSet { UIView.crossfade(tokenBalance, syncIndicator, toRight: isSyncIndicatorVisible, duration: 0.3) fiatBalance.textColor = isSyncIndicatorVisible ? .disabledWhiteText : .white } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } func set(viewModel: WalletListViewModel) { updateDataCell(viewModel: viewModel) addSubscriptions() } func refreshAnimations() { //syncIndicator.pulse() } private func setupViews() { addSubviews() addConstraints() setupStyle() } private func updateDataCell(viewModel: WalletListViewModel) { container.currency = viewModel.currency currencyName.text = viewModel.currency.name price.text = viewModel.exchangeRate fiatBalance.text = viewModel.fiatBalance tokenBalance.text = viewModel.tokenBalance container.setNeedsDisplay() chartModel() } private func chartModel() { let chartModel = ChartModel(parentVC: self.parentViewController()!, callback: { elements in let prices = elements.map { ($0 as! NSDictionary).object(forKey: "C") } let dates = elements.map { (($0 as! NSDictionary).object(forKey: "T") as! String).replacingOccurrences(of: "T00:00:00", with: "") } self.aaChartModel = AAChartModel() .chartType(.area)//Can be any of the chart types listed under `AAChartType`. .animationType(.easeOutSine) .title("")//The chart title .subtitle("")//The chart subtitle .xAxisVisible(false) .yAxisVisible(false) .legendEnabled(false) .dataLabelsEnabled(false) .backgroundColor("transparent") .colorsTheme(["#ffffff"]) .markerRadius(0) .categories(dates) .marginLeft(-1) .marginRight(-1) .marginBottom(-1) .yAxisMin((prices as! [NSNumber]).map{$0.floatValue}.min() ?? 0) .yAxisMax((prices as! [NSNumber]).map{$0.floatValue}.max() ?? 0) .series([ AASeriesElement() .name("RVN") .data(prices) .color("white") .fillColor(AAGradientColor.linearGradient(direction: .toBottom, startColor: AAColor.rgbaColor(255,255,255,0.5), endColor: AAColor.rgbaColor(255,255,255,0))) .lineWidth(1)]) DispatchQueue.main.async { self.aaChartView.aa_drawChartWithChartModel(self.aaChartModel) } }) chartModel.getChartData() } private func addSubscriptions(){ Store.subscribe(self, selector: { $0[self.container.currency!].syncState != $1[self.container.currency!].syncState }, callback: { state in switch state[self.container.currency!].syncState { case .connecting: self.isSyncIndicatorVisible = true case .syncing: self.isSyncIndicatorVisible = true case .success: self.isSyncIndicatorVisible = false } }) Store.subscribe(self, selector: { return $0[self.container.currency!].lastBlockTimestamp != $1[self.container.currency!].lastBlockTimestamp }, callback: { state in self.syncIndicator.progress = CGFloat(state[self.container.currency!].syncProgress) }) Store.subscribe(self, selector: { $0[self.container.currency!].currentRate != $1[self.container.currency!].currentRate}, callback: { self.price.textColor = .transparentWhiteText let rate = $0[self.container.currency!].currentRate if(rate?.rate == 0){ self.price.textColor = .sentRed } }) } private func addSubviews() { contentView.addSubview(container) container.addSubview(currencyName) container.addSubview(price) container.addSubview(fiatBalance) container.addSubview(tokenBalance) container.addSubview(syncIndicator) container.addSubview(aaChartView) container.addSubview(separator) container.addSubview(chartTitle) container.addSubview(arrow) } private func addConstraints() { container.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[1]*0.5, left: C.padding[2], bottom: -C.padding[1], right: -C.padding[2])) currencyName.constrain([ currencyName.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: C.padding[2]), currencyName.topAnchor.constraint(equalTo: container.topAnchor, constant: C.padding[2]) ]) price.constrain([ price.leadingAnchor.constraint(equalTo: currencyName.leadingAnchor), price.topAnchor.constraint(equalTo: currencyName.bottomAnchor) ]) fiatBalance.constrain([ fiatBalance.trailingAnchor.constraint(equalTo: arrow.leadingAnchor, constant: -C.padding[1]), fiatBalance.topAnchor.constraint(equalTo: container.topAnchor, constant: C.padding[2]), fiatBalance.leadingAnchor.constraint(greaterThanOrEqualTo: currencyName.trailingAnchor, constant: C.padding[1]) ]) tokenBalance.constrain([ tokenBalance.trailingAnchor.constraint(equalTo: fiatBalance.trailingAnchor), tokenBalance.topAnchor.constraint(equalTo: fiatBalance.bottomAnchor), tokenBalance.leadingAnchor.constraint(greaterThanOrEqualTo: price.trailingAnchor, constant: C.padding[1]) ]) syncIndicator.constrain([ syncIndicator.trailingAnchor.constraint(equalTo: fiatBalance.trailingAnchor), syncIndicator.topAnchor.constraint(equalTo: fiatBalance.bottomAnchor), syncIndicator.leadingAnchor.constraint(greaterThanOrEqualTo: price.trailingAnchor, constant: C.padding[1]) ]) arrow.constrain([ arrow.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -C.padding[1]), arrow.widthAnchor.constraint(equalToConstant: 7.0), arrow.heightAnchor.constraint(equalToConstant: 12.0), arrow.centerYAnchor.constraint(equalTo: fiatBalance.bottomAnchor) ]) chartTitle.constrain([ chartTitle.topAnchor.constraint(equalTo: tokenBalance.bottomAnchor, constant: C.padding[2]), chartTitle.trailingAnchor.constraint(equalTo: arrow.trailingAnchor) ]) separator.constrain([ separator.leadingAnchor.constraint(equalTo: container.leadingAnchor), separator.trailingAnchor.constraint(equalTo: chartTitle.leadingAnchor, constant: -C.padding[2]), separator.centerYAnchor.constraint(equalTo: chartTitle.centerYAnchor), separator.heightAnchor.constraint(equalToConstant: 0.0) ]) aaChartView.constrain([ aaChartView.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: C.padding[2]), aaChartView.topAnchor.constraint(equalTo: chartTitle.bottomAnchor, constant: C.padding[0]), aaChartView.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: -C.padding[2]), aaChartView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: C.padding[0]) ]) } private func setupStyle() { selectionStyle = .none backgroundColor = .clear chartTitle.text = S.Chart.title aaChartView.isClearBackgroundColor = true aaChartView.scrollEnabled = false syncIndicator.isHidden = true arrow.tintColor = .white } override func prepareForReuse() { Store.unsubscribe(self) } deinit { Store.unsubscribe(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
44.041667
180
0.611826
2023404d6f72e05746830e0cb4d1440542fdb18d
2,643
import Foundation import UIKit public enum DeviceModel: Equatable { case iPhone1G case iPhone3G case iPhone3GS case iPhone4 case iPhone4S case iPhone5 case iPhone5C case iPhone5S case iPhone6 case iPhone6Plus case iPhone6S case iPhone6SPlus case iPhoneSE case iPhone7 case iPhone7Plus case iPhone8 case iPhone8Plus case iPhoneX case iPhoneXR case iPhoneXS case iPhoneXSMax case iPhone11 case iPhone11Pro case iPhone11ProMax case iPhoneSE2G case iPhone12Mini case iPhone12 case iPhone12Pro case iPhone12ProMax case iPodTouch1G case iPodTouch2G case iPodTouch3G case iPodTouch4G case iPodTouch5G case iPodTouch6G case iPodTouch7G case iPad1G case iPad2G case iPad3G case iPad4G case iPadMini1 case iPadMini2 case iPadMini3 case iPadMini4 case iPadMini5 case iPadAir1G case iPadAir2G case iPadAir3G case iPadAir4G case iPadPro9d7inch1G case iPadPro10d5inch1G case iPadPro12d9inch1G case iPadPro12d9inch2G case iPadPro12d9inch3G case iPadPro12d9inch4G case iPadPro11inch case iPadPro11inch2G case iPad5G case iPad6G case iPad7G case iPad8G case appleTV4G case appleTV4K case iPadSimulator case iPhoneSimulator case appleTVSimulator case iPhoneUnknown(model: String) case iPadUnknown(model: String) case iPodUnknown(model: String) case unknown(model: String) internal init(_ identifier: DeviceIdentifier) { guard let model = identifier.model else { if identifier.rawValue == "i386" || identifier.rawValue == "x86_64" { #if os(iOS) let smallerScreen = UIScreen.main.bounds.size.width < 768 self = smallerScreen ? .iPhoneSimulator : .iPadSimulator #elseif os(tvOS) self = .appleTVSimulator #endif } else if identifier.rawValue.hasPrefix("iPhone") { self = .iPhoneUnknown(model: identifier.rawValue) } else if identifier.rawValue.hasPrefix("iPod") { self = .iPodUnknown(model: identifier.rawValue) } else if identifier.rawValue.hasPrefix("iPad") { self = .iPadUnknown(model: identifier.rawValue) } else { self = .unknown(model: identifier.rawValue) } return } self = model } } public func == (lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.name == rhs.name }
24.027273
81
0.637533
714297041e1c272d7acb3f7b5e0bb1b10e652895
858
// // WindowController.swift // Reader // // Created by Niket Shah on 09/04/2015. // Copyright (c) 2015 Niket Shah. All rights reserved. // import Cocoa class WindowController: NSWindowController { //MARK: Properties @IBOutlet var titleLabelCell: NSTextFieldCell! var title: String = "Hello" { didSet { titleLabelCell.title = title } } // MARK: - Overrides override var document: AnyObject? { didSet { let contentViewController = window!.contentViewController as! ContentViewController contentViewController.document = document as? Document } } override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } }
20.926829
134
0.655012
8fd5f82161517cd0323e8ccc400908ac7cd70f86
835
// // LedgerView.swift // SwiftBeanCountApp // // Created by Steffen Kötte on 2020-06-01. // Copyright © 2020 Steffen Kötte. All rights reserved. // import SwiftBeanCountModel import SwiftUI struct LedgerView: View { private let ledger: Ledger var body: some View { TabView { AccountsView(ledger) .tabItem { Text("Accounts") } TransactionsView(ledger) .tabItem { Text("Transactions") } ErrorView(ledger) .tabItem { Text("Errors") } } .padding() } init(_ ledger: Ledger) { self.ledger = ledger } } struct LedgerView_Previews: PreviewProvider { static var previews: some View { LedgerView(Ledger()) } }
18.977273
56
0.529341
01392adb1a45048f830a5c5e49d181d56d87c2d3
1,657
// // Created by RevenueCat on 3/2/20. // Copyright (c) 2020 Purchases. All rights reserved. // class MockUserManager: RCIdentityManager { var configurationCalled = false var identifyError: Error? var aliasError: Error? var aliasCalled = false var identifyCalled = false var resetCalled = false var mockIsAnonymous = false var mockAppUserID: String init(mockAppUserID: String) { self.mockAppUserID = mockAppUserID super.init() } override var currentAppUserID: String { if (mockIsAnonymous) { return "$RCAnonymousID:ff68f26e432648369a713849a9f93b58" } else { return mockAppUserID } } override func configure(withAppUserID appUserID: String?) { configurationCalled = true } override func createAlias(_ alias: String, withCompletionBlock completion: @escaping (Error?) -> ()) { aliasCalled = true if (aliasError != nil) { completion(aliasError) } else { mockAppUserID = alias completion(nil) } } override func identifyAppUserID(_ appUserID: String, withCompletionBlock completion: @escaping (Error?) -> ()) { identifyCalled = true if (identifyError != nil) { completion(identifyError) } else { mockAppUserID = appUserID completion(nil) } } override func resetAppUserID() { resetCalled = true mockAppUserID = "$RCAnonymousID:ff68f26e432648369a713849a9f93b58" } override var currentUserIsAnonymous: Bool { return mockIsAnonymous } }
26.301587
116
0.624623
e48d48c68a2f89d57839d780878a8bc4ee1f1eca
2,382
// // SocketAckManager.swift // Socket.IO-Client-Swift // // Created by Erik Little on 4/3/15. // // 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 private struct SocketAck: Hashable, Equatable { let ack: Int var callback: AckCallback! var hashValue: Int { return ack.hashValue } init(ack: Int) { self.ack = ack } init(ack: Int, callback: AckCallback) { self.ack = ack self.callback = callback } } private func <(lhs: SocketAck, rhs: SocketAck) -> Bool { return lhs.ack < rhs.ack } private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool { return lhs.ack == rhs.ack } struct SocketAckManager { private var acks = Set<SocketAck>(minimumCapacity: 1) mutating func addAck(ack: Int, callback: AckCallback) { acks.insert(SocketAck(ack: ack, callback: callback)) } mutating func executeAck(ack: Int, items: [AnyObject]) { let callback = acks.remove(SocketAck(ack: ack)) dispatch_async(dispatch_get_main_queue()) { callback?.callback(items) } } mutating func timeoutAck(ack: Int) { let callback = acks.remove(SocketAck(ack: ack)) dispatch_async(dispatch_get_main_queue()) { callback?.callback(["NO ACK"]) } } }
31.76
81
0.675483
38258a368b19719bed1e69172a94e682bebf468a
3,109
// // MenuHeaderView.swift // Eatery // // Created by Eric Appel on 11/18/15. // Copyright © 2015 CUAppDev. All rights reserved. // import UIKit import SnapKit import Kingfisher class MenuHeaderView: UIView { var eatery: CampusEatery? var displayedDate: Date? let container = UIView() let titleLabel = UILabel() let favoriteButton = UIButton() let paymentView = PaymentMethodsView() override init(frame: CGRect) { super.init(frame: frame) addSubview(container) container.snp.makeConstraints { make in make.edges.equalToSuperview() } titleLabel.isOpaque = false titleLabel.font = .boldSystemFont(ofSize: 34) titleLabel.textColor = .white titleLabel.adjustsFontSizeToFitWidth = true titleLabel.minimumScaleFactor = 0.25 container.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.leading.equalToSuperview().inset(16) make.bottom.equalToSuperview().inset(15) } favoriteButton.setImage(UIImage(named: "whiteStar"), for: .normal) favoriteButton.addTarget(self, action: #selector(favoriteButtonPressed(_:)), for: .touchUpInside) container.addSubview(favoriteButton) favoriteButton.snp.makeConstraints { make in make.centerY.equalTo(titleLabel.snp.centerY) make.leading.equalTo(titleLabel.snp.trailing).offset(10) make.width.height.equalTo(27) } container.addSubview(paymentView) paymentView.snp.makeConstraints { make in make.leading.greaterThanOrEqualTo(favoriteButton.snp.trailing) make.trailing.equalToSuperview().inset(16) make.centerY.equalTo(titleLabel.snp.centerY) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) will not be implemented") } func set(eatery: CampusEatery, date: Date) { self.eatery = eatery self.displayedDate = date updateFavoriteButtonImage() paymentView.paymentMethods = eatery.paymentMethods titleLabel.text = eatery.nickname favoriteButton.imageEdgeInsets = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0) favoriteButton.tintColor = .favoriteYellow let eateryStatus = eatery.currentStatus() switch eateryStatus { case .open, .closingSoon: titleLabel.textColor = .white case .closed, .openingSoon: titleLabel.textColor = UIColor.lightGray } } func updateFavoriteButtonImage() { guard let eatery = eatery else { return } favoriteButton.setImage( eatery.isFavorite ? UIImage(named: "goldStar") : UIImage(named: "whiteStar"), for: .normal ) } @objc private func favoriteButtonPressed(_ sender: AnyObject) { guard var eatery = eatery else { return } eatery.isFavorite.toggle() updateFavoriteButtonImage() self.eatery = eatery } }
28.009009
105
0.637826
62fc18f6e6f706c6620afe7c2e1684156aecf268
1,392
// // WeexNavigatorImp.swift // WeexCache_Example // // Created by 陈广川 on 2018/1/18. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit import WeexSDK class WeexNavigatorImp: NSObject, WXNavigationProtocol { func navigationController(ofContainer container: UIViewController!) -> Any! { return container.navigationController } func setNavigationBarHidden(_ hidden: Bool, animated: Bool, withContainer container: UIViewController!) { container.navigationController?.setNavigationBarHidden(hidden, animated: animated) } func setNavigationBackgroundColor(_ backgroundColor: UIColor!, withContainer container: UIViewController!) { } func setNavigationItemWithParam(_ param: [AnyHashable : Any]!, position: WXNavigationItemPosition, completion block: WXNavigationResultBlock!, withContainer container: UIViewController!) { } func clearNavigationItem(withParam param: [AnyHashable : Any]!, position: WXNavigationItemPosition, completion block: WXNavigationResultBlock!, withContainer container: UIViewController!) { } func pushViewController(withParam param: [AnyHashable : Any]!, completion block: WXNavigationResultBlock!, withContainer container: UIViewController!) { } func popViewController(withParam param: [AnyHashable : Any]!, completion block: WXNavigationResultBlock!, withContainer container: UIViewController!) { } }
32.372093
190
0.783764
0e6b036b3eead1d50c533d04c168673a0ad96fda
1,650
/** * Copyright (c) 2021 Dustin Collins (Strega's Gate) * All Rights Reserved. * Licensed under Apache License v2.0 * * Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate */ import WinSDK /// Defines constants that specify a shading rate tier (for variable-rate shading, or VRS). For more info, see Variable-rate shading (VRS). public enum VariableShadingRateTier { /// Specifies that variable-rate shading is not supported. case notSupported /// Specifies that variable-rate shading tier 1 is supported. case tier1 /// Specifies that variable-rate shading tier 2 is supported. case tier2 internal var rawValue: WinSDK.D3D12_VARIABLE_SHADING_RATE_TIER { switch self { case .notSupported: return WinSDK.D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED case .tier1: return WinSDK.D3D12_VARIABLE_SHADING_RATE_TIER_1 case .tier2: return WinSDK.D3D12_VARIABLE_SHADING_RATE_TIER_2 } } } //MARK: - Original Style API #if !Direct3D12ExcludeOriginalStyleAPI @available(*, deprecated, renamed: "VariableShadingRateTier") public typealias D3D12_VARIABLE_SHADING_RATE_TIER = VariableShadingRateTier public extension VariableShadingRateTier { @available(*, deprecated, renamed: "notSupported") static let D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED = Self.notSupported @available(*, deprecated, renamed: "tier1") static let D3D12_VARIABLE_SHADING_RATE_TIER_1 = Self.tier1 @available(*, deprecated, renamed: "tier2") static let D3D12_VARIABLE_SHADING_RATE_TIER_2 = Self.tier2 } #endif
32.352941
139
0.736364
23b99cf87934368fb794b4c4e08deecc09150f60
917
// // StaticLength.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // struct StaticLength : WriteableRuntimeLength { fileprivate let formId : FormIdentifier fileprivate let offset : Int init(formId: FormIdentifier, offset: Int) { self.formId = formId self.offset = offset } func getLengthFor<R:Runtime>(_ runtime: R) -> Double? { guard let l = runtime.read(formId, offset: offset) else { return nil } return Double(bitPattern: l) } func setLengthFor<R:Runtime>(_ runtime: R, length: Double) { runtime.write(formId, offset: offset, value: length.bitPattern) } } extension StaticLength : Equatable { } func ==(lhs: StaticLength, rhs: StaticLength) -> Bool { return lhs.formId == rhs.formId && lhs.offset == rhs.offset }
23.512821
71
0.629226
e990f0eb07078907cbb2e22128ab5f6e30c6277e
1,570
// // MD2OnConnectionLostHandler.swift // md2-ios-library // // Created by Christoph Rieger on 05.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /// Event handler to react to connection losses. class MD2OnConnectionLostHandler: MD2GlobalEventHandler { /// The singleton instance. static let instance: MD2OnConnectionLostHandler = MD2OnConnectionLostHandler() /// The list of registered actions. var actions: Dictionary<String, MD2Action> = [:] /// Singleton initializer. private init() { // Nothing to initialize } /** Register an action to execute when the connection is lost. :param: action The action to execute in case of an event. */ func registerAction(action: MD2Action) { actions[action.actionSignature] = action } /** Unregister an action. :param: action The action to remove. */ func unregisterAction(action: MD2Action) { for (key, value) in actions { if key == action.actionSignature { actions[key] = nil break } } } /** Method that is called to fire an event. *Notice* Visible to Objective-C runtime to receive events. */ @objc func fire() { //println("Event fired to OnClickHandler: " + String(sender.tag) + "=" + WidgetMapping.fromRawValue(sender.tag).description) for (_, action) in actions { action.execute() } } }
26.166667
132
0.592357
eb567a9703ec47be70ee620f689c9c6fa85bbbcd
1,334
// // ManualLocalizeViewController.swift // Pods // // Created by Will Powell on 28/07/2017. // // #if os(iOS) import UIKit class ManualLocalizeViewController: UIViewController { @IBOutlet weak var keyLabel:UILabel! @IBOutlet weak var languageLabel:UILabel! @IBOutlet weak var textField:UITextField! public var localizationKey:String? { didSet{ DispatchQueue.main.async { self.keyLabel.text = self.localizationKey } } } override func viewDidLoad() { super.viewDidLoad() self.languageLabel.text = Localization.languageCode if let localizationKeyStr = self.localizationKey { let localizationString = Localization.get(localizationKeyStr, alternate: "") self.textField.text = localizationString textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) } } func textFieldDidChange(_ textField: UITextField) { if let localizationKeyStr = self.localizationKey { Localization.set(localizationKeyStr, value: textField.text!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } #endif
26.68
102
0.648426
26427ceb651a9c47eaf050eb4a3a5957287a2dd1
2,158
// // AppDelegate.swift // CustomSearchBar // // Created by chenchangqing on 12/23/2015. // Copyright (c) 2015 chenchangqing. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.914894
285
0.755792
9bb2d0aaa62b18bd61947d746f3759a54cd0b178
3,242
import Foundation import CoreBluetooth /// It should be deleted when `RestoredState` will be deleted protocol CentralManagerRestoredStateType { var restoredStateData: [String: Any] { get } var centralManager: CentralManager { get } var peripherals: [Peripheral] { get } var scanOptions: [String: AnyObject]? { get } var services: [Service] { get } } /// Convenience class which helps reading state of restored CentralManager. public struct CentralManagerRestoredState: CentralManagerRestoredStateType { /// Restored state dictionary. public let restoredStateData: [String: Any] public unowned let centralManager: CentralManager /// Creates restored state information based on CoreBluetooth's dictionary /// - parameter restoredStateDictionary: Core Bluetooth's restored state data /// - parameter centralManager: `CentralManager` instance of which state has been restored. init(restoredStateDictionary: [String: Any], centralManager: CentralManager) { restoredStateData = restoredStateDictionary self.centralManager = centralManager } /// Array of `Peripheral` objects which have been restored. /// These are peripherals that were connected to the central manager (or had a connection pending) /// at the time the app was terminated by the system. public var peripherals: [Peripheral] { let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } #if swift(>=4.1) let cbPeripherals = arrayOfAnyObjects.compactMap { $0 as? CBPeripheral } #else let cbPeripherals = arrayOfAnyObjects.flatMap { $0 as? CBPeripheral } #endif return cbPeripherals.map { centralManager.retrievePeripheral(for: $0) } } /// Dictionary that contains all of the peripheral scan options that were being used /// by the central manager at the time the app was terminated by the system. public var scanOptions: [String: AnyObject]? { return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String: AnyObject] } /// Array of `Service` objects which have been restored. /// These are all the services the central manager was scanning for at the time the app /// was terminated by the system. public var services: [Service] { let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } #if swift(>=4.1) let cbServices = arrayOfAnyObjects.compactMap { $0 as? CBService } #else let cbServices = arrayOfAnyObjects.flatMap { $0 as? CBService } #endif return cbServices.compactMap { cbService -> Service? in do { return Service( peripheral: centralManager.retrievePeripheral(for: try cbService.unwrapPeripheral()), service: cbService ) } catch { RxBluetoothKitLog.e("Failed to restore service \(cbService.logDescription) with error \(error)") return nil } } } }
42.657895
112
0.685379
206a59220b80a0059e9e20ace8abee0e39238edf
1,180
import Foundation import UIKit extension UICollectionView { final class Factory { static func construct( delegate: UICollectionViewDelegate, uiCollectionViewLayout: UICollectionViewLayout ) -> UICollectionView { let collectionView = UICollectionView( frame: .zero, collectionViewLayout: uiCollectionViewLayout) collectionView.delegate = delegate return collectionView } } } extension UICollectionViewLayout { final class Factory { static func construct( ) -> UICollectionViewLayout { return UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in let configuration = UICollectionLayoutListConfiguration( appearance: .insetGrouped) let section = NSCollectionLayoutSection.list( using: configuration, layoutEnvironment: layoutEnvironment) return section } } } }
26.222222
91
0.552542
efd8910f87213c2cf61506cd4e7c7406f43eee0d
2,615
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 CreateAcronymTableViewController: UITableViewController { // MARK: - IBOutlets @IBOutlet weak var acronymShortTextField: UITextField! @IBOutlet weak var acronymLongTextField: UITextField! @IBOutlet weak var userLabel: UILabel! // MARK: - Properties var selectedUser: User? var acronym: Acronym? // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() acronymShortTextField.becomeFirstResponder() } // MARK: - Navigation @IBSegueAction func makeSelectUserViewController(_ coder: NSCoder) -> SelectUserTableViewController? { return nil } // MARK: - IBActions @IBAction func cancel(_ sender: UIBarButtonItem) { navigationController?.popViewController(animated: true) } @IBAction func save(_ sender: UIBarButtonItem) { navigationController?.popViewController(animated: true) } @IBAction func updateSelectedUser(_ segue: UIStoryboardSegue) { } }
40.230769
104
0.751434
56aae9fdaf6cb5d181d30d6ff38adc888a05abfe
6,471
// // Publisher.swift // BwTools // // Created by k2moons on 2018/07/28. // Copyright (c) 2018 k2moons. All rights reserved. // import Foundation // swiftlint:disable strict_fileprivate // MARK: - Unsubscribable /// A protocol with a method for canceling subscribe all at once private protocol Unsubscribable { func unsubscribe() func unsubscribe(_ idetifier: SubscribeBagIdentifier) } /// Because this is just an identifier, AnyObject can be public typealias Subscriber = AnyObject public typealias SubscribeBagIdentifier = Int // MARK: - SubscriptionBag /// Class for canceling subscribe when subscribed instance is destroyed public final class SubscriptionBag { private var unsubscribables = [Unsubscribable]() private static var globalIdentifier: SubscribeBagIdentifier = 0 private(set) var idetifier: SubscribeBagIdentifier public init() { idetifier = SubscriptionBag.globalIdentifier SubscriptionBag.globalIdentifier += 1 } fileprivate func set(_ subscriberInfo: Unsubscribable) -> SubscribeBagIdentifier { unsubscribables.append(subscriberInfo) return idetifier } deinit { // log.deinit(self) for unsubscribable in unsubscribables { unsubscribable.unsubscribe(idetifier) } } } // MARK: - Publisher // Publisher // // public final class Publisher<ContentsType> { // --------------------------------------------------------------- // subscribe()される時にSubscriberの情報を格納して、Publisherに保持される。 // またsubscribe()の戻り値となるので、SubscribeBagに渡すことで自動削除できるようになる public class Subscription: Unsubscribable { fileprivate var action: (_ result: ContentsType) -> Void fileprivate weak var subscriber: Subscriber? fileprivate var once: Bool = false fileprivate var main: Bool = true private var publisher: Publisher<ContentsType>? private(set) var identifier: SubscribeBagIdentifier = -1 public required init( _ subscriber: Subscriber, publisher: Publisher<ContentsType>, once: Bool, main: Bool, action: @escaping ((ContentsType) -> Void) ) { self.subscriber = subscriber self.once = once self.main = main self.action = action self.publisher = publisher } public func unsubscribed(by unsubscribeBag: SubscriptionBag) { identifier = unsubscribeBag.set(self) } // 指定されたSubscriberによってsubscribeされているものをunsubscribeする fileprivate func unsubscribe() { if let observer = subscriber { self.publisher?.unsubscribe(by: observer) } } // 指定されたidentifierによってunsubscribeする fileprivate func unsubscribe(_ identifier: SubscribeBagIdentifier) { self.publisher?.unsubscribe(by: identifier) } // deinit { // log.deinit(self) // } } // --------------------------------------------------------------- private var subscriptions: [Subscription] = [] private var latestContents: ContentsType? public init(_ contents: ContentsType? = nil) { latestContents = contents } // --------------------------------------------------------------- /// subscribe /// /// - Parameters: /// - subscriber: BwObserver that observe this Publisher. This is just identifier of subscriber. /// - once: subscribe once /// - latest: immediately return contens, if it already exists. /// - main: if true, action executed in main thread /// - action: closure that is invoked when contents are published /// - Returns: Subscription? @discardableResult public func subscribe( _ subscriber: Subscriber, latest: Bool = false, main: Bool = true, action: @escaping ((_ contents: ContentsType) -> Void) ) -> Subscription { if latest, let latestContents = latestContents { if main { DispatchQueue.main.async { action(latestContents) } } else { DispatchQueue.global().async { action(latestContents) } } } let subscriberInfo = Subscription(subscriber, publisher: self, once: false, main: main, action: action) subscriptions.append(subscriberInfo) return subscriberInfo } // --------------------------------------------------------------- public func once( _ subscriber: Subscriber, latest: Bool = false, main: Bool = true, action: @escaping ((_ contents: ContentsType) -> Void) ) { if latest, let latestContents = latestContents { if main { DispatchQueue.main.async { action(latestContents) } } else { DispatchQueue.global().async { action(latestContents) } } return } let subscriberInfo = Subscription(subscriber, publisher: self, once: true, main: main, action: action) subscriptions.append(subscriberInfo) } // --------------------------------------------------------------- /// Execute action closures /// /// - Parameter contents: Contents to be published to subscribers(observers) public func publish(_ contents: ContentsType) { latestContents = contents for subscriberInfo in subscriptions { if subscriberInfo.main { DispatchQueue.main.async { subscriberInfo.action(contents) } } else { DispatchQueue.global().async { subscriberInfo.action(contents) } } } // 1度だけコンテンツ取得の場合は、ここで終了 subscriptions = subscriptions.filter { !$0.once } } // Subscriberを渡してsubscriptionを終了する // public func unsubscribe(by subscriber: Subscriber) { subscriptions = subscriptions.filter { !($0.subscriber === subscriber) } } // SubscribeBagから、Subscriptionを介して呼び出される。SubscribeBag毎に割り振られたidentifierでsubscriptionを終了する // fileprivate func unsubscribe(by identifier: SubscribeBagIdentifier) { subscriptions = subscriptions.filter { !($0.identifier == identifier) } } }
30.523585
111
0.579818
8f3f0b325931e951b2d4d7b1c12791f16379a7cf
3,450
// // Swutler // // Created by Steve Stomp on 20/05/2017. // Copyright © 2017 Code&Coding. All rights reserved. // import UIKit extension UITableView { public func showEmpty(image: UIImage, title: String, description: String, titleFont: UIFont = UIFont.systemFont(ofSize: 12), descriptionFont: UIFont = UIFont.systemFont(ofSize: 12), textColor: UIColor? = nil) { struct LayoutConstants { static let padding : CGFloat = 40 static let imageWidth : CGFloat = 136 static let spacing : CGFloat = 20 static let lineHeight : CGFloat = 1.5 static let maxWidth : CGFloat = 280 } var titleLabel: UILabel = { let view = UILabel() view.font = titleFont view.numberOfLines = 0 view.text = title view.textColor = textColor ?? UIColor.black view.textAlignment = .center return view }() var descriptionLabel: UILabel = { let view = UILabel() view.font = descriptionFont view.numberOfLines = 0 view.text = description view.textAlignment = .center view.textColor = textColor ?? UIColor.black view.set(lineHeight: LayoutConstants.lineHeight) return view }() let wrapper = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: frame.height)) let inner = UIView(frame: wrapper.frame) let icon: UIImageView = UIImageView(image: image) icon.contentMode = .scaleAspectFit icon.frame = CGRect(x: 0, y: 0, width: LayoutConstants.imageWidth, height: LayoutConstants.imageWidth) icon.center.x = bounds.width * 0.5 inner.addSubview(icon) inner.addSubview(titleLabel) inner.addSubview(descriptionLabel) let titleLabelSize = titleLabel .sizeThatFits(CGSize(width: LayoutConstants.maxWidth, height: 0)) let descriptionLabelSize = descriptionLabel.sizeThatFits(CGSize(width: LayoutConstants.maxWidth, height: 0)) let titleLabelFrame = CGRect( origin: CGPoint(x: (bounds.width - LayoutConstants.maxWidth) * 0.5, y: LayoutConstants.imageWidth + LayoutConstants.spacing), size: CGSize(width: LayoutConstants.maxWidth, height: titleLabelSize.height) ) let descriptionLabelFrame = CGRect( origin: CGPoint(x: (bounds.width - LayoutConstants.maxWidth) * 0.5, y: titleLabelSize.height + LayoutConstants.spacing + LayoutConstants.imageWidth + (LayoutConstants.spacing / 4)), size: CGSize(width: LayoutConstants.maxWidth, height: descriptionLabelSize.height) ) titleLabel .frame = titleLabelFrame descriptionLabel.frame = descriptionLabelFrame inner.center.y = bounds.height * 0.5 + LayoutConstants.padding wrapper.addSubview(inner) backgroundView = wrapper } public func removeEmptyMessage() { backgroundView = nil } }
40.116279
214
0.56058
d7427ec0f71c1d605c04f70dc0374838e985c216
6,231
import UIKit import RxSwift let SwitchViewBorderWidth: CGFloat = 2 class SwitchView: UIView { fileprivate var _selectedIndex = Variable(0) var selectedIndex: Observable<Int> { return _selectedIndex.asObservable() } var shouldAnimate = true var animationDuration: TimeInterval = AnimationDuration.Short fileprivate let buttons: Array<UIButton> fileprivate let selectionIndicator: UIView fileprivate let topSelectionIndicator: UIView fileprivate let bottomSelectionIndicator: UIView fileprivate let topBar = CALayer() fileprivate let bottomBar = CALayer() var selectionConstraint: NSLayoutConstraint! init(buttonTitles: Array<String>) { buttons = buttonTitles.map { (buttonTitle: String) -> UIButton in let button = UIButton(type: .custom) button.setTitle(buttonTitle, for: .normal) button.setTitle(buttonTitle, for: .disabled) if let titleLabel = button.titleLabel { titleLabel.font = UIFont.sansSerifFont(withSize: 13) titleLabel.backgroundColor = .white titleLabel.isOpaque = true } button.backgroundColor = .white button.setTitleColor(.black, for: .disabled) button.setTitleColor(.black, for: .selected) button.setTitleColor(.artsyGrayMedium(), for: .normal) return button } selectionIndicator = UIView() topSelectionIndicator = UIView() bottomSelectionIndicator = UIView() super.init(frame: CGRect.zero) setup() } override func layoutSubviews() { super.layoutSubviews() var rect = CGRect(x: 0, y: 0, width: layer.bounds.width, height: SwitchViewBorderWidth) topBar.frame = rect rect.origin.y = layer.bounds.height - SwitchViewBorderWidth bottomBar.frame = rect } required convenience init(coder aDecoder: NSCoder) { self.init(buttonTitles: []) } override var intrinsicContentSize : CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: 46) } @objc func selectedButton(_ button: UIButton!) { let index = buttons.index(of: button)! setSelectedIndex(index, animated: shouldAnimate) } subscript(index: Int) -> UIButton? { get { if index >= 0 && index < buttons.count { return buttons[index] } return nil } } } private extension SwitchView { func setup() { if let firstButton = buttons.first { firstButton.isEnabled = false } let widthPredicateMultiplier = "*\(widthMultiplier())" for i in 0 ..< buttons.count { let button = buttons[i] self.addSubview(button) button.addTarget(self, action: #selector(SwitchView.selectedButton(_:)), for: .touchUpInside) button.constrainWidth(to: self, predicate: widthPredicateMultiplier) if (i == 0) { button.alignLeadingEdge(with: self, predicate: nil) } else { button.constrainLeadingSpace(to: buttons[i-1], predicate: nil) } button.alignTop("\(SwitchViewBorderWidth)", bottom: "\(-SwitchViewBorderWidth)", to: self) } topBar.backgroundColor = UIColor.artsyGrayMedium().cgColor bottomBar.backgroundColor = UIColor.artsyGrayMedium().cgColor layer.addSublayer(topBar) layer.addSublayer(bottomBar) selectionIndicator.addSubview(topSelectionIndicator) selectionIndicator.addSubview(bottomSelectionIndicator) topSelectionIndicator.backgroundColor = .black bottomSelectionIndicator.backgroundColor = .black topSelectionIndicator.alignTop("0", leading: "0", bottom: nil, trailing: "0", to: selectionIndicator) bottomSelectionIndicator.alignTop(nil, leading: "0", bottom: "0", trailing: "0", to: selectionIndicator) topSelectionIndicator.constrainHeight("\(SwitchViewBorderWidth)") bottomSelectionIndicator.constrainHeight("\(SwitchViewBorderWidth)") addSubview(selectionIndicator) selectionIndicator.constrainWidth(to: self, predicate: widthPredicateMultiplier) selectionIndicator.alignTop("0", bottom: "0", to: self) selectionConstraint = selectionIndicator.alignLeadingEdge(with: self, predicate: nil).last! as! NSLayoutConstraint } func widthMultiplier() -> Float { return 1.0 / Float(buttons.count) } func setSelectedIndex(_ index: Int) { setSelectedIndex(index, animated: false) } func setSelectedIndex(_ index: Int, animated: Bool) { UIView.animateIf(shouldAnimate && animated, duration: animationDuration, options: .curveEaseOut) { let button = self.buttons[index] self.buttons.forEach { (button: UIButton) in button.isEnabled = true } button.isEnabled = false // Set the x-position of the selection indicator as a fraction of the total width of the switch view according to which button was pressed. let multiplier = CGFloat(index) / CGFloat(self.buttons.count) self.removeConstraint(self.selectionConstraint) // It's illegal to have a multiplier of zero, so if we're at index zero, we .just stick to the left side. if multiplier == 0 { self.selectionConstraint = self.selectionIndicator.alignLeadingEdge(with: self, predicate: nil).last! as! NSLayoutConstraint } else { self.selectionConstraint = NSLayoutConstraint(item: self.selectionIndicator, attribute: .left, relatedBy: .equal, toItem: self, attribute: .right, multiplier: multiplier, constant: 0) } self.addConstraint(self.selectionConstraint) self.layoutIfNeeded() } self._selectedIndex.value = index } }
36.869822
199
0.623495