repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
visenze/visearch-sdk-swift
ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Request/VaEvent.swift
1
13168
// // VaEvent.swift // ViSenzeAnalytics // // Created by Hung on 8/9/20. // Copyright © 2020 ViSenze. All rights reserved. // import UIKit /// Protocol to generate dictionary for query parameters (in the URL) public protocol VaParamsProtocol{ /// Generate dictionary of parameters , will be appended into query string /// /// - returns: dictionary func toDict() -> [String: String] } // predefine events public enum VaEventAction: String { case PRODUCT_CLICK = "product_click" case PRODUCT_VIEW = "product_view" case VIEW = "view" case CLICK = "click" case SEARCH = "search" case APP_INSTALL = "app_install" case APP_UNINSTALL = "app_uninstall" case TRANSACTION = "transaction" case ADD_TO_CART = "add_to_cart" case ADD_TO_WISHLIST = "add_to_wishlist" case RESULT_LOAD = "result_load" } public class VaEvent: VaParamsProtocol { // MARK: common fields /// event category public var category: String? = nil // action public var action: String // event name public var name: String? = nil // Linux timestamp public var ts: Int64 public var value: String? = nil public var label: String? = nil public var queryId: String? = nil public var fromReqId: String? = nil public var uid: String? = nil public var sid: String? = nil public var source: String? = nil // product ID public var pid: String? = nil // image URL public var imUrl: String? = nil // position of product in search result public var pos: Int? = nil public var brand: String? = nil public var price: Double? = nil public var currency: String? = nil public var productUrl: String? = nil public var transId: String? = nil public var url: String? = nil public var referrer: String? = nil // MARK: device fields public var aaid: String? = nil public var didmd5: String? = nil public var geo: String? = nil // MARK: other fields public var campaign: String? = nil public var adGroup: String? = nil public var creative: String? = nil public var n1: Double? = nil public var n2: Double? = nil public var n3: Double? = nil public var n4: Double? = nil public var n5: Double? = nil public var s1: String? = nil public var s2: String? = nil public var s3: String? = nil public var s4: String? = nil public var s5: String? = nil public var json: String? = nil // this is for custom event public init?(action: String){ if action.isEmpty { print("\(type(of: self)).\(#function)[line:\(#line)] - error: action parameter is missing") return nil } self.action = action self.ts = Int64(Date().timeIntervalSince1970 * 1000) } public func isTransactionEvent() -> Bool { return action == VaEventAction.TRANSACTION.rawValue } // MARK: event constructor helpers public static func newSearchEvent(queryId: String) -> VaEvent? { if queryId.isEmpty { print("ViSenze Analytics - missing queryId for search event") return nil } let searchEvent = VaEvent(action: VaEventAction.SEARCH.rawValue) searchEvent?.queryId = queryId return searchEvent } public static func newProductClickEvent(queryId: String, pid: String) -> VaEvent? { if queryId.isEmpty || pid.isEmpty { print("ViSenze Analytics - missing queryId or pid for product click event") return nil } let productClick = VaEvent(action: VaEventAction.PRODUCT_CLICK.rawValue) productClick?.queryId = queryId productClick?.pid = pid return productClick } public static func newProductClickEvent(queryId: String, pid: String, imgUrl: String, pos: Int) -> VaEvent? { if queryId.isEmpty || pid.isEmpty || imgUrl.isEmpty{ print("ViSenze Analytics - missing queryId or pid or imgUrl for product click event") return nil } if pos < 1 { print("ViSenze Analytics - pos (product position in search results) must be at least 1") return nil } let productClick = VaEvent(action: VaEventAction.PRODUCT_CLICK.rawValue) productClick?.queryId = queryId productClick?.pid = pid productClick?.imUrl = imgUrl productClick?.pos = pos return productClick } public static func newProductImpressionEvent(queryId: String, pid: String) -> VaEvent? { if queryId.isEmpty || pid.isEmpty { print("ViSenze Analytics - missing queryId or pid for product impression event") return nil } let productView = VaEvent(action: VaEventAction.PRODUCT_VIEW.rawValue) productView?.queryId = queryId productView?.pid = pid return productView } public static func newProductImpressionEvent(queryId: String, pid: String, imgUrl: String, pos: Int) -> VaEvent? { if queryId.isEmpty || pid.isEmpty || imgUrl.isEmpty{ print("ViSenze Analytics - missing queryId or pid or imgUrl for product impression event") return nil } if pos < 1 { print("ViSenze Analytics - pos (product position in search results) must be at least 1") return nil } let productView = VaEvent(action: VaEventAction.PRODUCT_VIEW.rawValue) productView?.queryId = queryId productView?.pid = pid productView?.imUrl = imgUrl productView?.pos = pos return productView } public static func newAdd2CartEvent(queryId: String, pid: String) -> VaEvent? { if queryId.isEmpty || pid.isEmpty { print("ViSenze Analytics - missing queryId or pid for add to cart event") return nil } let add2Cart = VaEvent(action: VaEventAction.ADD_TO_CART.rawValue) add2Cart?.queryId = queryId add2Cart?.pid = pid return add2Cart } public static func newAdd2CartEvent(queryId: String, pid: String, imgUrl: String, pos: Int) -> VaEvent? { if queryId.isEmpty || pid.isEmpty || imgUrl.isEmpty{ print("ViSenze Analytics - missing queryId or pid or imgUrl for add to cart event") return nil } if pos < 1 { print("ViSenze Analytics - pos (product position in search results) must be at least 1") return nil } let add2Cart = VaEvent(action: VaEventAction.ADD_TO_CART.rawValue) add2Cart?.queryId = queryId add2Cart?.pid = pid add2Cart?.imUrl = imgUrl add2Cart?.pos = pos return add2Cart } public static func newAdd2WishListEvent(queryId: String, pid: String) -> VaEvent? { if queryId.isEmpty || pid.isEmpty { print("ViSenze Analytics - missing queryId or pid for add to wishlist event") return nil } let add2Wishlist = VaEvent(action: VaEventAction.ADD_TO_WISHLIST.rawValue) add2Wishlist?.queryId = queryId add2Wishlist?.pid = pid return add2Wishlist } public static func newAdd2WishListEvent(queryId: String, pid: String, imgUrl: String, pos: Int) -> VaEvent? { if queryId.isEmpty || pid.isEmpty || imgUrl.isEmpty{ print("ViSenze Analytics - missing queryId or pid or imgUrl for add to wishlist event") return nil } if pos < 1 { print("ViSenze Analytics - pos (product position in search results) must be at least 1") return nil } let add2Wishlist = VaEvent(action: VaEventAction.ADD_TO_WISHLIST.rawValue) add2Wishlist?.queryId = queryId add2Wishlist?.pid = pid add2Wishlist?.imUrl = imgUrl add2Wishlist?.pos = pos return add2Wishlist } public static func newTransactionEvent(queryId: String, value: Double) -> VaEvent? { return newTransactionEvent(queryId: queryId, transactionId: "", value: value) } public static func newTransactionEvent(queryId: String, transactionId: String, value: Double) -> VaEvent? { if queryId.isEmpty { print("ViSenze Analytics - queryId is missing for transaction event") return nil } let transEvnt = VaEvent(action: VaEventAction.TRANSACTION.rawValue) transEvnt?.queryId = queryId transEvnt?.transId = transactionId transEvnt?.value = String(value) return transEvnt } public static func generateRandomTransId() -> String { return UUID().uuidString } public static func newResultLoadEvent(queryId: String, pid: String?) -> VaEvent? { if queryId.isEmpty { print("ViSenze Analytics - queryId is missing for result_load event") return nil } let resultLoadEvt = VaEvent(action: VaEventAction.RESULT_LOAD.rawValue) resultLoadEvt?.queryId = queryId resultLoadEvt?.pid = pid return resultLoadEvt } public static func newClickEvent() -> VaEvent? { return VaEvent(action: VaEventAction.CLICK.rawValue) } public static func newImpressionEvent() -> VaEvent? { return VaEvent(action: VaEventAction.VIEW.rawValue) } // MARK: param protocol public func toDict() -> [String: String] { var dict : [String:String] = [:] dict["action"] = action dict["ts"] = String(ts) if let category = self.category { dict["cat"] = category } if let name = self.name { dict["name"] = name } if let value = self.value { dict["value"] = value } if let label = self.label { dict["label"] = label } if let queryId = self.queryId { dict["queryId"] = queryId } if let fromReqId = self.fromReqId { dict["fromReqId"] = fromReqId } if let uid = self.uid { dict["uid"] = uid } if let sid = self.sid { dict["sid"] = sid } if let source = self.source { dict["source"] = source } if let pid = self.pid { dict["pid"] = pid } if let imUrl = self.imUrl { dict["imUrl"] = imUrl } if let pos = self.pos { dict["pos"] = String(pos) } if let brand = self.brand { dict["brand"] = brand } if let price = self.price { dict["price"] = String(price) } if let currency = self.currency { dict["currency"] = currency } if let productUrl = self.productUrl { dict["productUrl"] = productUrl } if let transId = self.transId { dict["transId"] = transId } if let url = self.url { dict["url"] = url } if let referrer = self.referrer { dict["r"] = referrer } if let aaid = self.aaid { dict["aaid"] = aaid } if let didmd5 = self.didmd5 { dict["didmd5"] = didmd5 } if let geo = self.geo { dict["geo"] = geo } if let campaign = self.campaign { dict["c"] = campaign } if let adGroup = self.adGroup { dict["cag"] = adGroup } if let creative = self.creative { dict["cc"] = creative } if let n1 = self.n1 { dict["n1"] = String(n1) } if let n2 = self.n2 { dict["n2"] = String(n2) } if let n3 = self.n3 { dict["n3"] = String(n3) } if let n4 = self.n4 { dict["n4"] = String(n4) } if let n5 = self.n5 { dict["n5"] = String(n5) } if let s1 = self.s1 { dict["s1"] = s1 } if let s2 = self.s2 { dict["s2"] = s2 } if let s3 = self.s3 { dict["s3"] = s3 } if let s4 = self.s4 { dict["s4"] = s4 } if let s5 = self.s5 { dict["s5"] = s5 } if let json = self.json { dict["json"] = json } return dict } }
mit
3c1f60ffbffcc517e163bff6dd3a93ed
27.194861
118
0.543556
4.600629
false
false
false
false
S-Shimotori/Chalcedony
Chalcedony/Chalcedony/CCDSettingKaeritaiTableViewController.swift
1
2293
// // CCDSettingKaeritaiTableViewController.swift // Chalcedony // // Created by S-Shimotori on 6/30/15. // Copyright (c) 2015 S-Shimotori. All rights reserved. // import UIKit class CCDSettingKaeritaiTableViewController: UITableViewController, UITextViewDelegate { @IBOutlet private weak var textViewToShowKaeritaiMessage: UITextView! private let minNumberOfChars = 1 private let maxNumberOfChars = 100 override func viewDidLoad() { super.viewDidLoad() textViewToShowKaeritaiMessage.text = CCDSetting.messageToTweetKaeritai changeTextViewColor(minNumberOfChars <= count(textViewToShowKaeritaiMessage.text) && count(textViewToShowKaeritaiMessage.text) <= maxNumberOfChars) textViewToShowKaeritaiMessage.delegate = self } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if minNumberOfChars <= count(textViewToShowKaeritaiMessage.text) && count(textViewToShowKaeritaiMessage.text) <= maxNumberOfChars { CCDSetting.messageToTweetKaeritai = textViewToShowKaeritaiMessage.text println("set") } } private func changeTextViewColor(valid: Bool) { if valid { textViewToShowKaeritaiMessage.textColor = .ultramarineBlueColor() } else { textViewToShowKaeritaiMessage.textColor = .cherryPinkColor() } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "「かえりたい!」メッセージ" } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "最大\(maxNumberOfChars)文字" } func textViewShouldBeginEditing(textView: UITextView) -> Bool { println("begin") return true } func textViewShouldEndEditing(textView: UITextView) -> Bool { textView.endEditing(true) println(count(textView.text)) return true } func textViewDidChange(textView: UITextView) { changeTextViewColor(minNumberOfChars <= count(textViewToShowKaeritaiMessage.text) && count(textViewToShowKaeritaiMessage.text) <= maxNumberOfChars) println("textViewDidChange") } }
mit
cf6f6a46b378d3737a55853403ce06a9
33.784615
102
0.702786
5.345154
false
false
false
false
Legoless/iOS-Course
2015-1/Lesson7/Converter/Converter/ViewController.swift
1
4446
// // ViewController.swift // Converter // // Created by Dal Rupnik on 21/10/15. // Copyright © 2015 Unified Sense. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let usdRate = 1.14 let jpyRate = 136.12 let gbpRate = 0.71 let rubRate = 70.51 var currentCurrency = Currency(type: "USD", rate: 1.14) var converter = Converter.instance lazy var locationManager : CLLocationManager = { let manager = CLLocationManager() manager.delegate = self return manager }() @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var textField: UITextField! @IBOutlet weak var usdButton: UIButton! @IBOutlet weak var jpyButton: UIButton! @IBOutlet weak var autoButton: UIButton! @IBOutlet weak var locationLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() autoButton.selected = true } @IBAction func usdButtonTap(sender: UIButton) { currentCurrency = Currency(type: "USD", rate: usdRate) usdButton.selected = true jpyButton.selected = false autoButton.selected = false; } @IBAction func jpyButtonTap(sender: UIButton) { currentCurrency = Currency(type: "JPY", rate: jpyRate) usdButton.selected = false jpyButton.selected = true autoButton.selected = false; } @IBAction func autoButtonTap(sender: UIButton) { usdButton.selected = false jpyButton.selected = false autoButton.selected = true; } @IBAction func convertButtonTap(sender: UIButton) { if autoButton.selected { valueFromLocation() } else { convertValue() } } func convertValue () { if let value = Double(textField.text!) { let (converted, _) = value.convert(Currency(), to: currentCurrency) resultLabel.text = "In \(currentCurrency.type): \(converted)" resultLabel.textColor = UIColor.blackColor() } else { resultLabel.text = "Error: Enter valid value!" resultLabel.textColor = UIColor.redColor() } } func valueFromLocation () { if CLLocationManager.authorizationStatus() == .NotDetermined { locationManager.requestWhenInUseAuthorization() } else if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { resultLabel.text = "" resultLabel.textColor = UIColor.blackColor() locationLabel.text = "Lat: \(location.coordinate.latitude) Long: \(location.coordinate.longitude)" manager.stopUpdatingLocation() CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemark, error) -> Void in print ("\(placemark?.first?.ISOcountryCode)") if placemark?.first?.ISOcountryCode == "GB" { self.currentCurrency = Currency(type: "GBP", rate: self.gbpRate) } else if placemark?.first?.ISOcountryCode == "JP" { self.currentCurrency = Currency(type: "JPY", rate: self.jpyRate) } else if placemark?.first?.ISOcountryCode == "RU" { self.currentCurrency = Currency(type: "RUB", rate: self.rubRate) } else { self.currentCurrency = Currency(type: "USD", rate: self.usdRate) } self.convertValue() }) } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { //resultLabel.text = error.description //resultLabel.textColor = UIColor.redColor() } }
mit
aaabf06755aac9689917be8fddb776a3
30.524823
114
0.587627
5.381356
false
false
false
false
lazersly/GithubzToGo
GithubzToGo/RepositoryJSONParser.swift
1
1189
// // RepositoryJSONParser.swift // GithubzToGo // // Created by Brandon Roberts on 4/14/15. // Copyright (c) 2015 BR World. All rights reserved. // import Foundation class RepositoryJSONParser { class func reposFromJSONData(jsonData: NSData) -> [Repository] { var repos = [Repository]() var jsonError : NSError? if let root = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &jsonError) as? [String : AnyObject], items = root["items"] as? [[String : AnyObject]] { for itemDescription in items { if let name = itemDescription["name"] as? String, id = itemDescription["id"] as? NSNumber, ownerDescription = itemDescription["owner"] as? [String : AnyObject], author = ownerDescription["login"] as? String, htmlURL = itemDescription["html_url"] as? String, description = itemDescription["description"] as? String { let id_str = id.description let repo = Repository(id: id_str, name: name, author: author, description: description, htmlURL: htmlURL) repos.append(repo) } } } return repos } }
mit
895267aa38086299aae07b7943144d64
30.289474
120
0.626577
4.403704
false
false
false
false
kkserver/kk-ios-app
KKApp/KKApp/KKApplication_Window.swift
1
2082
// // KKApplication_Window.swift // KKApp // // Created by zhanghailong on 2016/11/27. // Copyright © 2016年 kkserver.cn. All rights reserved. // import Foundation import KKView import KKObserver public extension KKApplication { public func openWindow() -> (UIWindow,KKDocument) { let v:UIWindow = UIWindow.init(frame: UIScreen.main.bounds) let document:KKDocument = KKDocument.init(view: v); let name:String? = stringValue(["app","kk-view"],nil) if(name != nil) { document.loadXML(contentsOf: bundle.url(forResource: name, withExtension: "xml")!) } let p = firstChild if p != nil { v.rootViewController = p!.openViewController() } on(["action"], { (observer:KKObserver, changedKey:[String], weakObject:AnyObject?) in let name = observer.stringValue(["action","name"], "") if(weakObject != nil && name == "present") { var viewController = (weakObject as! UIWindow?)?.rootViewController while( viewController != nil && viewController?.presentedViewController != nil) { viewController = viewController?.presentedViewController } if viewController != nil { let app = observer.app if app != nil { let a = app!.open(app!.stringValue(["action","present"],"")!) let animated = app!.booleanValue(["action","animated"],true) if(a != nil) { viewController?.present(a!.openViewController(), animated: animated, completion: nil) } } } } }, v) return (v,document) } }
mit
677368bcaca561f0da0de975f1050ca0
30.5
113
0.469456
5.573727
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Onboarding/Main/LoginViewController.swift
1
9408
// // LoginViewController.swift // HTWDD // // Created by Mustafa Karademir on 06.08.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import UIKit import Lottie import RxSwift import RxCocoa import SwiftKeychainWrapper class LoginViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var lblLoginHeader: UILabel! @IBOutlet weak var lblLoginDescription: UILabel! @IBOutlet weak var lblLoginInformation: UILabel! @IBOutlet weak var tfUserName: TextField! @IBOutlet weak var tfUserPassword: PasswordField! @IBOutlet weak var padLockAnimationView: AnimationView! @IBOutlet weak var btnLogin: UIButton! @IBOutlet weak var btnClose: UIButton! @IBOutlet weak var scrollView: UIScrollView! // MARK: - Properties weak var context: AppContext? weak var delegate: UIPageViewSwipeDelegate? var delegateClosure: (() -> Void)? = nil private let visualEffectView = UIVisualEffectView(effect: nil) private lazy var animator: UIViewPropertyAnimator = { return UIViewPropertyAnimator(duration: 0.4, curve: .easeInOut, animations: { self.visualEffectView.effect = UIBlurEffect(style: .regular) }) }() private lazy var padLockAnimation: Animation? = { return Animation.named("PadlockGrey") }() private lazy var errorLoginAlert: UIAlertController = { return UIAlertController(title: R.string.localizable.gradesNoResultsTitle(), message: R.string.localizable.gradesNoResultsMessage(), preferredStyle: .alert).also { alert in alert.view.tintColor = UIColor.htw.Label.primary alert.addAction(UIAlertAction(title: R.string.localizable.ok(), style: .default, handler: nil)) } }() private struct State { var hasUserName: Bool = false var hasUserPassword: Bool = false var hasUserNameAndPassword: Bool { return hasUserName && hasUserPassword } } private let state = BehaviorRelay(value: State()) // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() observe() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.padLockAnimationView.play() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if delegate == nil { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(25), execute: { [weak self] in guard let self = self else { return } self.animator.startAnimation() }) } } // MARK: - User Interaction @IBAction func onButtonTap(_ sender: UIButton) { view.endEditing(true) sender.setState(with: .inactive) if let authData = "s\(tfUserName.text?.nilWhenEmpty ?? String("")):\(tfUserPassword.text?.nilWhenEmpty ?? String(""))".data(using: .utf8) { context?.apiService.requestCourses(auth: authData.base64EncodedString(options: .lineLength64Characters)) .asObservable() .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] result in guard let self = self else { return } KeychainService.shared[.authToken] = authData.base64EncodedString(options: .lineLength64Characters) self.delegate?.next(animated: true) if let delegateClosure = self.delegateClosure { delegateClosure() self.disolveWithAnimation() } }, onError: { [weak self] in guard let self = self else { return } self.present(self.errorLoginAlert, animated: true, completion: nil) sender.setState(with: .active) Log.error($0) }) .disposed(by: rx_disposeBag) } } @IBAction func onCancelTap(_ sender: UIButton) { UIImpactFeedbackGenerator(style: .medium) .also { $0.prepare() } .apply { $0.impactOccurred() } disolveWithAnimation() } private func disolveWithAnimation() { UIViewPropertyAnimator(duration: 0.25, curve: .easeInOut, animations: { [weak self] in guard let self = self else { return } self.visualEffectView.effect = nil }).apply { $0.startAnimation() } DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(170)) { [weak self] in guard let self = self else { return } self.dismiss(animated: true, completion: nil) } } } // MARK: - Setup extension LoginViewController { private func setup() { lblLoginHeader.apply { $0.text = R.string.localizable.onboardingLoginHeader() $0.textColor = UIColor.htw.Label.primary } lblLoginDescription.apply { $0.text = R.string.localizable.onboardingLoginDescription() $0.textColor = UIColor.htw.Label.primary } lblLoginInformation.apply { $0.text = R.string.localizable.onboardingLoginInformation() $0.textColor = UIColor.htw.Label.secondary } padLockAnimationView.apply { $0.animation = padLockAnimation $0.contentMode = .scaleAspectFill $0.loopMode = .playOnce } tfUserName.apply { $0.placeholder = R.string.localizable.onboardingUnixLoginSPlaceholder() $0.backgroundColor = UIColor.htw.cellBackground $0.textColor = UIColor.htw.Label.primary $0.delegate = self } tfUserPassword.apply { $0.placeholder = R.string.localizable.onboardingUnixLoginPasswordPlaceholder() $0.backgroundColor = UIColor.htw.cellBackground $0.textColor = UIColor.htw.Label.primary $0.delegate = self } btnLogin.apply { $0.setTitle(R.string.localizable.onboardingUnixLoginTitle(), for: .normal) $0.setState(with: .inactive) $0.makeDropShadow() } if delegate == nil { btnClose.apply { $0.isHidden = false $0.setTitle(R.string.localizable.onboardingUnixLoginNotnow(), for: .normal) } view.insertSubview(visualEffectView.also { $0.frame = self.view.frame }, at: 0) } view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(view.endEditing(_:)))) keyboardObserve() } private func keyboardObserve() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { adjustContent(with: keyboardSize.height - 37) } } @objc private func keyboardWillHide(notification: Notification) { adjustContent(with: 0) } private func adjustContent(with size: CGFloat) { scrollView.also { let inset = UIEdgeInsets(top: 0, left: 0, bottom: size, right: 0) $0.contentInset = inset $0.scrollIndicatorInsets = inset }.scrollToBottom() view.layoutIfNeeded() } private func observe() { state.asObservable() .map({ $0.hasUserNameAndPassword }) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] hasUserNameAndPassword in guard let self = self else { return } self.btnLogin.setState(with: hasUserNameAndPassword ? .active : .inactive) }, onError: { Log.error($0) }) .disposed(by: rx_disposeBag) } } // MARK: - Textfield Delegate extension LoginViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let textFieldText = textField.text else { return true } let newLength = textFieldText.count + string.count - range.length switch textField { case tfUserName: var mutableState = state.value mutableState.hasUserName = newLength >= 5 state.accept(mutableState) return newLength <= 5 case tfUserPassword: var mutableState = state.value mutableState.hasUserPassword = newLength >= 1 state.accept(mutableState) return true default: return true } } }
gpl-2.0
fb1a5a3501e9b2cdf62ee29631771699
37.08502
180
0.602211
5.038565
false
false
false
false
gtranchedone/NFYU
NFYUTests/TestSystemLocationManager.swift
1
9033
// // TestSystemLocationManager.swift // NFYU // // Created by Gianluca Tranchedone on 03/11/2015. // Copyright © 2015 Gianluca Tranchedone. All rights reserved. // import XCTest import CoreLocation @testable import NFYU class TestSystemUserLocationManager: XCTestCase { var systemLocationManager: SystemUserLocationManager? var fakeLocationManager: FakeLocationManager? override func setUp() { super.setUp() fakeLocationManager = FakeLocationManager() systemLocationManager = SystemUserLocationManager(locationManager: fakeLocationManager) } override func tearDown() { FakeLocationManager.stubAuthorizationStatus = .notDetermined systemLocationManager = nil super.tearDown() } func testInfoPlistContainsRequiredInfoForUsingLocationServices() { XCTAssertNotNil(Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription")) } func testSystemLocationManagerSetsItselfAsTheLocationManagerDelegate() { XCTAssertTrue(fakeLocationManager!.delegate === systemLocationManager) } // MARK: Authorization for Use of Location Services func testSystemLocationManagerDidNotRequestAuthorizationIfPermissionsAreNotDetermined() { XCTAssertFalse(systemLocationManager!.didRequestAuthorization) } func testSystemLocationManagerDidNotRequestAuthorizationIfPermissionsAreGranted() { FakeLocationManager.stubAuthorizationStatus = .authorizedWhenInUse XCTAssertTrue(systemLocationManager!.didRequestAuthorization) } func testSystemLocationManagerDidNotRequestAuthorizationIfPermissionsAreDenied() { FakeLocationManager.stubAuthorizationStatus = .denied XCTAssertTrue(systemLocationManager!.didRequestAuthorization) } func testSystemLocationManagerDidNotRequestAuthorizationIfPermissionsAreRestricted() { FakeLocationManager.stubAuthorizationStatus = .restricted XCTAssertTrue(systemLocationManager!.didRequestAuthorization) } func testSystemLocationManagerShouldNotRequestAuthorizationIfPermissionsAreGranted() { FakeLocationManager.stubAuthorizationStatus = .authorizedWhenInUse XCTAssertFalse(systemLocationManager!.requestUserAuthorizationForUsingLocationServices({})) } func testSystemLocationManagerShouldNotRequestAuthorizationIfPermissionsAreDenied() { FakeLocationManager.stubAuthorizationStatus = .denied XCTAssertFalse(systemLocationManager!.requestUserAuthorizationForUsingLocationServices({})) } func testSystemLocationManagerShouldNotRequestAuthorizationIfPermissionsAreRestricted() { FakeLocationManager.stubAuthorizationStatus = .restricted XCTAssertFalse(systemLocationManager!.requestUserAuthorizationForUsingLocationServices({})) } func testSystemLocationManagerDoesNotAllowUsageOfLocationServicesWhenPermissionIsNotDetermined() { XCTAssertFalse(systemLocationManager!.locationServicesEnabled) } func testSystemLocationManagerAllowsUsageOfLocationServicesWhenPermissionIsGranted() { FakeLocationManager.stubAuthorizationStatus = .authorizedWhenInUse XCTAssertTrue(systemLocationManager!.locationServicesEnabled) } func testSystemLocationManagerDoesNotAllowUsageOfLocationServicesWhenPermissionIsDenied() { FakeLocationManager.stubAuthorizationStatus = .denied XCTAssertFalse(systemLocationManager!.locationServicesEnabled) } func testSystemLocationManagerDoesNotAllowUsageOfLocationServicesWhenPermissionIsRestricted() { FakeLocationManager.stubAuthorizationStatus = .restricted XCTAssertFalse(systemLocationManager!.locationServicesEnabled) } // MARK: Requesting Location Updates func testSystemLocationManagerRequestsLocationUsageAuthorizationIfNeeded() { systemLocationManager?.requestCurrentLocation { _ in } XCTAssertTrue(fakeLocationManager!.didRequestAuthorizationForInUse) } func testSystemLocationManagerRequestsLocationUsageAuthorizationIfAlreadyAuthorized() { FakeLocationManager.stubAuthorizationStatus = .authorizedWhenInUse systemLocationManager?.requestCurrentLocation { _ in } XCTAssertFalse(fakeLocationManager!.didRequestAuthorizationForInUse) } func testSystemLocationManagerDoesNotRequestLocationUsageAuthorizationIfAlreadyDenied() { FakeLocationManager.stubAuthorizationStatus = .denied systemLocationManager?.requestCurrentLocation { _ in } XCTAssertFalse(fakeLocationManager!.didRequestAuthorizationForInUse) } func testSystemLocationManagerCallsCompletionBlockWithErrorIfLocationServicesAuthorizationIsDenied() { FakeLocationManager.stubAuthorizationStatus = .denied let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .error(_): break default: XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } func testSystemLocationManagerCallsCompletionBlockWithErrorIfLocationServicesAuthorizationIsRestricted() { FakeLocationManager.stubAuthorizationStatus = .restricted let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .error(_): break default: XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } func testSystemLocationManagerCallsCompletionBlockWithErrorIfLocationServicesAuthorizationBecomesDenied() { let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .error(_): break default: XCTFail() } expectation.fulfill() } FakeLocationManager.stubAuthorizationStatus = .denied systemLocationManager?.locationManager(fakeLocationManager!, didChangeAuthorization: .denied) waitForExpectations(timeout: 1.0, handler: nil) } func testSystemLocationManagerCallsCompletionBlockWithErrorIfLocationServicesAuthorizationBecomesRestricted() { let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .error(_): break default: XCTFail() } expectation.fulfill() } FakeLocationManager.stubAuthorizationStatus = .restricted systemLocationManager?.locationManager(fakeLocationManager!, didChangeAuthorization: .restricted) waitForExpectations(timeout: 1.0, handler: nil) } func testSystemLocationManagerForwardsRequestForUpdatingCurrentLocationToLocationManager() { FakeLocationManager.stubAuthorizationStatus = .authorizedWhenInUse systemLocationManager?.requestCurrentLocation { _ in } XCTAssertTrue(fakeLocationManager!.didRequestLocation) } func testSystemLocationManagerCallsCompletionBlockWithErrorIfLocationManagerFailsToUpdateLocation() { let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .error(_): break default: XCTFail() } expectation.fulfill() } let error = NSError(domain: "testDomain", code: 400, userInfo: nil) systemLocationManager?.locationManager(fakeLocationManager!, didFailWithError: error) waitForExpectations(timeout: 1.0, handler: nil) } func testSystemLocationManagerCallsCompletionBlockWithLastFoundLocationIfLocationManagerSucceedsInUpdatingLocation() { let expectation = self.expectation(description: "Location update request calls completion block") systemLocationManager?.requestCurrentLocation { result in switch result { case .success(_): break default: XCTFail() } expectation.fulfill() } let locations: [CLLocation] = [CLLocation(latitude: 0, longitude: 0)] systemLocationManager?.locationManager(fakeLocationManager!, didUpdateLocations: locations) waitForExpectations(timeout: 1.0, handler: nil) } }
mit
6b59681c6ec2f82dff17fceaf8617ff8
41.603774
122
0.724092
7.483016
false
true
false
false
Adlai-Holler/Flux.swift
Examples/TodoMVC/TodoMVC/TodoViewController.swift
1
6482
// // ViewController.swift // TodoMVC // // Created by Adlai Holler on 2/6/16. // Copyright © 2016 Adlai Holler. All rights reserved. // import UIKit import CoreData import AsyncDisplayKit import ReactiveCocoa import ArrayDiff import Whisper final class TodoViewController: ASViewController, ASTableDelegate, ASTableDataSource { struct State { var items: [TodoItem] var editingItemID: NSManagedObjectID? static let empty = State(items: [], editingItemID: nil) } var tableNode: ASTableNode { return node as! ASTableNode } private(set) var state: State = .empty let store: TodoStore let queue: dispatch_queue_t let deinitDisposable = CompositeDisposable() private let nodeCache = NSMapTable.strongToWeakObjectsMapTable() /// The table data, as set on our private queue. private var pendingTableData: [BasicSection<ASCellNode>] = [] /// The table data, as set on the main queue & vended to the ASTableNode. private var tableData: [BasicSection<ASCellNode>] = [] private let hasTableDataBeenQueried = Atomic(false) init(store: TodoStore) { self.store = store queue = dispatch_queue_create("TodoViewController Queue", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0)) super.init(node: ASTableNode(style: .Plain)) title = "Todo MVC" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "didTapAdd") navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: "didTapClear") tableNode.dataSource = self tableNode.delegate = self /// Async onto our queue so we can wait for this to finish /// before our first layout if needed. dispatch_async(queue) { self.deinitDisposable += store.changes.observeNext { [weak self] event in self?.handleStoreChangeWithEvent(event) } var newState = self.state newState.items = store.getAll() self.setState(newState) } } deinit { deinitDisposable.dispose() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Model Observing private func handleStoreChangeWithEvent(event: TodoStore.Event) { guard case let .Change(_, error) = event else { return } if let error = error { dispatch_async(dispatch_get_main_queue()) { let message = Message(title: error, backgroundColor: UIColor.redColor()) Whisper(message, to: self.navigationController!) } } dispatch_async(queue) { var newState = self.state newState.items = self.store.getAll() newState.editingItemID = self.store.editingItemID self.setState(newState) } } // MARK: UI Action Observing @objc private func didTapAdd() { TodoAction.Create.dispatch() } @objc private func didTapClear() { TodoAction.DeleteAllCompleted.dispatch() } // MARK: State Updating func renderTableData(nodeCache: NodeCache) -> [BasicSection<ASCellNode>] { let state = self.state let nodes = state.items.map { item -> TodoNode in let state = TodoNode.State(item: item, editingTitle: state.editingItemID == item.objectID) /// We can't use `node.id` here because the id will change /// when the server assigns a permanent one. let node: TodoNode = nodeCache.nodeForKey("Todo Item Node \(item.objectID!.URIRepresentation())", create: { key in TodoNode(state: state) }) node.setState(state) return node } return [ BasicSection(name: "Single Section", items: nodes) ] } private func setState(newState: State) { state = newState let oldData = pendingTableData let newData = renderTableData(nodeCache) let diff = oldData.diffNested(newData) if diff.isEmpty { return } self.pendingTableData = newData let hasBeenQueried = hasTableDataBeenQueried.withValue { isQueried -> Bool in if !isQueried { tableData = newData } return isQueried } if !hasBeenQueried { return } let deletedIndexPaths = diff.itemDiffs[0]?.removedIndexes.indexPathsInSection(0) dispatch_async(dispatch_get_main_queue()) { let tableView = self.tableNode.view /// A little gross but our ASEditableTextNodes refuse to resign during updates! if let deletedIndexPaths = deletedIndexPaths { self.forceResignIfFirstResponderIsAtIndexPath(deletedIndexPaths) } tableView.beginUpdates() self.tableData = newData diff.applyToTableView(tableView, rowAnimation: .Automatic) tableView.endUpdates() } } private func forceResignIfFirstResponderIsAtIndexPath(indexPaths: [NSIndexPath]) { for indexPath in indexPaths { tableNode.view.cellForRowAtIndexPath(indexPath)?.endEditing(true) } } override func viewDidLoad() { super.viewDidLoad() tableNode.view.tableFooterView = UIView() } override func viewWillLayoutSubviews() { dispatch_sync(queue, {}) super.viewWillLayoutSubviews() } // MARK: Table View Data Source Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { hasTableDataBeenQueried.value = true return tableData.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData[section].items.count } func tableView(tableView: ASTableView, nodeForRowAtIndexPath indexPath: NSIndexPath) -> ASCellNode { return tableData[indexPath]! } // MARK: Table View Delegate Methods func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard let node = (tableView as? ASTableView)?.nodeForRowAtIndexPath(indexPath) as? TodoNode else { return } TodoAction.BeginEditingTitle(node.state.item.objectID!).dispatch() tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
045bd6a3d176233d3fb03f2a93a7929b
32.755208
160
0.647277
4.880271
false
false
false
false
OpenStack-mobile/aerogear-ios-oauth2
AeroGearOAuth2/OpenIdClaim.swift
2
5389
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * 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 /** Standard claims as described in spec: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims */ open class OpenIdClaim: CustomStringConvertible { /// Subject - Identifier for the End-User at the Issuer. open var sub: String? /// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. open var name: String? /// Given name(s) or first name(s) of the End-User. open var givenName: String? /// Surname(s) or last name(s) of the End-User. open var familyName: String? /// Middle name(s) of the End-User. open var middleName: String? /// Casual name of the End-User that may or may not be the same as the given_name. open var nickname: String? /// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. open var preferredUsername: String? /// URL of the End-User's profile page. open var profile: String? /// URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. open var picture: String? /// URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with. open var website: String? /// End-User's preferred e-mail address. open var email: String? /// True if the End-User's e-mail address has been verified; otherwise false. open var emailVerified: Bool? /// End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable. open var gender: String? /// End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. open var birthdate: String? /// String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. open var zoneinfo: String? /// [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. open var locale: String? /// End-User's preferred telephone number. open var phoneNumber: String? /// True if the End-User's phone number has been verified; otherwise false. open var phoneNumberVerified: Bool? /// End-User's preferred postal address. open var address: [String: AnyObject?]? /// Time the End-User's information was last updated. open var updatedAt: Int? // google specific - not in spec? open var kind: String? open var hd: String? /// Display all the claims. open var description: String { return "sub: \(sub)\nname: \(name)\ngivenName: \(givenName)\nfamilyName: \(familyName)\nmiddleName: \(middleName)\n" + "nickname: \(nickname)\npreferredUsername: \(preferredUsername)\nprofile: \(profile)\npicture: \(picture)\n" + "website: \(website)\nemail: \(email)\nemailVerified: \(emailVerified)\ngender: \(gender)\nbirthdate: \(birthdate)\n" } /// Initialize an OpenIDClaim from a dictionary. all information not available are optional values set to .None. public init(fromDict: [String: AnyObject]) { sub = fromDict["sub"] as? String name = fromDict["name"] as? String givenName = fromDict["given_name"] as? String familyName = fromDict["family_name"] as? String middleName = fromDict["middle_name"] as? String nickname = fromDict["nickname"] as? String preferredUsername = fromDict["preferred_username"] as? String profile = fromDict["profile"] as? String picture = fromDict["picture"] as? String website = fromDict["website"] as? String email = fromDict["email"] as? String emailVerified = fromDict["email_verified"] as? Bool gender = fromDict["gender"] as? String zoneinfo = fromDict["zoneinfo"] as? String locale = fromDict["locale"] as? String phoneNumber = fromDict["phone_number"] as? String phoneNumberVerified = fromDict["phone_number_verified"] as? Bool updatedAt = fromDict["updated_at"] as? Int kind = fromDict["sub"] as? String hd = fromDict["hd"] as? String } } /// Facebook specific claims. open class FacebookOpenIdClaim: OpenIdClaim { override init(fromDict: [String: AnyObject]) { super.init(fromDict: fromDict) givenName = fromDict["first_name"] as? String familyName = fromDict["last_name"] as? String zoneinfo = fromDict["timezone"] as? String } }
apache-2.0
69be5fbca4f43965bfe13a84017d0529
49.327103
177
0.689322
4.193925
false
false
false
false
luosheng/OpenSim
OpenSim/AppInfoView.swift
1
2174
// // AppInfoView.swift // OpenSim // // Created by Luo Sheng on 07/05/2017. // Copyright © 2017 Luo Sheng. All rights reserved. // import Cocoa final class AppInfoView: NSView { var application: Application var textField: NSTextField! static let width: CGFloat = 250 static let edgeInsets = NSEdgeInsets(top: 0, left: 20, bottom: 5, right: 0) static let leftMargin: CGFloat = 20 init(application: Application) { self.application = application super.init(frame: NSRect.zero) setupViews() update() let size = textField.sizeThatFits(NSSize(width: CGFloat.infinity, height: CGFloat.infinity)) textField.frame = NSRect(x: AppInfoView.leftMargin, y: AppInfoView.edgeInsets.bottom, width: AppInfoView.width - AppInfoView.edgeInsets.left, height: size.height) frame = NSRect(x: 0, y: 0, width: AppInfoView.width, height: size.height + AppInfoView.edgeInsets.bottom) application.calcSize { [weak self] _ in DispatchQueue.main.async { self?.update() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { textField = NSTextField(frame: NSRect(x: 20, y: 0, width: 230, height: 100)) textField.isBezeled = false textField.drawsBackground = false textField.isEditable = false textField.isSelectable = false textField.cell?.wraps = false textField.textColor = NSColor.disabledControlTextColor addSubview(textField) } private func update() { var sizeDescription = "---" if let size = application.size { sizeDescription = ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file) } let string = "\(application.bundleID)\n" + "\(UIConstants.strings.appInfoVersion): \(application.bundleVersion) (\(application.bundleShortVersion))\n" + "\(UIConstants.strings.appInfoSize): \(sizeDescription)" textField.stringValue = string } }
mit
5139176c2e9b668551c1ce58585ebc72
32.953125
170
0.630005
4.693305
false
false
false
false
yume190/JSONDecodeKit
Sources/JSONDecodeKit/JSON/JSON+Dictionary.swift
1
1185
// // JSON+Dictionary.swift // JSONDecodeKit // // Created by Yume on 2017/11/20. // Copyright © 2017年 Yume. All rights reserved. // import Foundation extension JSON { public func dictionary<Key, Value: JSONDecodable>() -> [Key:Value] { return toDictionary(json: self) { (any: Any) -> Value? in try? Value.decode(json: JSON(any: any)) } } public func dictionary<Key, Value: RawRepresentable>() -> [Key:Value] where Value.RawValue: PrimitiveType { return toDictionary(json: self) { (any: Any) -> Value? in try? Value.decode(any: any) } } } private func toDictionary<Key,Value>(json: JSON, valueTransform:(Any) -> Value?) -> [Key:Value] { guard let dic = json.data as? NSDictionary else { return [Key:Value]() } return dic.reduce([Key:Value]()) { (result:[Key:Value], set:(key: Any, value: Any)) -> [Key:Value] in guard let key = set.key as? Key, let value = valueTransform(set.value) else { return result } var result = result result[key] = value return result } }
mit
7c3cfc91689c0d6c49097b9575a1fe3f
27.142857
111
0.566836
3.850163
false
false
false
false
ustwo/formvalidator-swift
Tests/Unit Tests/Validators/PasswordStrengthValidatorTests.swift
1
1137
// // PasswordStrengthValidatorTests.swift // FormValidatorSwift // // Created by Aaron McTavish on 14/01/2016. // Copyright © 2016 ustwo. All rights reserved. // import XCTest @testable import FormValidatorSwift final class PasswordStrengthValidatorTests: XCTestCase { // MARK: - Properties let validator = PasswordStrengthValidator(configuration: ConfigurationSeeds.PasswordStrengthSeeds.veryStrong) // MARK: - Test Success func testPasswordStrengthValidator_Success() { // Given let testInput = "F1@b9a_c12983y" let expectedResult: [Condition]? = nil // Test AssertValidator(validator, testInput: testInput, expectedResult: expectedResult) } // MARK: - Test Failure func testPasswordStrengthValidator_Failure() { // Given let testInput = "Foo" let expectedResult: [Condition]? = validator.conditions // Test AssertValidator(validator, testInput: testInput, expectedResult: expectedResult) } }
mit
7eff1b320c238a2dda96519b3f5689af
24.244444
115
0.623239
5.163636
false
true
false
false
nerdyc/Squeal
Sources/Helpers/UpdateHelpers.swift
1
6353
import Foundation public extension Database { /// Prepares an `UPDATE` statement. /// /// - Parameters: /// - tableName: The table to update. /// - setExpr: A SQL expression to update rows (e.g. what follows the `SET` keyword) /// - whereExpr: A SQL `WHERE` expression that selects which rows are updated (e.g. what follows the `WHERE` keyword) /// - parameters: Parameters to bind to the statement. /// - Returns: The prepared `Statement`. /// - Throws: /// An NSError with the sqlite error code and message. public func prepareUpdate(_ tableName: String, setExpr:String, whereExpr:String? = nil, parameters: [Bindable?] = []) throws -> Statement { var fragments = ["UPDATE", escapeIdentifier(tableName), "SET", setExpr] if whereExpr != nil { fragments.append("WHERE") fragments.append(whereExpr!) } let statement = try prepareStatement(fragments.joined(separator: " ")) if parameters.count > 0 { try statement.bind(parameters) } return statement } /// Updates table rows using a dynamic SQL expression. This is useful when you would like to use SQL functions or /// operators to update the values of particular rows. /// /// - Parameters: /// - tableName: The table to update. /// - setExpr: A SQL expression to update rows (e.g. what follows the `SET` keyword) /// - whereExpr: A SQL `WHERE` expression that selects which rows are updated (e.g. what follows the `WHERE` keyword) /// - parameters: Parameters to bind to the statement. /// - Returns: The number of rows updated. /// - Throws: /// An NSError with the sqlite error code and message. @discardableResult public func update(_ tableName: String, setExpr:String, whereExpr:String? = nil, parameters: [Bindable?] = []) throws -> Int { let statement = try prepareUpdate(tableName, setExpr:setExpr, whereExpr:whereExpr, parameters:parameters) try statement.execute() return self.numberOfChangedRows } /// Prepares an `UPDATE` statement to update the given columns to specific values. The returned `Statement` will /// have one parameter for each column, in the same order. /// /// - Parameters: /// - tableName: The name of the table to update. /// - columns: The columns to update. /// - whereExpr: A SQL expression to select which rows to update. If `nil`, all rows are updated. /// - Returns: The prepared UPDATE statement. /// - Throws: /// An NSError with the sqlite error code and message. public func prepareUpdate(_ tableName: String, columns: [String], whereExpr: String? = nil) throws -> Statement { let columnsToSet = columns.map { escapeIdentifier($0) + " = ?" }.joined(separator: ", ") return try prepareUpdate(tableName, setExpr:columnsToSet, whereExpr:whereExpr) } /// Updates table rows with the given values. This is a helper for executing an /// `UPDATE ... SET ... WHERE` statement when all updated values are provided. /// /// - Parameters: /// - tableName: The name of the table to update. /// - columns: The columns to update. /// - values: The column values. /// - whereExpr: A WHERE clause to select which rows to update. If nil, all rows are updated. /// - parameters: Parameters to the WHERE clause. /// - Returns: The number of rows updated. /// - Throws: /// An NSError with the sqlite error code and message. @discardableResult public func update(_ tableName: String, columns: [String], values: [Bindable?], whereExpr: String? = nil, parameters: [Bindable?] = []) throws -> Int { let statement = try prepareUpdate(tableName, columns: columns, whereExpr: whereExpr) try statement.bind(values + parameters) try statement.execute() return self.numberOfChangedRows } /// Updates table rows with the given values. This is a helper for executing an `UPDATE ... SET ... WHERE` statement /// when all updated values are provided. /// /// - Parameters: /// - tableName: The name of the table to update. /// - set: A dictionary of column names and values to set. /// - whereExpr: A WHERE clause to select which rows to update. If nil, all rows are updated. /// - parameters: Parameters to the WHERE clause. /// - Returns: The number of rows updated. /// - Throws: /// An NSError with the sqlite error code and message. @discardableResult public func update(_ tableName: String, set: [String:Bindable?], whereExpr: String? = nil, parameters: [Bindable?] = []) throws -> Int { var columns = [String]() var values = [Bindable?]() for (columnName, value) in set { columns.append(columnName) values.append(value) } return try update(tableName, columns:columns, values:values, whereExpr:whereExpr, parameters:parameters) } /// Updates table rows given a set of row IDs. /// /// - Parameters: /// - tableName: The name of the table to update. /// - rowIds: The IDs of rows to update. /// - values: A dictionary of column names and values to set on the rows. /// - Returns: The number of rows updated. /// - Throws: /// An NSError with the sqlite error code and message. @discardableResult public func update(_ tableName: String, rowIds: [RowId], values: [String:Bindable?]) throws -> Int { if rowIds.count == 0 { return 0 } let whereExpr = "_ROWID_ IN (" + rowIds.map { String($0) }.joined(separator: ",") + ")" return try update(tableName, set:values, whereExpr:whereExpr) } }
mit
0cdfbcaf17e81d2a5f5f1283ff7c1468
43.118056
143
0.579884
4.776692
false
false
false
false
nferocious76/NFImageView
Example/Pods/Alamofire/Source/URLEncodedFormEncoder.swift
1
40883
// // URLEncodedFormEncoder.swift // // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// An object that encodes instances into URL-encoded query strings. /// /// There is no published specification for how to encode collection types. By default, the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. /// /// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` /// strategy is used, which formats dates from their structure. /// /// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (`%20`), /// while older encodings may expect spaces to be replaced with `+`. /// /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. public final class URLEncodedFormEncoder { /// Encoding to use for `Array` values. public enum ArrayEncoding { /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. case brackets /// No brackets are appended to the key and the key is encoded as is. case noBrackets /// Encodes the key according to the encoding. /// /// - Parameter key: The `key` to encode. /// - Returns: The encoded key. func encode(_ key: String) -> String { switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Encoding to use for `Bool` values. public enum BoolEncoding { /// Encodes `true` as `1`, `false` as `0`. case numeric /// Encodes `true` as "true", `false` as "false". This is the default encoding. case literal /// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// /// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } /// Encoding to use for `Data` values. public enum DataEncoding { /// Defers encoding to the `Data` type. case deferredToData /// Encodes `Data` as a Base64-encoded string. This is the default encoding. case base64 /// Encode the `Data` as a custom value encoded by the given closure. case custom((Data) throws -> String) /// Encodes `Data` according to the encoding. /// /// - Parameter data: The `Data` to encode. /// /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its /// `Encodable` implementation. func encode(_ data: Data) throws -> String? { switch self { case .deferredToData: return nil case .base64: return data.base64EncodedString() case let .custom(encoding): return try encoding(data) } } } /// Encoding to use for `Date` values. public enum DateEncoding { /// ISO8601 and RFC3339 formatter. private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() /// Defers encoding to the `Date` type. This is the default encoding. case deferredToDate /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. case secondsSince1970 /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. case millisecondsSince1970 /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. case iso8601 /// Encodes `Date`s using the given `DateFormatter`. case formatted(DateFormatter) /// Encodes `Date`s using the given closure. case custom((Date) throws -> String) /// Encodes the date according to the encoding. /// /// - Parameter date: The `Date` to encode. /// /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its /// `Encodable` implementation. func encode(_ date: Date) throws -> String? { switch self { case .deferredToDate: return nil case .secondsSince1970: return String(date.timeIntervalSince1970) case .millisecondsSince1970: return String(date.timeIntervalSince1970 * 1000.0) case .iso8601: return DateEncoding.iso8601Formatter.string(from: date) case let .formatted(formatter): return formatter.string(from: date) case let .custom(closure): return try closure(date) } } } /// Encoding to use for keys. /// /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). public enum KeyEncoding { /// Use the keys specified by each type. This is the default encoding. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. /// /// Capital characters are determined by testing membership in /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` /// (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as /// the ICU "root" locale. This means the result is consistent /// regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Same as convertToSnakeCase, but using `-` instead of `_`. /// For example `oneTwoThree` becomes `one-two-three`. case convertToKebabCase /// Capitalize the first letter only. /// For example `oneTwoThree` becomes `OneTwoThree`. case capitalized /// Uppercase all letters. /// For example `oneTwoThree` becomes `ONETWOTHREE`. case uppercased /// Lowercase all letters. /// For example `oneTwoThree` becomes `onetwothree`. case lowercased /// A custom encoding using the provided closure. case custom((String) -> String) func encode(_ key: String) -> String { switch self { case .useDefaultKeys: return key case .convertToSnakeCase: return convertToSnakeCase(key) case .convertToKebabCase: return convertToKebabCase(key) case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) case .uppercased: return key.uppercased() case .lowercased: return key.lowercased() case let .custom(encoding): return encoding(key) } } private func convertToSnakeCase(_ key: String) -> String { convert(key, usingSeparator: "_") } private func convertToKebabCase(_ key: String) -> String { convert(key, usingSeparator: "-") } private func convert(_ key: String, usingSeparator separator: String) -> String { guard !key.isEmpty else { return key } var words: [Range<String.Index>] = [] // The general idea of this algorithm is to split words on // transition from lower to upper case, then on transition of >1 // upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = key.startIndex var searchRange = key.index(after: wordStart)..<key.endIndex // Find next uppercase character while let upperCaseRange = key.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = key.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? // If so, we encountered a group of uppercase letters that we // should treat as its own word let nextCharacterAfterCapital = key.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map { range in key[range].lowercased() }.joined(separator: separator) return result } } /// Encoding to use for spaces. public enum SpaceEncoding { /// Encodes spaces according to normal percent escaping rules (%20). case percentEscaped /// Encodes spaces as `+`, case plusReplaced /// Encodes the string according to the encoding. /// /// - Parameter string: The `String` to encode. /// /// - Returns: The encoded `String`. func encode(_ string: String) -> String { switch self { case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") } } } /// `URLEncodedFormEncoder` error. public enum Error: Swift.Error { /// An invalid root object was created by the encoder. Only keyed values are valid. case invalidRootObject(String) var localizedDescription: String { switch self { case let .invalidRootObject(object): return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." } } } /// Whether or not to sort the encoded key value pairs. /// /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. public let alphabetizeKeyValuePairs: Bool /// The `ArrayEncoding` to use. public let arrayEncoding: ArrayEncoding /// The `BoolEncoding` to use. public let boolEncoding: BoolEncoding /// THe `DataEncoding` to use. public let dataEncoding: DataEncoding /// The `DateEncoding` to use. public let dateEncoding: DateEncoding /// The `KeyEncoding` to use. public let keyEncoding: KeyEncoding /// The `SpaceEncoding` to use. public let spaceEncoding: SpaceEncoding /// The `CharacterSet` of allowed (non-escaped) characters. public var allowedCharacters: CharacterSet /// Creates an instance from the supplied parameters. /// /// - Parameters: /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by /// default. public init(alphabetizeKeyValuePairs: Bool = true, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric, dataEncoding: DataEncoding = .base64, dateEncoding: DateEncoding = .deferredToDate, keyEncoding: KeyEncoding = .useDefaultKeys, spaceEncoding: SpaceEncoding = .percentEscaped, allowedCharacters: CharacterSet = .afURLQueryAllowed) { self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs self.arrayEncoding = arrayEncoding self.boolEncoding = boolEncoding self.dataEncoding = dataEncoding self.dateEncoding = dateEncoding self.keyEncoding = keyEncoding self.spaceEncoding = spaceEncoding self.allowedCharacters = allowedCharacters } func encode(_ value: Encodable) throws -> URLEncodedFormComponent { let context = URLEncodedFormContext(.object([])) let encoder = _URLEncodedFormEncoder(context: context, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) try value.encode(to: encoder) return context.component } /// Encodes the `value` as a URL form encoded `String`. /// /// - Parameter value: The `Encodable` value.` /// /// - Returns: The encoded `String`. /// - Throws: An `Error` or `EncodingError` instance if encoding fails. public func encode(_ value: Encodable) throws -> String { let component: URLEncodedFormComponent = try encode(value) guard case let .object(object) = component else { throw Error.invalidRootObject("\(component)") } let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, arrayEncoding: arrayEncoding, keyEncoding: keyEncoding, spaceEncoding: spaceEncoding, allowedCharacters: allowedCharacters) let query = serializer.serialize(object) return query } /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the /// `.utf8` data. /// /// - Parameter value: The `Encodable` value. /// /// - Returns: The encoded `Data`. /// /// - Throws: An `Error` or `EncodingError` instance if encoding fails. public func encode(_ value: Encodable) throws -> Data { let string: String = try encode(value) return Data(string.utf8) } } final class _URLEncodedFormEncoder { var codingPath: [CodingKey] // Returns an empty dictionary, as this encoder doesn't support userInfo. var userInfo: [CodingUserInfoKey: Any] { [:] } let context: URLEncodedFormContext private let boolEncoding: URLEncodedFormEncoder.BoolEncoding private let dataEncoding: URLEncodedFormEncoder.DataEncoding private let dateEncoding: URLEncodedFormEncoder.DateEncoding init(context: URLEncodedFormContext, codingPath: [CodingKey] = [], boolEncoding: URLEncodedFormEncoder.BoolEncoding, dataEncoding: URLEncodedFormEncoder.DataEncoding, dateEncoding: URLEncodedFormEncoder.DateEncoding) { self.context = context self.codingPath = codingPath self.boolEncoding = boolEncoding self.dataEncoding = dataEncoding self.dateEncoding = dateEncoding } } extension _URLEncodedFormEncoder: Encoder { func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { _URLEncodedFormEncoder.UnkeyedContainer(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } func singleValueContainer() -> SingleValueEncodingContainer { _URLEncodedFormEncoder.SingleValueContainer(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } } final class URLEncodedFormContext { var component: URLEncodedFormComponent init(_ component: URLEncodedFormComponent) { self.component = component } } enum URLEncodedFormComponent { typealias Object = [(key: String, value: URLEncodedFormComponent)] case string(String) case array([URLEncodedFormComponent]) case object(Object) /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. var array: [URLEncodedFormComponent]? { switch self { case let .array(array): return array default: return nil } } /// Converts self to an `Object` or returns `nil` if not convertible. var object: Object? { switch self { case let .object(object): return object default: return nil } } /// Sets self to the supplied value at a given path. /// /// data.set(to: "hello", at: ["path", "to", "value"]) /// /// - parameters: /// - value: Value of `Self` to set at the supplied path. /// - path: `CodingKey` path to update with the supplied value. public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { set(&self, to: value, at: path) } /// Recursive backing method to `set(to:at:)`. private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { guard path.count >= 1 else { context = value return } let end = path[0] var child: URLEncodedFormComponent switch path.count { case 1: child = value case 2...: if let index = end.intValue { let array = context.array ?? [] if array.count > index { child = array[index] } else { child = .array([]) } set(&child, to: value, at: Array(path[1...])) } else { child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) set(&child, to: value, at: Array(path[1...])) } default: fatalError("Unreachable") } if let index = end.intValue { if var array = context.array { if array.count > index { array[index] = child } else { array.append(child) } context = .array(array) } else { context = .array([child]) } } else { if var object = context.object { if let index = object.firstIndex(where: { $0.key == end.stringValue }) { object[index] = (key: end.stringValue, value: child) } else { object.append((key: end.stringValue, value: child)) } context = .object(object) } else { context = .object([(key: end.stringValue, value: child)]) } } } } struct AnyCodingKey: CodingKey, Hashable { let stringValue: String let intValue: Int? init?(stringValue: String) { self.stringValue = stringValue intValue = nil } init?(intValue: Int) { stringValue = "\(intValue)" self.intValue = intValue } init<Key>(_ base: Key) where Key: CodingKey { if let intValue = base.intValue { self.init(intValue: intValue)! } else { self.init(stringValue: base.stringValue)! } } } extension _URLEncodedFormEncoder { final class KeyedContainer<Key> where Key: CodingKey { var codingPath: [CodingKey] private let context: URLEncodedFormContext private let boolEncoding: URLEncodedFormEncoder.BoolEncoding private let dataEncoding: URLEncodedFormEncoder.DataEncoding private let dateEncoding: URLEncodedFormEncoder.DateEncoding init(context: URLEncodedFormContext, codingPath: [CodingKey], boolEncoding: URLEncodedFormEncoder.BoolEncoding, dataEncoding: URLEncodedFormEncoder.DataEncoding, dateEncoding: URLEncodedFormEncoder.DateEncoding) { self.context = context self.codingPath = codingPath self.boolEncoding = boolEncoding self.dataEncoding = dataEncoding self.dateEncoding = dateEncoding } private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { codingPath + [key] } } } extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { func encodeNil(forKey key: Key) throws { let context = EncodingError.Context(codingPath: codingPath, debugDescription: "URLEncodedFormEncoder cannot encode nil values.") throw EncodingError.invalidValue("\(key): nil", context) } func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { var container = nestedSingleValueEncoder(for: key) try container.encode(value) } func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, codingPath: nestedCodingPath(for: key), boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) return container } func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, codingPath: nestedCodingPath(for: key), boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) return container } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context, codingPath: nestedCodingPath(for: key), boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) return KeyedEncodingContainer(container) } func superEncoder() -> Encoder { _URLEncodedFormEncoder(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } func superEncoder(forKey key: Key) -> Encoder { _URLEncodedFormEncoder(context: context, codingPath: nestedCodingPath(for: key), boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } } extension _URLEncodedFormEncoder { final class SingleValueContainer { var codingPath: [CodingKey] private var canEncodeNewValue = true private let context: URLEncodedFormContext private let boolEncoding: URLEncodedFormEncoder.BoolEncoding private let dataEncoding: URLEncodedFormEncoder.DataEncoding private let dateEncoding: URLEncodedFormEncoder.DateEncoding init(context: URLEncodedFormContext, codingPath: [CodingKey], boolEncoding: URLEncodedFormEncoder.BoolEncoding, dataEncoding: URLEncodedFormEncoder.DataEncoding, dateEncoding: URLEncodedFormEncoder.DateEncoding) { self.context = context self.codingPath = codingPath self.boolEncoding = boolEncoding self.dataEncoding = dataEncoding self.dateEncoding = dateEncoding } private func checkCanEncode(value: Any?) throws { guard canEncodeNewValue else { let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Attempt to encode value through single value container when previously value already encoded.") throw EncodingError.invalidValue(value as Any, context) } } } } extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { func encodeNil() throws { try checkCanEncode(value: nil) defer { canEncodeNewValue = false } let context = EncodingError.Context(codingPath: codingPath, debugDescription: "URLEncodedFormEncoder cannot encode nil values.") throw EncodingError.invalidValue("nil", context) } func encode(_ value: Bool) throws { try encode(value, as: String(boolEncoding.encode(value))) } func encode(_ value: String) throws { try encode(value, as: value) } func encode(_ value: Double) throws { try encode(value, as: String(value)) } func encode(_ value: Float) throws { try encode(value, as: String(value)) } func encode(_ value: Int) throws { try encode(value, as: String(value)) } func encode(_ value: Int8) throws { try encode(value, as: String(value)) } func encode(_ value: Int16) throws { try encode(value, as: String(value)) } func encode(_ value: Int32) throws { try encode(value, as: String(value)) } func encode(_ value: Int64) throws { try encode(value, as: String(value)) } func encode(_ value: UInt) throws { try encode(value, as: String(value)) } func encode(_ value: UInt8) throws { try encode(value, as: String(value)) } func encode(_ value: UInt16) throws { try encode(value, as: String(value)) } func encode(_ value: UInt32) throws { try encode(value, as: String(value)) } func encode(_ value: UInt64) throws { try encode(value, as: String(value)) } private func encode<T>(_ value: T, as string: String) throws where T: Encodable { try checkCanEncode(value: value) defer { canEncodeNewValue = false } context.component.set(to: .string(string), at: codingPath) } func encode<T>(_ value: T) throws where T: Encodable { switch value { case let date as Date: guard let string = try dateEncoding.encode(date) else { try attemptToEncode(value) return } try encode(value, as: string) case let data as Data: guard let string = try dataEncoding.encode(data) else { try attemptToEncode(value) return } try encode(value, as: string) default: try attemptToEncode(value) } } private func attemptToEncode<T>(_ value: T) throws where T: Encodable { try checkCanEncode(value: value) defer { canEncodeNewValue = false } let encoder = _URLEncodedFormEncoder(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) try value.encode(to: encoder) } } extension _URLEncodedFormEncoder { final class UnkeyedContainer { var codingPath: [CodingKey] var count = 0 var nestedCodingPath: [CodingKey] { codingPath + [AnyCodingKey(intValue: count)!] } private let context: URLEncodedFormContext private let boolEncoding: URLEncodedFormEncoder.BoolEncoding private let dataEncoding: URLEncodedFormEncoder.DataEncoding private let dateEncoding: URLEncodedFormEncoder.DateEncoding init(context: URLEncodedFormContext, codingPath: [CodingKey], boolEncoding: URLEncodedFormEncoder.BoolEncoding, dataEncoding: URLEncodedFormEncoder.DataEncoding, dateEncoding: URLEncodedFormEncoder.DateEncoding) { self.context = context self.codingPath = codingPath self.boolEncoding = boolEncoding self.dataEncoding = dataEncoding self.dateEncoding = dateEncoding } } } extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { func encodeNil() throws { let context = EncodingError.Context(codingPath: codingPath, debugDescription: "URLEncodedFormEncoder cannot encode nil values.") throw EncodingError.invalidValue("nil", context) } func encode<T>(_ value: T) throws where T: Encodable { var container = nestedSingleValueContainer() try container.encode(value) } func nestedSingleValueContainer() -> SingleValueEncodingContainer { defer { count += 1 } return _URLEncodedFormEncoder.SingleValueContainer(context: context, codingPath: nestedCodingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { defer { count += 1 } let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context, codingPath: nestedCodingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) return KeyedEncodingContainer(container) } func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { defer { count += 1 } return _URLEncodedFormEncoder.UnkeyedContainer(context: context, codingPath: nestedCodingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } func superEncoder() -> Encoder { defer { count += 1 } return _URLEncodedFormEncoder(context: context, codingPath: codingPath, boolEncoding: boolEncoding, dataEncoding: dataEncoding, dateEncoding: dateEncoding) } } final class URLEncodedFormSerializer { private let alphabetizeKeyValuePairs: Bool private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding private let keyEncoding: URLEncodedFormEncoder.KeyEncoding private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding private let allowedCharacters: CharacterSet init(alphabetizeKeyValuePairs: Bool, arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, keyEncoding: URLEncodedFormEncoder.KeyEncoding, spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, allowedCharacters: CharacterSet) { self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs self.arrayEncoding = arrayEncoding self.keyEncoding = keyEncoding self.spaceEncoding = spaceEncoding self.allowedCharacters = allowedCharacters } func serialize(_ object: URLEncodedFormComponent.Object) -> String { var output: [String] = [] for (key, component) in object { let value = serialize(component, forKey: key) output.append(value) } output = alphabetizeKeyValuePairs ? output.sorted() : output return output.joinedWithAmpersands() } func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { switch component { case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" case let .array(array): return serialize(array, forKey: key) case let .object(object): return serialize(object, forKey: key) } } func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { var segments: [String] = object.map { subKey, value in let keyPath = "[\(subKey)]" return serialize(value, forKey: key + keyPath) } segments = alphabetizeKeyValuePairs ? segments.sorted() : segments return segments.joinedWithAmpersands() } func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { var segments: [String] = array.map { component in let keyPath = arrayEncoding.encode(key) return serialize(component, forKey: keyPath) } segments = alphabetizeKeyValuePairs ? segments.sorted() : segments return segments.joinedWithAmpersands() } func escape(_ query: String) -> String { var allowedCharactersWithSpace = allowedCharacters allowedCharactersWithSpace.insert(charactersIn: " ") let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) return spaceEncodedQuery } } extension Array where Element == String { func joinedWithAmpersands() -> String { joined(separator: "&") } } public extension CharacterSet { /// Creates a CharacterSet from RFC 3986 allowed characters. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. static let afURLQueryAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) }() }
mit
74b69ae039bde97402d236c1a51d7857
41.017472
206
0.586307
5.649164
false
false
false
false
nate-parrott/SwipeAwayTableViewController
SwipeAwayTableViewController.swift
2
5034
// // SwipeAwayTableViewController.swift // ScantronKit // // Created by Nate Parrott on 9/30/14. // Copyright (c) 2014 Nate Parrott. All rights reserved. // import UIKit class SwipeAwayTableViewController: UITableViewController, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var contentBackdrop: UIView! override func viewDidLoad() { super.viewDidLoad() scrollViewDidScroll(tableView) tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, 1, topMargin())) let tapRec = UITapGestureRecognizer(target: self, action: "dismiss") tableView.tableHeaderView!.addGestureRecognizer(tapRec) contentBackdrop = UIView() contentBackdrop.backgroundColor = UIColor.whiteColor() tableView.insertSubview(contentBackdrop, atIndex: 0) tableView.backgroundColor = UIColor.clearColor() tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, topMargin(), 0, 0) } func topMargin() -> CGFloat { return 60 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.setNeedsLayout() } // MARK: Transitioning func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.7 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let isDismissal = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) == self let duration = transitionDuration(transitionContext) let containerView = transitionContext.containerView() let dimmingView = UIView(frame: containerView.bounds) if isDismissal { containerView.insertSubview(dimmingView, belowSubview: self.view) dimmingView.backgroundColor = tableView.backgroundColor tableView.backgroundColor = UIColor.clearColor() UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: -dismissVelocity / containerView.bounds.size.height, options: nil, animations: { () -> Void in self.view.transform = CGAffineTransformMakeTranslation(0, containerView.bounds.size.height) dimmingView.alpha = 0 }, completion: { (_) -> Void in self.view.removeFromSuperview() dimmingView.removeFromSuperview() transitionContext.completeTransition(true) }) } else { containerView.addSubview(dimmingView) dimmingView.backgroundColor = UIColor.clearColor() containerView.addSubview(self.view) self.view.frame = transitionContext.finalFrameForViewController(self) self.view.transform = CGAffineTransformMakeTranslation(0, containerView.bounds.size.height) tableView.backgroundColor = UIColor.clearColor() UIView.animateWithDuration(duration, animations: { () -> Void in self.view.transform = CGAffineTransformIdentity dimmingView.backgroundColor = UIColor(white: 0.1, alpha: 0.5) }, completion: { (_) -> Void in dimmingView.removeFromSuperview() self.scrollViewDidScroll(self.tableView) transitionContext.completeTransition(true) }) } } // MARK: Interaction var isDismissing = false @IBAction func dismiss() { isDismissing = true dismissViewControllerAnimated(true, completion: nil) } var dismissVelocity: CGFloat = 1 override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView.contentOffset.y < -10 && velocity.y < -1 { dismissVelocity = velocity.y dismiss() } } override func scrollViewDidScroll(scrollView: UIScrollView) { if !isDismissing { let scrollUpProportion: CGFloat = -scrollView.contentOffset.y / (view.bounds.size.height - topMargin()) let fadeOut: CGFloat = min(1.0, max(0.0, scrollUpProportion)) tableView.backgroundColor = UIColor(white: 0.1, alpha: (1 - fadeOut) * 0.5) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() contentBackdrop.frame = CGRectMake(0, topMargin(), view.bounds.size.width, tableView.contentSize.height + view.bounds.size.height) } }
mit
b71f932cbbea6efe06017c92104071b4
42.396552
217
0.673619
5.873979
false
false
false
false
sseitov/v-Chess-Swift
v-Chess/Extensions/UIFontExtension.swift
1
881
// // UIFontExtension.swift // // Created by Сергей Сейтов on 22.05.17. // Copyright © 2017 V-Channel. All rights reserved. // import UIKit func printFontNames() { for family:String in UIFont.familyNames { print("\(family)") for names:String in UIFont.fontNames(forFamilyName: family) { print("== \(names)") } } } extension UIFont { class func mainFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue", size: size)! } class func thinFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue-Thin", size: size)! } class func condensedFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue-CondensedBold", size: size)! } class func commentsFont() -> UIFont { return mainFont(15) } }
gpl-3.0
0172d151ae177a23044a24b414264804
23.111111
71
0.599078
3.945455
false
false
false
false
alessiobrozzi/firefox-ios
UITests/ViewMemoryLeakTests.swift
10
5716
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit /// This test should be disabled since getTopViewController() crashes with iOS 10 /// ------------------------------------------------------------------------------ /// Set of tests that wait for weak references to views to be cleared. Technically, this is /// non-deterministic and there are no guarantees the references will be set to nil. In practice, /// though, the references are consistently cleared, which should be good enough for testing. class ViewMemoryLeakTests: KIFTestCase, UITextFieldDelegate { fileprivate var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } override func tearDown() { do { try tester().tryFindingTappableView(withAccessibilityLabel: "home") tester().tapView(withAccessibilityLabel: "home") } catch _ { } BrowserUtils.resetToAboutHome(tester()) } /* func testAboutHomeDisposed() { // about:home is already active on startup; grab a reference to it. let browserViewController = getTopViewController() weak var aboutHomeController = getChildViewController(browserViewController, childClass: "HomePanelViewController") // Change the page to make about:home go away. tester().tapViewWithAccessibilityIdentifier("url") let url = "\(webRoot)/numberedPage.html?page=1" // Work around potential KIF bug. The nillification does not seem to propagate unless we use and explicit autorelease pool. // https://github.com/kif-framework/KIF/issues/739 autoreleasepool { tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n") } tester().waitForWebViewElementWithAccessibilityLabel("Page 1") tester().runBlock { _ in return (aboutHomeController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait } XCTAssertNil(aboutHomeController, "about:home controller disposed") } func testSearchViewControllerDisposed() { // Type the URL to make the search controller appear. tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("foobar") tester().waitForTimeInterval(0.1) // Wait to make sure that input has propagated through delegate methods let browserViewController = getTopViewController() weak var searchViewController = getChildViewController(browserViewController, childClass: "SearchViewController") XCTAssertNotNil(searchViewController, "Got search controller reference") // Submit to close about:home and the search controller. tester().enterTextIntoCurrentFirstResponder("\n") tester().runBlock { _ in return (searchViewController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait } XCTAssertNil(searchViewController, "Search controller disposed") } func testTabTrayDisposed() { // Enter the tab tray. tester().tapViewWithAccessibilityLabel("Show Tabs") tester().waitForViewWithAccessibilityLabel("Tabs Tray") weak var tabTrayController = getTopViewController() weak var tabCell = tester().waitForTappableViewWithAccessibilityLabel("home") XCTAssertNotNil(tabTrayController, "Got tab tray reference") XCTAssertNotNil(tabCell, "Got tab cell reference") // Leave the tab tray. tester().tapViewWithAccessibilityLabel("home") tester().runBlock { _ in return (tabTrayController == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait } XCTAssertNil(tabTrayController, "Tab tray controller disposed") tester().runBlock { _ in return (tabCell == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait } XCTAssertNil(tabCell, "Tab tray cell disposed") } func testWebViewDisposed() { weak var webView = tester().waitForViewWithAccessibilityLabel("Web content") XCTAssertNotNil(webView, "webView found") tester().tapViewWithAccessibilityLabel("Show Tabs") let tabsView = tester().waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))! tester().swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester().waitForTappableViewWithAccessibilityLabel("Show Tabs") tester().runBlock { _ in return (webView == nil) ? KIFTestStepResult.Success : KIFTestStepResult.Wait } XCTAssertNil(webView, "webView disposed") } private func getTopViewController() -> UIViewController { //return (UIApplication.sharedApplication().keyWindow!.rootViewController as! UINavigationController).topViewController! return UIApplication.sharedApplication().keyWindow!.rootViewController! } private func getChildViewController(parent: UIViewController, childClass: String) -> UIViewController { let childControllers = parent.childViewControllers.filter { child in let description = NSString(string: child.description) return description.containsString(childClass) } XCTAssertEqual(childControllers.count, 0, "Found 1 child controller of type: \(childClass)") return childControllers.first! } */ }
mpl-2.0
715e2fdb9f8002f0784ba0c873c0836a
45.096774
131
0.692617
5.929461
false
true
false
false
adow/CardsAnimationDemo
CardsAnimationDemo/ViewController.swift
1
5809
// // ViewController.swift // TestCards // // Created by 秦 道平 on 15/10/29. // Copyright © 2015年 秦 道平. All rights reserved. // import UIKit class ViewController: UIViewController { var collectionView : UICollectionView! private let cellIdentifier = "cell" var start_offset_y : CGFloat = 0.0 /// 轮转中的照片列表 var carouselImages:[UIImage] = [] /// 真正的照片列表 var images : [UIImage] = [] { didSet{ carouselImages.removeAll() carouselImages = images + images + images } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.whiteColor() /// self.prepageImages() /// collectionView self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: CardsCollectionViewLayout()) self.collectionView.showsVerticalScrollIndicator = true self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(collectionView) self.collectionView.registerClass(CardsCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier) self.collectionView.dataSource = self self.collectionView.delegate = self let layout_collectionView = ["collectionView":self.collectionView] let collectionView_constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(-16.0)-[collectionView]-(-16.0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: layout_collectionView) let collectionView_constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(-16.0)-[collectionView]-(-16.0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: layout_collectionView) self.view.addConstraints(collectionView_constraintsH) self.view.addConstraints(collectionView_constraintsV) /// frameView // let frameView = UIView() // frameView.translatesAutoresizingMaskIntoConstraints = false // self.view.addSubview(frameView) // frameView.backgroundColor = UIColor(white: 1.0, alpha: 0.3) // let layout_frameView = ["frameView":frameView,"superView":self.view] // let frameView_constraintsX = NSLayoutConstraint.constraintsWithVisualFormat("H:[frameView(300.)]-(<=0)-[superView]", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: layout_frameView) // let frameView_constraintsY = NSLayoutConstraint.constraintsWithVisualFormat("V:[frameView(200.0)]-(<=0)-[superView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: layout_frameView) // self.view.addConstraints(frameView_constraintsX) // self.view.addConstraints(frameView_constraintsY) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.collectionView.layoutIfNeeded() /// 在开始的时候就滚动到中间一组 let max_offset_y = self.collectionView.contentSize.height - self.collectionView.bounds.height // self.start_offset_y = floor(max_offset_y / 2.0 / 30.0) * 30.0 + 30.0 * CGFloat(self.images.count) self.start_offset_y = floor(max_offset_y / 2.0 / 30.0) * 30.0 - 30.0 * CGFloat(self.images.count) NSLog("start_offset_y:%f", start_offset_y) self.collectionView.setContentOffset(CGPointMake(0.0, start_offset_y), animated: false) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } } extension ViewController { /// 准备轮转的图片 func prepageImages(){ var images : [UIImage] = [] for a in 0..<11 { let i = UIImage(named: "\(a)")! images.append(i) } self.images = images } } extension ViewController:UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // return 11 return self.carouselImages.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CardsCollectionViewCell // let image = UIImage(named: "\(indexPath.row)") // cell.label.text = "\(indexPath.row)" let image = self.carouselImages[indexPath.row] cell.contentImageView.image = image return cell } } extension ViewController:UIScrollViewDelegate { /// 滚动的时候判断边界距离进行跳转 func scrollViewDidScroll(scrollView: UIScrollView) { let translate = scrollView.contentOffset.y - self.start_offset_y NSLog("scroll:%f, %f", scrollView.contentOffset.y, translate) // if translate >= 30.0 { // scrollView.setContentOffset(CGPointMake(0.0, self.start_offset_y), animated: false) // } let target_scroll_y : CGFloat = 30.0 * CGFloat(self.images.count) if abs(translate) >= target_scroll_y { scrollView.setContentOffset(CGPointMake(0.0, self.start_offset_y), animated: false) } } }
mit
f4cb1143322280c2d9e51bc159bcf5a9
45.655738
219
0.686753
4.692498
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/Wallpapers/Legacy/LegacyWallpaperManager.swift
2
4417
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import UIKit import Shared struct LegacyWallpaperManager { // MARK: - Variables private let userDefaults: UserDefaults private let dataManager: LegacyWallpaperDataManager private let storageManager: LegacyWallpaperStorageUtility var numberOfWallpapers: Int { return dataManager.availableWallpapers.count } var currentWallpaperImage: UIImage? { return storageManager.getCurrentWallpaperImage() } var currentWallpaper: LegacyWallpaper { guard let currentWallpaper = storageManager.getCurrentWallpaperObject() else { // Returning the default wallpaper if nothing else is currently set, // as default will always exist. The reason this is returned is this manner // is that, on fresh app installation, no wallpaper will be set. Thus, // if this variable is accessed, it would return nil, when a wallpaper // actually be required. return dataManager.availableWallpapers[0] } return currentWallpaper } var currentlySelectedWallpaperIndex: Int? { // If no wallpaper was ever set, then we must be at index 0 guard let currentWallpaper = storageManager.getCurrentWallpaperObject() else { return 0 } for (index, wallpaper) in dataManager.availableWallpapers.enumerated() { if wallpaper == currentWallpaper { return index } } return nil } /// Returns the user's preference for whether or not to be able to change wallpapers /// by tapping on the logo on the homepage. /// /// Because the default value of this feature is actually `true`, we have to invert /// the actual value. Therefore, if the setting is `false`, we treat the setting as /// being turned on, as `false` is what UserDefaults returns when a bool does not /// exist for a key. var switchWallpaperFromLogoEnabled: Bool { get { return !userDefaults.bool(forKey: PrefsKeys.WallpaperManagerLogoSwitchPreference) } set { userDefaults.set(!newValue, forKey: PrefsKeys.WallpaperManagerLogoSwitchPreference) } } // MARK: - Initializer init(with userDefaults: UserDefaults = UserDefaults.standard, wallpaperDataManager: LegacyWallpaperDataManager = LegacyWallpaperDataManager(), wallpaperStorageManager: LegacyWallpaperStorageUtility = LegacyWallpaperStorageUtility() ) { self.userDefaults = userDefaults self.dataManager = wallpaperDataManager self.storageManager = wallpaperStorageManager } // MARK: - Public methods public func updateSelectedWallpaperIndex(to index: Int) { let wallpapers = dataManager.availableWallpapers guard index <= (wallpapers.count - 1) else { return } storageManager.store(dataManager.availableWallpapers[index], and: dataManager.getImageSet(at: index)) } public func cycleWallpaper() { let newIndex = calculateNextIndex(using: currentlySelectedWallpaperIndex, and: dataManager.availableWallpapers) updateSelectedWallpaperIndex(to: newIndex) } public func getImageAt(index: Int, inLandscape: Bool) -> UIImage? { let image = dataManager.getImageSet(at: index) return inLandscape ? image.landscape : image.portrait } public func getWallpaperTelemetryAt(index: Int) -> [String: String] { return dataManager.availableWallpapers[index].telemetryMetadata } public func getAccessibilityLabelForWallpaper(at index: Int) -> String { return dataManager.availableWallpapers[index].accessibilityLabel } public func runResourceVerification() { dataManager.verifyResources() } // MARK: - Private functions private func calculateNextIndex( using currentIndex: Int?, and wallpaperArray: [LegacyWallpaper] ) -> Int { guard let currentIndex = currentIndex else { return 0 } let newIndex = currentIndex + 1 let maxIndex = wallpaperArray.count - 1 if newIndex > maxIndex { return 0 } return newIndex } }
mpl-2.0
2b8c200ab67bc577ba71da029f433194
36.432203
99
0.68259
5.340992
false
false
false
false
codepgq/LearningSwift
PlayVideo/PlayVideo/ViewController.swift
1
3043
// // ViewController.swift // PlayVideo // // Created by ios on 16/9/7. // Copyright © 2016年 ios. All rights reserved. // import UIKit import AVKit import AVFoundation class ViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate ,myBtnClickCellDelegate { var tableView = UITableView() var playViewController = AVPlayerViewController() var playerView = AVPlayer() var data : Array = [video(imageNamed: "videoScreenshot01", title: "Introduce 3DS Mario", time: "Youtube - 06:32"), video(imageNamed: "videoScreenshot02", title: "Emoji Among Us", time: "Vimeo - 3:34"), video(imageNamed: "videoScreenshot03", title: "Seals Documentary", time: "Vine - 00:06"), video(imageNamed: "videoScreenshot04", title: "Adventure Time", time: "Youtube - 02:39"), video(imageNamed: "videoScreenshot05", title: "Facebook HQ", time: "Facebook - 10:20"), video(imageNamed: "videoScreenshot06", title: "Lijiang Lugu Lake", time: "Allen - 20:30")] override func viewDidLoad() { super.viewDidLoad() tableView = UITableView.init(frame: self.view.bounds, style: UITableViewStyle.Plain) tableView.delegate = self; tableView.dataSource = self; self.view.addSubview(tableView); tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "Cell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 300 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell cell.delegate = self let model = self.data[indexPath.row]; cell.initData(model.imageNamed, title: model.title, deTitle: model.time) cell.myPlayBtnClickBlock { (button) in print("我是VC") self.playVideo() } return cell; } func playVideo(){ let path = NSBundle.mainBundle().pathForResource("emoji zone", ofType: "mp4") self.playerView = AVPlayer(URL: NSURL(fileURLWithPath: path!)) self.playViewController.player = self.playerView self.presentViewController(self.playViewController, animated: true) { self.playViewController.player?.play() } } func cellPlayBtnClick(cell: TableViewCell, button: UIButton) { print("进入代理了!!!") playVideo() } }
apache-2.0
bb6c5b578ce06c066f386bff0687707a
33.712644
118
0.625828
5.041736
false
false
false
false
nodes-ios/model-generator
Frameworks/CommandLine/Option.swift
1
7009
/* * Option.swift * Copyright (c) 2014 Ben Gollmer. * * 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. */ /** * The base class for a command-line option. */ public class Option { public let shortFlag: String? public let longFlag: String? public let required: Bool public let helpMessage: String /** True if the option was set when parsing command-line arguments */ public var wasSet: Bool { return false } public var flagDescription: String { switch (shortFlag, longFlag) { case (let sf, let lf) where sf != nil && lf != nil: return "\(ShortOptionPrefix)\(sf!), \(LongOptionPrefix)\(lf!)" case (_, let lf) where lf != nil: return "\(LongOptionPrefix)\(lf!)" default: return "\(ShortOptionPrefix)\(shortFlag!)" } } fileprivate init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) { if let sf = shortFlag { assert(sf.count == 1, "Short flag must be a single character") assert(Int(sf) == nil && sf.toDouble() == nil, "Short flag cannot be a numeric value") } if let lf = longFlag { assert(Int(lf) == nil && lf.toDouble() == nil, "Long flag cannot be a numeric value") } self.shortFlag = shortFlag self.longFlag = longFlag self.helpMessage = helpMessage self.required = required } /* The optional casts in these initalizers force them to call the private initializer. Without * the casts, they recursively call themselves. */ /** Initializes a new Option that has both long and short flags. */ public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, longFlag, required, helpMessage) } /** Initializes a new Option that has only a short flag. */ public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, nil, required, helpMessage) } /** Initializes a new Option that has only a long flag. */ public convenience init(longFlag: String, required: Bool = false, helpMessage: String) { self.init(nil, longFlag as String?, required, helpMessage) } func flagMatch(flag: String) -> Bool { return flag == shortFlag || flag == longFlag } func setValue(values: [String]) -> Bool { return false } } /** * A boolean option. The presence of either the short or long flag will set the value to true; * absence of the flag(s) is equivalent to false. */ public class BoolOption: Option { private var _value: Bool = false public var value: Bool { return _value } override public var wasSet: Bool { return _value } override func setValue(values: [String]) -> Bool { _value = true return true } } /** An option that accepts a positive or negative integer value. */ public class IntOption: Option { private var _value: Int? public var value: Int? { return _value } override public var wasSet: Bool { return _value != nil } override func setValue(values: [String]) -> Bool { if values.count == 0 { return false } if let val = Int(values[0]) { _value = val return true } return false } } /** * An option that represents an integer counter. Each time the short or long flag is found * on the command-line, the counter will be incremented. */ public class CounterOption: Option { private var _value: Int = 0 public var value: Int { return _value } override public var wasSet: Bool { return _value > 0 } override func setValue(values: [String]) -> Bool { _value += 1 return true } } /** An option that accepts a positive or negative floating-point value. */ public class DoubleOption: Option { private var _value: Double? public var value: Double? { return _value } override public var wasSet: Bool { return _value != nil } override func setValue(values: [String]) -> Bool { if values.count == 0 { return false } if let val = values[0].toDouble() { _value = val return true } return false } } /** An option that accepts a string value. */ public class StringOption: Option { private var _value: String? = nil public var value: String? { return _value } override public var wasSet: Bool { return _value != nil } override func setValue(values: [String]) -> Bool { if values.count == 0 { return false } _value = values[0] return true } } /** An option that accepts one or more string values. */ public class MultiStringOption: Option { private var _value: [String]? public var value: [String]? { return _value } override public var wasSet: Bool { return _value != nil } override func setValue(values: [String]) -> Bool { if values.count == 0 { return false } _value = values return true } } /** An option that represents an enum value. */ public class EnumOption<T:RawRepresentable>: Option where T.RawValue == String { private var _value: T? public var value: T? { return _value } override public var wasSet: Bool { return _value != nil } /* Re-defining the intializers is necessary to make the Swift 2 compiler happy, as * of Xcode 7 beta 2. */ private override init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) { super.init(shortFlag, longFlag, required, helpMessage) } /** Initializes a new Option that has both long and short flags. */ public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, longFlag, required, helpMessage) } /** Initializes a new Option that has only a short flag. */ public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, nil, required, helpMessage) } /** Initializes a new Option that has only a long flag. */ public convenience init(longFlag: String, required: Bool = false, helpMessage: String) { self.init(nil, longFlag as String?, required, helpMessage) } override func setValue(values: [String]) -> Bool { if values.count == 0 { return false } if let v = T(rawValue: values[0]) { _value = v return true } return false } }
mit
6cc4bb738217f7f3c7741bdf0142ee74
24.863469
109
0.64888
4.167063
false
false
false
false
up-n-down/Up-N-Down
Git Service/CommitHandler.swift
1
1555
// // CommitHandler.swift // Up-N-Down // // Created by Thomas Paul Mann on 05/12/2016. // Copyright © 2016 Up-N-Down. All rights reserved. // import Foundation import ObjectiveGit struct CommitHandler { // MARK: - Properties let repository: GTRepository // MARK: - API func commit(message: String) throws { do { let head = try repository.headReference() let index = try repository.index() let tree = try index.writeTree() guard let parentCommit = parentCommit, let signature = GTSignature(name: "Thomas Paul Mann", email: "[email protected]", time: Date()) else { return } try repository.createCommit(with: tree, message: message, author: signature, committer: signature, parents: [parentCommit], updatingReferenceNamed: head.name) } } /// Returns the parent commit for the current head reference. private var parentCommit: GTCommit? { do { let enumerator = try GTEnumerator(repository: repository) let head = try repository.headReference() try enumerator.pushSHA(head.targetOID.sha) return enumerator.nextObject() as? GTCommit } catch _ { return nil } } }
gpl-3.0
44a9e270d3511ba4ee06841abd7136b1
25.793103
115
0.514157
5.061889
false
false
false
false
biohazardlover/ByTrain
ByTrain/ResponseSerialization+Image.swift
1
1182
import Alamofire extension DataRequest { @discardableResult func responseImage( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<UIImage>) -> Void) -> Self { let responseSerializer = DataResponseSerializer<UIImage> { (request, response, data, error) -> Result<UIImage> in guard error == nil else { return .failure(BackendError.network(error: error!)) } let dataResponseSerializer = DataRequest.dataResponseSerializer() let result = dataResponseSerializer.serializeResponse(request, response, data, nil) guard case let .success(data) = result else { return .failure(BackendError.dataSerialization(error: result.error!)) } guard let image = UIImage(data: data) else { return .failure(BackendError.imageSerialization(reason: "Image could not be serialized: \(data)")) } return .success(image) } return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) } }
mit
d1c0a48b9cff5fe32a62514767f4492e
38.4
121
0.618443
5.710145
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/Nimble-Snapshots/HaveValidSnapshot.swift
6
6695
import Foundation import FBSnapshotTestCase import UIKit import Nimble import QuartzCore import Quick @objc public protocol Snapshotable { var snapshotObject: UIView? { get } } extension UIViewController : Snapshotable { public var snapshotObject: UIView? { self.beginAppearanceTransition(true, animated: false) self.endAppearanceTransition() return view } } extension UIView : Snapshotable { public var snapshotObject: UIView? { return self } } @objc class FBSnapshotTest : NSObject { var currentExampleMetadata: ExampleMetadata? var referenceImagesDirectory: String? class var sharedInstance : FBSnapshotTest { struct Instance { static let instance: FBSnapshotTest = FBSnapshotTest() } return Instance.instance } class func setReferenceImagesDirectory(directory: String?) { sharedInstance.referenceImagesDirectory = directory } class func compareSnapshot(instance: Snapshotable, snapshot: String, record: Bool, referenceDirectory: String) -> Bool { let snapshotController: FBSnapshotTestController = FBSnapshotTestController(testName: _testFileName()) snapshotController.recordMode = record snapshotController.referenceImagesDirectory = referenceDirectory assert(snapshotController.referenceImagesDirectory != nil, "Missing value for referenceImagesDirectory - Call FBSnapshotTest.setReferenceImagesDirectory(FB_REFERENCE_IMAGE_DIR)") do { try snapshotController.compareSnapshotOfView(instance.snapshotObject, selector: Selector(snapshot), identifier: nil) } catch { return false; } return true; } } func _getDefaultReferenceDirectory(sourceFileName: String) -> String { if let globalReference = FBSnapshotTest.sharedInstance.referenceImagesDirectory { return globalReference } // Search the test file's path to find the first folder with the substring "tests" // then append "/ReferenceImages" and use that var result: NSString? let pathComponents: NSArray = (sourceFileName as NSString).pathComponents for folder in pathComponents { if (folder.lowercaseString as NSString).hasSuffix("tests") { let currentIndex = pathComponents.indexOfObject(folder) + 1 let folderPathComponents: NSArray = pathComponents.subarrayWithRange(NSMakeRange(0, currentIndex)) let folderPath = folderPathComponents.componentsJoinedByString("/") result = folderPath + "/ReferenceImages" } } assert(result != nil, "Could not infer reference image folder – You should provide a reference dir using FBSnapshotTest.setReferenceImagesDirectory(FB_REFERENCE_IMAGE_DIR)") return result! as String } func _testFileName() -> String { let name = FBSnapshotTest.sharedInstance.currentExampleMetadata!.example.callsite.file as NSString let type = ".\(name.pathExtension)" let sanitizedName = name.lastPathComponent.stringByReplacingOccurrencesOfString(type, withString: "") return sanitizedName } func _sanitizedTestName() -> String { let quickExample = FBSnapshotTest.sharedInstance.currentExampleMetadata var filename = quickExample!.example.name filename = filename.stringByReplacingOccurrencesOfString("root example group, ", withString: "") let characterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") let components: NSArray = filename.componentsSeparatedByCharactersInSet(characterSet.invertedSet) return components.componentsJoinedByString("_") } func _clearFailureMessage(failureMessage: FailureMessage) { failureMessage.actualValue = "" failureMessage.expected = "" failureMessage.postfixMessage = "" failureMessage.to = "" } func _performSnapshotTest(name: String?, actualExpression: Expression<Snapshotable>, failureMessage: FailureMessage) -> Bool { let instance = try! actualExpression.evaluate()! let testFileLocation = actualExpression.location.file let referenceImageDirectory = _getDefaultReferenceDirectory(testFileLocation) let snapshotName = name ?? _sanitizedTestName() let result = FBSnapshotTest.compareSnapshot(instance, snapshot: snapshotName, record: false, referenceDirectory: referenceImageDirectory) if !result { _clearFailureMessage(failureMessage) failureMessage.actualValue = "expected a matching snapshot in \(name)" } return result } func _recordSnapshot(name: String?, actualExpression: Expression<Snapshotable>, failureMessage: FailureMessage) -> Bool { let instance = try! actualExpression.evaluate()! let testFileLocation = actualExpression.location.file let referenceImageDirectory = _getDefaultReferenceDirectory(testFileLocation) let snapshotName = name ?? _sanitizedTestName() _clearFailureMessage(failureMessage) if FBSnapshotTest.compareSnapshot(instance, snapshot: snapshotName, record: true, referenceDirectory: referenceImageDirectory) { failureMessage.actualValue = "snapshot \(name) successfully recorded, replace recordSnapshot with a check" } else { failureMessage.actualValue = "expected to record a snapshot in \(name)" } return false } internal var switchChecksWithRecords = false public func haveValidSnapshot() -> MatcherFunc<Snapshotable> { return MatcherFunc { actualExpression, failureMessage in if (switchChecksWithRecords) { return _recordSnapshot(nil, actualExpression: actualExpression, failureMessage: failureMessage) } return _performSnapshotTest(nil, actualExpression: actualExpression, failureMessage: failureMessage) } } public func haveValidSnapshot(named name: String) -> MatcherFunc<Snapshotable> { return MatcherFunc { actualExpression, failureMessage in if (switchChecksWithRecords) { return _recordSnapshot(name, actualExpression: actualExpression, failureMessage: failureMessage) } return _performSnapshotTest(name, actualExpression: actualExpression, failureMessage: failureMessage) } } public func recordSnapshot() -> MatcherFunc<Snapshotable> { return MatcherFunc { actualExpression, failureMessage in return _recordSnapshot(nil, actualExpression: actualExpression, failureMessage: failureMessage) } } public func recordSnapshot(named name: String) -> MatcherFunc<Snapshotable> { return MatcherFunc { actualExpression, failureMessage in return _recordSnapshot(name, actualExpression: actualExpression, failureMessage: failureMessage) } }
mit
4e52e0c19abc86b50702795aa08701ed
37.245714
186
0.743762
5.65765
false
true
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Invoice/InvoiceCreatedViewController.swift
1
5443
// // InvoiceCreatedViewController.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import UIKit /** The view controller that shows the newly created invoice and lets the user share that invoice. */ final class InvoiceCreatedViewController: UIViewController { // MARK: - View Controller Properties var invoice: Invoice! // MARK: - View Controller Outlets @IBOutlet weak var invoiceQRCodeImageView: UIImageView! @IBOutlet weak var invoiceAccountTitleLabel: UILabel! @IBOutlet weak var invoiceAmountLabel: UILabel! @IBOutlet weak var invoiceMessageLabel: UILabel! @IBOutlet weak var invoiceDataHeadingLabel: UILabel! @IBOutlet weak var saveQRCodeImageButton: UIButton! @IBOutlet weak var shareQRCodeImageButton: UIButton! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var customNavigationItem: UINavigationItem! @IBOutlet weak var viewTopConstraint: NSLayoutConstraint! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationBar.delegate = self updateViewControllerAppearance() generateQRCode(forInvoice: invoice) let invoiceAccountTitleHeading = NSMutableAttributedString(string: "\("NAME".localized()): ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 13)]) let invoiceAccountTitle = NSMutableAttributedString(string: invoice.accountTitle, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)]) invoiceAccountTitleHeading.append(invoiceAccountTitle) invoiceAccountTitleLabel.attributedText = invoiceAccountTitleHeading let invoiceAmountHeading = NSMutableAttributedString(string: "\("AMOUNT".localized()): ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 13)]) let invoiceAmount = NSMutableAttributedString(string: "\((Double(invoice.amount) / 1000000).format()) XEM" , attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)]) invoiceAmountHeading.append(invoiceAmount) invoiceAmountLabel.attributedText = invoiceAmountHeading let invoiceMessageHeading = NSMutableAttributedString(string: "\("MESSAGE".localized()): ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 13)]) let invoiceMessage = NSMutableAttributedString(string: invoice.message, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)]) invoiceMessageHeading.append(invoiceMessage) invoiceMessageLabel.attributedText = invoiceMessageHeading } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() viewTopConstraint.constant = self.navigationBar.frame.height } // MARK: - View Controller Helper Methods /// Updates the appearance (coloring, titles) of the view controller. fileprivate func updateViewControllerAppearance() { invoiceDataHeadingLabel.text = "INVOICE_DATA".localized() saveQRCodeImageButton.setTitle("SAVE_QR".localized(), for: UIControlState()) shareQRCodeImageButton.setTitle("SHARE_QR".localized(), for: UIControlState()) } /** Generates the QR code image for the invoice. - Parameter invoice: The invoice for which the QR code image should get genererated. */ fileprivate func generateQRCode(forInvoice invoice: Invoice) { let invoiceDictionary: [String: Any] = [ QRKeys.address.rawValue : invoice.accountAddress, QRKeys.name.rawValue : invoice.accountTitle, QRKeys.amount.rawValue : invoice.amount, QRKeys.message.rawValue : invoice.message ] let jsonDictionary = NSDictionary(objects: [QRType.invoice.rawValue, invoiceDictionary, Constants.qrVersion], forKeys: [QRKeys.dataType.rawValue as NSCopying, QRKeys.data.rawValue as NSCopying, QRKeys.version.rawValue as NSCopying]) let jsonData = try! JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions.prettyPrinted) invoiceQRCodeImageView.image = String(data: jsonData, encoding: String.Encoding.utf8)!.createQRCodeImage() } // MARK: - View Controller Outlet Actions @IBAction func saveInvoiceQRCodeImage(_ sender: UIButton) { guard invoiceQRCodeImageView.image != nil else { return } UIImageWriteToSavedPhotosAlbum(invoiceQRCodeImageView.image!, nil, nil, nil) } @IBAction func shareInvoiceQRCodeImage(_ sender: UIButton) { if let qrCodeImage = invoiceQRCodeImageView.image { let message = "INVOICE_HEADER".localized() let shareActivityViewController = UIActivityViewController(activityItems: [message, qrCodeImage], applicationActivities: []) present(shareActivityViewController, animated: true) } } @IBAction func cancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } } // MARK: - Navigation Bar Delegate extension InvoiceCreatedViewController: UINavigationBarDelegate { func position(for bar: UIBarPositioning) -> UIBarPosition { return .topAttached } }
mit
4262ad6e8047f40809ca88b40d8996fb
40.549618
240
0.698696
5.509109
false
false
false
false
nguyenantinhbk77/practice-swift
Views/CollectionView/FlickrSearch/FlickrSearch/FlickrPhotosViewController.swift
2
10947
// // FlickrPhotosViewController.swift // FlickrSearch // // Created by Domenico on 03/06/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit let reuseIdentifier = "FlickrCell" extension FlickrPhotosViewController : UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { // 1 let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) textField.addSubview(activityIndicator) activityIndicator.frame = textField.bounds activityIndicator.startAnimating() flickr.searchFlickrForTerm(textField.text) { results, error in //2 activityIndicator.removeFromSuperview() if error != nil { println("Error searching : \(error)") } if results != nil { //3 println("Found \(results!.searchResults.count) matching \(results!.searchTerm)") self.searches.insert(results!, atIndex: 0) //4 self.collectionView?.reloadData() } } textField.text = nil textField.resignFirstResponder() return true } } extension FlickrPhotosViewController : UICollectionViewDataSource { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return searches.count } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return searches[section].searchResults.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FlickrPhotoCell let flickrPhoto = photoForIndexPath(indexPath) cell.activityIndicator.stopAnimating() if indexPath != largePhotoIndexPath { cell.imageView.image = flickrPhoto.thumbnail return cell } if flickrPhoto.largeImage != nil { cell.imageView.image = flickrPhoto.largeImage return cell } cell.imageView.image = flickrPhoto.thumbnail cell.activityIndicator.startAnimating() flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in cell.activityIndicator.stopAnimating() if error != nil { return } if loadedFlickrPhoto.largeImage == nil { return } if indexPath == self.largePhotoIndexPath { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? FlickrPhotoCell { cell.imageView.image = loadedFlickrPhoto.largeImage } } } return cell } } extension FlickrPhotosViewController : UICollectionViewDelegateFlowLayout { /** * It is responsible for telling the layout the size of a given cell. * To do this, you must first determine which FlickrPhoto you are looking at, since each photo could * have different dimensions. */ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let flickrPhoto = photoForIndexPath(indexPath) // Larged tapped photo if indexPath == largePhotoIndexPath { var size = collectionView.bounds.size size.height -= topLayoutGuide.length size.height -= (sectionInsets.top + sectionInsets.right) size.width -= (sectionInsets.left + sectionInsets.right) return flickrPhoto.sizeToFillWidthOfSize(size) } if var size = flickrPhoto.thumbnail?.size { size.width += 10 size.height += 10 return size } return CGSize(width: 20, height: 20) } // It returns the spacing between the cells, headers, and footers. func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return sectionInsets } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { switch kind { //2 case UICollectionElementKindSectionHeader: //3 let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "FlickrPhotoHeaderView", forIndexPath: indexPath) as! FlickrPhotoHeaderView headerView.label.text = searches[indexPath.section].searchTerm return headerView default: //4 assert(false, "Unexpected element kind") } } // Selected cell override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { if sharing { return true } if largePhotoIndexPath == indexPath{ largePhotoIndexPath = nil }else{ largePhotoIndexPath = indexPath } return false } // Add photos in sharing mode override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if sharing { let photo = photoForIndexPath(indexPath) selectedPhotos.append(photo) updateSharedPhotoCount() } } // Remove photos in sharing mode override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if sharing { if let foundIndex = find(selectedPhotos, photoForIndexPath(indexPath)) { selectedPhotos.removeAtIndex(foundIndex) updateSharedPhotoCount() } } } } class FlickrPhotosViewController: UICollectionViewController { private var searches = [FlickrSearchResults]() // List of searches private let flickr = Flickr() // Singleton private let sectionInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) private var selectedPhotos = [FlickrPhoto]() private let shareTextLabel = UILabel() func updateSharedPhotoCount() { shareTextLabel.textColor = themeColor shareTextLabel.text = "\(selectedPhotos.count) photos selected" shareTextLabel.sizeToFit() } override func viewDidLoad() { super.viewDidLoad() } // Keep track of the tapped cell var largePhotoIndexPath: NSIndexPath? { didSet{ var indexPaths = [NSIndexPath]() if self.largePhotoIndexPath != nil{ indexPaths.append(self.largePhotoIndexPath!) } if oldValue != nil{ indexPaths.append(oldValue!) } // Animate any changes to the collection view performed inside the block collectionView?.performBatchUpdates({ self.collectionView?.reloadItemsAtIndexPaths(indexPaths) return }){ completed in if self.largePhotoIndexPath != nil{ // Scroll the enlarged cell to the middle of the screen self.collectionView?.scrollToItemAtIndexPath( self.largePhotoIndexPath!, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true ) } } } } var sharing : Bool = false { didSet { collectionView?.allowsMultipleSelection = sharing collectionView?.selectItemAtIndexPath(nil, animated: true, scrollPosition: .None) selectedPhotos.removeAll(keepCapacity: false) if sharing && largePhotoIndexPath != nil { largePhotoIndexPath = nil } let shareButton = self.navigationItem.rightBarButtonItems!.first as! UIBarButtonItem if sharing { updateSharedPhotoCount() let sharingDetailItem = UIBarButtonItem(customView: shareTextLabel) navigationItem.setRightBarButtonItems([shareButton,sharingDetailItem], animated: true) } else { navigationItem.setRightBarButtonItems([shareButton], animated: true) } } } @IBAction func share(sender: AnyObject) { if searches.isEmpty { return } if !selectedPhotos.isEmpty { var imageArray = [UIImage]() for photo in self.selectedPhotos { imageArray.append(photo.thumbnail!); } let shareScreen = UIActivityViewController(activityItems: imageArray, applicationActivities: nil) //let popover = UIPopoverController(contentViewController: shareScreen) self.presentViewController(shareScreen, animated: true, completion: nil) //popover.presentPopoverFromBarButtonItem(self.navigationItem.rightBarButtonItems!.first as! UIBarButtonItem, // permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } sharing = !sharing } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //- MARK: Flickr // Convenience method that will get a specific photo related to // an index path in your collection view. func photoForIndexPath(indexPath: NSIndexPath) -> FlickrPhoto { return searches[indexPath.section].searchResults[indexPath.row] } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
2750975bf9121469c733cda5cb7e59e4
34.891803
180
0.602996
6.523838
false
false
false
false
neo1125/NumberPad
NumberPad/Sources/NumberPad.swift
1
9358
import UIKit import CoreGraphics public protocol NumberPadDelegate { func keyPressed(key: NumberKey?) } @IBDesignable open class NumberPad: UIView { open var delegate: NumberPadDelegate? private var longRunTimer: Timer? @IBInspectable open var keyBackgroundColor: UIColor = defaultBackgroundColor { didSet { updateKeys() } } @IBInspectable open var keyHighlightColor: UIColor = defaultHighlightColor { didSet { updateKeys() } } @IBInspectable open var keyTitleColor: UIColor = .white { didSet { updateKeys() } } @IBInspectable open var keyBorderWidth: CGFloat = 0.0 { didSet { updateKeys() } } @IBInspectable open var keyBorderColor: UIColor = .clear { didSet { updateKeys() } } @IBInspectable open var keyScale: CGFloat = 1.0 { didSet { updateKeys() } } open var style: NumberPadStyle = .square { didSet { updateKeys() } } open var keyFont: UIFont? = UIFont(name: "AppleSDGothicNeo-Thin", size: 44) { didSet { updateKeys() } } open var clearKeyPosition: NumberClearKeyPosition = .right { didSet { updateKeys() } } open var clearKeyIcon: UIImage? = UIImage(named: "ic_backspace", in: Bundle.myBundle(), compatibleWith: nil) { didSet { updateKeys() } } open var clearKeyBackgroundColor: UIColor = defaultBackgroundColor { didSet { updateKeys() } } open var clearKeyHighlightColor: UIColor = defaultHighlightColor { didSet { updateKeys() } } open var emptyKeyBackgroundColor: UIColor = defaultBackgroundColor { didSet { updateKeys() } } open var clearKeyTintColor: UIColor = .white { didSet { updateKeys() } } open var customKeyText: String? = nil { didSet { updateKeys() } } open var customKeyImgae: UIImage? = nil { didSet { updateKeys() } } open var customKeyTitleColor: UIColor? = nil { didSet { updateKeys() } } open var customKeyBackgroundColor: UIColor? = nil { didSet { updateKeys() } } open var customKeyHighlightColor: UIColor? = nil { didSet { updateKeys() } } open var customKeyBorderWidth: CGFloat = 0 { didSet { updateKeys() } } open var customKeyBorderColor: UIColor? = nil { didSet { updateKeys() } } public override init(frame: CGRect) { super.init(frame: frame) setupViews() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } open override func layoutSubviews() { super.layoutSubviews() print("########### layoutSubviews ") updateKeys() } @objc func keyEvent(sender: NumberKeyButton) { delegate?.keyPressed(key: sender.key) } @objc func longPressed(sender: UILongPressGestureRecognizer) { if let button = sender.view as? NumberKeyButton { switch sender.state { case .began: button.isHighlighted = true longRunTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(runLongPressed(sender:)), userInfo: button, repeats: true) case .ended: button.isHighlighted = false if longRunTimer != nil { longRunTimer?.invalidate() longRunTimer = nil } default: break } } } @objc func runLongPressed(sender: Timer) { if let button = sender.userInfo as? NumberKeyButton { delegate?.keyPressed(key: button.key) } } private static let defaultBackgroundColor: UIColor = UIColor(white: 0, alpha: 0.6) private static let defaultHighlightColor: UIColor = UIColor(white: 0, alpha: 0.4) private final let rows: Int = 4 private final let cols: Int = 3 private var keys: [NumberKeyButton] = [] private func setupViews() { clipsToBounds = true let width: CGFloat = bounds.width / CGFloat(cols) let height: CGFloat = bounds.height / CGFloat(rows) var keyNumber = 1 for i in 1...rows { for j in 1...cols { let keyButton = NumberKeyButton(type: .custom) keyButton.frame = CGRect(x: CGFloat(j-1) * width, y: CGFloat(i-1) * height, width: width, height: height) keyButton.addTarget(self, action: #selector(keyEvent(sender:)), for: .touchUpInside) keyButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressed(sender:)))) switch keyNumber { case 10: keyButton.key = .empty case 11: keyButton.key = .key0 case 12: keyButton.key = .clear default: keyButton.key = NumberKey(rawValue: keyNumber) } keys.append(keyButton) self.addSubview(keyButton) keyNumber += 1 } } updateKeys() } private func updateKeys() { var row: Int = 0 var col: Int = 0 let width: CGFloat = bounds.width / CGFloat(cols) let height: CGFloat = bounds.height / CGFloat(rows) for (index, button) in keys.enumerated() { if clearKeyPosition == .left { if index == 9 { button.key = .clear } if index == 11 { button.key = (customKeyText != nil || customKeyImgae != nil) ? .custom : .empty } } else { if index == 9 { button.key = (customKeyText != nil || customKeyImgae != nil) ? .custom : .empty } if index == 11 { button.key = .clear } } if button.bounds.width != width || button.bounds.height != height { if style == .circle && width != height { if width > height { button.frame = CGRect(x: CGFloat(col) * width, y: CGFloat(row) * height, width: height, height: height) } else { button.frame = CGRect(x: CGFloat(col) * width, y: CGFloat(row) * height, width: width, height: width) } } else { var offset: CGFloat = (keyBorderWidth > 0) ? keyBorderWidth/2 : 0 offset = (button.key == .custom) ? 0 : offset button.frame = CGRect(x: CGFloat(col) * width, y: CGFloat(row) * height, width: width + offset, height: height + offset) } } button.layer.cornerRadius = style == .square ? 0 : button.bounds.height / 2 button.setScale(scale: keyScale) button.setBackgroundColor(color: keyBackgroundColor, forState: .normal) button.setBackgroundColor(color: keyHighlightColor, forState: .highlighted) button.setTitleColor(keyTitleColor, for: .normal) button.titleLabel?.font = keyFont button.clipsToBounds = true switch button.key { case .some(.clear): button.setIcon(image: clearKeyIcon, color: clearKeyTintColor) button.setBackgroundColor(color: clearKeyBackgroundColor, forState: .normal) button.setBackgroundColor(color: clearKeyHighlightColor, forState: .highlighted) button.layer.borderWidth = keyBorderWidth button.layer.borderColor = keyBorderColor.cgColor case .some(.empty): button.setBackgroundColor(color: emptyKeyBackgroundColor, forState: .normal) button.setBackgroundColor(color: emptyKeyBackgroundColor, forState: .highlighted) button.layer.borderWidth = keyBorderWidth button.layer.borderColor = keyBorderColor.cgColor case .some(.custom): button.setIcon(image: customKeyImgae, color: clearKeyTintColor) button.setTitle(customKeyText, for: .normal) button.setBackgroundColor(color: customKeyBackgroundColor ?? keyBackgroundColor, forState: .normal) button.setBackgroundColor(color: customKeyHighlightColor ?? keyHighlightColor, forState: .highlighted) button.setTitleColor(customKeyTitleColor ?? keyTitleColor, for: .normal) button.layer.borderWidth = customKeyBorderWidth button.layer.borderColor = customKeyBorderColor?.cgColor default: button.layer.borderWidth = keyBorderWidth button.layer.borderColor = keyBorderColor.cgColor } col += 1 if col >= cols { row += 1 col = 0 } } } } extension Bundle { static func myBundle() -> Bundle { let bundle = Bundle(for: NumberPad.self) return bundle } }
mit
c703eb916c2cae673ed6264ec936f38a
34.854406
163
0.558453
5.155923
false
false
false
false
johnno1962c/swift-corelibs-foundation
Foundation/NSCalendar.swift
6
81467
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) internal let kCFCalendarUnitEra = CFCalendarUnit.era.rawValue internal let kCFCalendarUnitYear = CFCalendarUnit.year.rawValue internal let kCFCalendarUnitMonth = CFCalendarUnit.month.rawValue internal let kCFCalendarUnitDay = CFCalendarUnit.day.rawValue internal let kCFCalendarUnitHour = CFCalendarUnit.hour.rawValue internal let kCFCalendarUnitMinute = CFCalendarUnit.minute.rawValue internal let kCFCalendarUnitSecond = CFCalendarUnit.second.rawValue internal let kCFCalendarUnitWeekday = CFCalendarUnit.weekday.rawValue internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.weekdayOrdinal.rawValue internal let kCFCalendarUnitQuarter = CFCalendarUnit.quarter.rawValue internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.weekOfMonth.rawValue internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.weekOfYear.rawValue internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.yearForWeekOfYear.rawValue internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle #endif extension NSCalendar { public struct Identifier : RawRepresentable, Equatable, Hashable, Comparable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return rawValue.hashValue } public static let gregorian = NSCalendar.Identifier("gregorian") public static let buddhist = NSCalendar.Identifier("buddhist") public static let chinese = NSCalendar.Identifier("chinese") public static let coptic = NSCalendar.Identifier("coptic") public static let ethiopicAmeteMihret = NSCalendar.Identifier("ethiopic") public static let ethiopicAmeteAlem = NSCalendar.Identifier("ethiopic-amete-alem") public static let hebrew = NSCalendar.Identifier("hebrew") public static let ISO8601 = NSCalendar.Identifier("iso8601") public static let indian = NSCalendar.Identifier("indian") public static let islamic = NSCalendar.Identifier("islamic") public static let islamicCivil = NSCalendar.Identifier("islamic-civil") public static let japanese = NSCalendar.Identifier("japanese") public static let persian = NSCalendar.Identifier("persian") public static let republicOfChina = NSCalendar.Identifier("roc") public static let islamicTabular = NSCalendar.Identifier("islamic-tbla") public static let islamicUmmAlQura = NSCalendar.Identifier("islamic-umalqura") } public struct Unit: OptionSet { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let era = Unit(rawValue: UInt(kCFCalendarUnitEra)) public static let year = Unit(rawValue: UInt(kCFCalendarUnitYear)) public static let month = Unit(rawValue: UInt(kCFCalendarUnitMonth)) public static let day = Unit(rawValue: UInt(kCFCalendarUnitDay)) public static let hour = Unit(rawValue: UInt(kCFCalendarUnitHour)) public static let minute = Unit(rawValue: UInt(kCFCalendarUnitMinute)) public static let second = Unit(rawValue: UInt(kCFCalendarUnitSecond)) public static let weekday = Unit(rawValue: UInt(kCFCalendarUnitWeekday)) public static let weekdayOrdinal = Unit(rawValue: UInt(kCFCalendarUnitWeekdayOrdinal)) public static let quarter = Unit(rawValue: UInt(kCFCalendarUnitQuarter)) public static let weekOfMonth = Unit(rawValue: UInt(kCFCalendarUnitWeekOfMonth)) public static let weekOfYear = Unit(rawValue: UInt(kCFCalendarUnitWeekOfYear)) public static let yearForWeekOfYear = Unit(rawValue: UInt(kCFCalendarUnitYearForWeekOfYear)) public static let nanosecond = Unit(rawValue: UInt(1 << 15)) public static let calendar = Unit(rawValue: UInt(1 << 20)) public static let timeZone = Unit(rawValue: UInt(1 << 21)) internal var _cfValue: CFCalendarUnit { #if os(OSX) || os(iOS) return CFCalendarUnit(rawValue: self.rawValue) #else return CFCalendarUnit(self.rawValue) #endif } } public struct Options : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let wrapComponents = Options(rawValue: 1 << 0) public static let matchStrictly = Options(rawValue: 1 << 1) public static let searchBackwards = Options(rawValue: 1 << 2) public static let matchPreviousTimePreservingSmallerUnits = Options(rawValue: 1 << 8) public static let matchNextTimePreservingSmallerUnits = Options(rawValue: 1 << 9) public static let matchNextTime = Options(rawValue: 1 << 10) public static let matchFirst = Options(rawValue: 1 << 12) public static let matchLast = Options(rawValue: 1 << 13) } } extension NSCalendar.Identifier { public static func ==(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool { return lhs.rawValue == rhs.rawValue } public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool { return lhs.rawValue < rhs.rawValue } } open class NSCalendar : NSObject, NSCopying, NSSecureCoding { typealias CFType = CFCalendar private var _base = _CFInfo(typeID: CFCalendarGetTypeID()) private var _identifier: UnsafeMutableRawPointer? = nil private var _locale: UnsafeMutableRawPointer? = nil private var _localeID: UnsafeMutableRawPointer? = nil private var _tz: UnsafeMutableRawPointer? = nil private var _cal: UnsafeMutableRawPointer? = nil internal var _cfObject: CFType { return unsafeBitCast(self, to: CFCalendar.self) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let calendarIdentifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else { return nil } self.init(identifier: NSCalendar.Identifier.init(rawValue: calendarIdentifier._swiftObject)) if let timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone") { self.timeZone = timeZone._swiftObject } if let locale = aDecoder.decodeObject(of: NSLocale.self, forKey: "NS.locale") { self.locale = locale._swiftObject } self.firstWeekday = aDecoder.decodeInteger(forKey: "NS.firstwkdy") self.minimumDaysInFirstWeek = aDecoder.decodeInteger(forKey: "NS.mindays") if let startDate = aDecoder.decodeObject(of: NSDate.self, forKey: "NS.gstartdate") { self._startDate = startDate._swiftObject } } private var _startDate : Date? { get { return CFCalendarCopyGregorianStartDate(self._cfObject)?._swiftObject } set { if let startDate = newValue { CFCalendarSetGregorianStartDate(self._cfObject, startDate._cfObject) } } } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.calendarIdentifier.rawValue._bridgeToObjectiveC(), forKey: "NS.identifier") aCoder.encode(self.timeZone._nsObject, forKey: "NS.timezone") aCoder.encode(self.locale?._bridgeToObjectiveC(), forKey: "NS.locale") aCoder.encode(self.firstWeekday, forKey: "NS.firstwkdy") aCoder.encode(self.minimumDaysInFirstWeek, forKey: "NS.mindays") aCoder.encode(self._startDate?._nsObject, forKey: "NS.gstartdate") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let copy = NSCalendar(identifier: calendarIdentifier)! copy.locale = locale copy.timeZone = timeZone copy.firstWeekday = firstWeekday copy.minimumDaysInFirstWeek = minimumDaysInFirstWeek copy._startDate = _startDate return copy } open class var current: Calendar { return CFCalendarCopyCurrent()._swiftObject } open class var autoupdatingCurrent: Calendar { NSUnimplemented() } // tracks changes to user's preferred calendar identifier public /*not inherited*/ init?(identifier calendarIdentifierConstant: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant.rawValue._cfObject) { return nil } } public init?(calendarIdentifier ident: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, ident.rawValue._cfObject) { return nil } } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Calendar: return CFEqual(_cfObject, other._cfObject) case let other as NSCalendar: return other === self || CFEqual(_cfObject, other._cfObject) default: return false } } open override var description: String { return CFCopyDescription(_cfObject)._swiftObject } deinit { _CFDeinit(self) } open var calendarIdentifier: Identifier { get { return Identifier(rawValue: CFCalendarGetIdentifier(_cfObject)._swiftObject) } } /*@NSCopying*/ open var locale: Locale? { get { return CFCalendarCopyLocale(_cfObject)._swiftObject } set { CFCalendarSetLocale(_cfObject, newValue?._cfObject) } } /*@NSCopying*/ open var timeZone: TimeZone { get { return CFCalendarCopyTimeZone(_cfObject)._swiftObject } set { CFCalendarSetTimeZone(_cfObject, newValue._cfObject) } } open var firstWeekday: Int { get { return CFCalendarGetFirstWeekday(_cfObject) } set { CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue)) } } open var minimumDaysInFirstWeek: Int { get { return CFCalendarGetMinimumDaysInFirstWeek(_cfObject) } set { CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue)) } } // Methods to return component name strings localized to the calendar's locale private func _symbols(_ key: CFString) -> [String] { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject) let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! CFArray)._swiftObject return result.map { return ($0 as! NSString)._swiftObject } } private func _symbol(_ key: CFString) -> String { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._bridgeToObjectiveC()._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject) return (CFDateFormatterCopyProperty(dateFormatter, key) as! CFString)._swiftObject } open var eraSymbols: [String] { return _symbols(kCFDateFormatterEraSymbolsKey) } open var longEraSymbols: [String] { return _symbols(kCFDateFormatterLongEraSymbolsKey) } open var monthSymbols: [String] { return _symbols(kCFDateFormatterMonthSymbolsKey) } open var shortMonthSymbols: [String] { return _symbols(kCFDateFormatterShortMonthSymbolsKey) } open var veryShortMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey) } open var standaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey) } open var shortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey) } open var veryShortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey) } open var weekdaySymbols: [String] { return _symbols(kCFDateFormatterWeekdaySymbolsKey) } open var shortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortWeekdaySymbolsKey) } open var veryShortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey) } open var standaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey) } open var shortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey) } open var veryShortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey) } open var quarterSymbols: [String] { return _symbols(kCFDateFormatterQuarterSymbolsKey) } open var shortQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortQuarterSymbolsKey) } open var standaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey) } open var shortStandaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey) } open var amSymbol: String { return _symbol(kCFDateFormatterAMSymbolKey) } open var pmSymbol: String { return _symbol(kCFDateFormatterPMSymbolKey) } // Calendrical calculations open func minimumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue) if (r.location == kCFNotFound) { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length) } open func maximumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue) if r.location == kCFNotFound { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length) } open func range(of smaller: Unit, in larger: Unit, for date: Date) -> NSRange { let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate) if r.location == kCFNotFound { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length) } open func ordinality(of smaller: Unit, in larger: Unit, for date: Date) -> Int { return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfUnit(_ unit: Unit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(of unit: Unit, for date: Date) -> DateInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp in withUnsafeMutablePointer(to: &ti) { tip in return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip) } } if res { return DateInterval(start: Date(timeIntervalSinceReferenceDate: start), duration: ti) } return nil } private func _convert(_ comp: Int?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comp: Bool?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component ? 0 : 1)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comps: DateComponents) -> (Array<Int32>, Array<Int8>) { var vector = [Int32]() var compDesc = [Int8]() _convert(comps.era, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc) _convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc) if comps.weekOfYear != NSDateComponentUndefined { _convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc) } else { // _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc) } _convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc) _convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc) _convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc) _convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc) _convert(comps.isLeapMonth, type: "l", vector: &vector, compDesc: &compDesc) _convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc) _convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc) _convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc) _convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc) _convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc) compDesc.append(0) return (vector, compDesc) } open func date(from comps: DateComponents) -> Date? { var (vector, compDesc) = _convert(comps) self.timeZone = comps.timeZone ?? timeZone var at: CFAbsoluteTime = 0.0 let res: Bool = withUnsafeMutablePointer(to: &at) { t in return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress!, Int32(vectorBuffer.count)) } } if res { return Date(timeIntervalSinceReferenceDate: at) } else { return nil } } private func _setup(_ unitFlags: Unit, field: Unit, type: String, compDesc: inout [Int8]) { if unitFlags.contains(field) { compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _setup(_ unitFlags: Unit) -> [Int8] { var compDesc = [Int8]() _setup(unitFlags, field: .era, type: "G", compDesc: &compDesc) _setup(unitFlags, field: .year, type: "y", compDesc: &compDesc) _setup(unitFlags, field: .quarter, type: "Q", compDesc: &compDesc) _setup(unitFlags, field: .month, type: "M", compDesc: &compDesc) _setup(unitFlags, field: .month, type: "l", compDesc: &compDesc) _setup(unitFlags, field: .day, type: "d", compDesc: &compDesc) _setup(unitFlags, field: .weekOfYear, type: "w", compDesc: &compDesc) _setup(unitFlags, field: .weekOfMonth, type: "W", compDesc: &compDesc) _setup(unitFlags, field: .yearForWeekOfYear, type: "Y", compDesc: &compDesc) _setup(unitFlags, field: .weekday, type: "E", compDesc: &compDesc) _setup(unitFlags, field: .weekdayOrdinal, type: "F", compDesc: &compDesc) _setup(unitFlags, field: .hour, type: "H", compDesc: &compDesc) _setup(unitFlags, field: .minute, type: "m", compDesc: &compDesc) _setup(unitFlags, field: .second, type: "s", compDesc: &compDesc) _setup(unitFlags, field: .nanosecond, type: "#", compDesc: &compDesc) compDesc.append(0) return compDesc } private func _setComp(_ unitFlags: Unit, field: Unit, vector: [Int32], compIndex: inout Int, setter: (Int32) -> Void) { if unitFlags.contains(field) { setter(vector[compIndex]) compIndex += 1 } } private func _components(_ unitFlags: Unit, vector: [Int32]) -> DateComponents { var compIdx = 0 var comps = DateComponents() _setComp(unitFlags, field: .era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) } _setComp(unitFlags, field: .year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) } _setComp(unitFlags, field: .quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) } _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) } _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.isLeapMonth = $0 != 0 } _setComp(unitFlags, field: .day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) } _setComp(unitFlags, field: .weekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) } _setComp(unitFlags, field: .weekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) } _setComp(unitFlags, field: .yearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) } _setComp(unitFlags, field: .weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) } _setComp(unitFlags, field: .weekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) } _setComp(unitFlags, field: .hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) } _setComp(unitFlags, field: .minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) } _setComp(unitFlags, field: .second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) } _setComp(unitFlags, field: .nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) } if unitFlags.contains(.calendar) { comps.calendar = self._swiftObject } if unitFlags.contains(.timeZone) { comps.timeZone = timeZone } return comps } /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(_ unitFlags: Unit, from date: Date) -> DateComponents { let compDesc = _setup(unitFlags) // _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format // int32_t ints[20]; // int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]}; var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in intArrayBuffer.baseAddress!.advanced(by: idx) } return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress!, Int32(compDesc.count - 1)) } } if res { return _components(unitFlags, vector: ints) } fatalError() } open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? { var (vector, compDesc) = _convert(comps) var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate let res: Bool = withUnsafeMutablePointer(to: &at) { t in return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress!, Int32(vector.count)) } } if res { return Date(timeIntervalSinceReferenceDate: at) } return nil } open func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents { let compDesc = _setup(unitFlags) var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in return intArrayBuffer.baseAddress!.advanced(by: idx) } return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, Int32(vector.count)) } } if res { return _components(unitFlags, vector: ints) } fatalError() } /* This API is a convenience for getting era, year, month, and day of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .year, .month, .day], from: date) if let value = comps.era { eraValuePointer?.pointee = value } else { eraValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.year { yearValuePointer?.pointee = value } else { yearValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.month { monthValuePointer?.pointee = value } else { monthValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.day { dayValuePointer?.pointee = value } else { dayValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.year { yearValuePointer?.pointee = value } else { yearValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.month { monthValuePointer?.pointee = value } else { monthValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.day { dayValuePointer?.pointee = value } else { dayValuePointer?.pointee = NSDateComponentUndefined } } /* This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .yearForWeekOfYear, .weekOfYear, .weekday], from: date) if let value = comps.era { eraValuePointer?.pointee = value } else { eraValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.yearForWeekOfYear { yearValuePointer?.pointee = value } else { yearValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.weekOfYear { weekValuePointer?.pointee = value } else { weekValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.weekday { weekdayValuePointer?.pointee = value } else { weekdayValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.yearForWeekOfYear { yearValuePointer?.pointee = value } else { yearValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.weekOfYear { weekValuePointer?.pointee = value } else { weekValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.weekday { weekdayValuePointer?.pointee = value } else { weekdayValuePointer?.pointee = NSDateComponentUndefined } } /* This API is a convenience for getting hour, minute, second, and nanoseconds of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.hour, .minute, .second, .nanosecond], from: date) if let value = comps.hour { hourValuePointer?.pointee = value } else { hourValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.minute { minuteValuePointer?.pointee = value } else { minuteValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.second { secondValuePointer?.pointee = value } else { secondValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.nanosecond { nanosecondValuePointer?.pointee = value } else { nanosecondValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.minute { minuteValuePointer?.pointee = value } else { minuteValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.second { secondValuePointer?.pointee = value } else { secondValuePointer?.pointee = NSDateComponentUndefined } if let value = comps.nanosecond { nanosecondValuePointer?.pointee = value } else { nanosecondValuePointer?.pointee = NSDateComponentUndefined } } /* Get just one component's value. */ open func component(_ unit: Unit, from date: Date) -> Int { let comps = components(unit, from: date) if let res = comps.value(for: Calendar._fromCalendarUnit(unit)) { return res } else { return NSDateComponentUndefined } } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.year = yearValue comps.month = monthValue comps.day = dayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.yearForWeekOfYear = yearValue comps.weekOfYear = weekValue comps.weekday = weekdayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* This API returns the first moment date of a given date. Pass in [NSDate date], for example, if you want the start of "today". If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. */ open func startOfDay(for date: Date) -> Date { return range(of: .day, for: date)!.start } /* This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone). The time zone overrides the time zone of the NSCalendar for the purposes of this calculation. Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(in timezone: TimeZone, from date: Date) -> DateComponents { let oldTz = self.timeZone self.timeZone = timezone let comps = components([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone], from: date) self.timeZone = oldTz return comps } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than. */ open func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: Unit) -> ComparisonResult { switch (unit) { case Unit.calendar: return .orderedSame case Unit.timeZone: return .orderedSame case Unit.day: fallthrough case Unit.hour: let range = self.range(of: unit, for: date1) let ats = range!.start.timeIntervalSinceReferenceDate let at2 = date2.timeIntervalSinceReferenceDate if ats <= at2 && at2 < ats + range!.duration { return .orderedSame } if at2 < ats { return .orderedDescending } return .orderedAscending case Unit.minute: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(int1 / 60.0) int2 = floor(int2 / 60.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case Unit.second: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case Unit.nanosecond: var int1 = 0.0 var int2 = 0.0 let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1) let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(frac1 * 1000000000.0) int2 = floor(frac2 * 1000000000.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending default: break } let calendarUnits1: [Unit] = [.era, .year, .month, .day] let calendarUnits2: [Unit] = [.era, .year, .month, .weekdayOrdinal, .day] let calendarUnits3: [Unit] = [.era, .year, .month, .weekOfMonth, .weekday] let calendarUnits4: [Unit] = [.era, .yearForWeekOfYear, .weekOfYear, .weekday] var units: [Unit] if unit == .yearForWeekOfYear || unit == .weekOfYear { units = calendarUnits4 } else if unit == .weekdayOrdinal { units = calendarUnits2 } else if unit == .weekday || unit == .weekOfMonth { units = calendarUnits3 } else { units = calendarUnits1 } // TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret let reducedUnits = units.reduce(Unit()) { $0.union($1) } let comp1 = components(reducedUnits, from: date1) let comp2 = components(reducedUnits, from: date2) for unit in units { let value1 = comp1.value(for: Calendar._fromCalendarUnit(unit)) let value2 = comp2.value(for: Calendar._fromCalendarUnit(unit)) if value1! > value2! { return .orderedDescending } else if value1! < value2! { return .orderedAscending } if unit == .month && calendarIdentifier == .chinese { if let leap1 = comp1.isLeapMonth { if let leap2 = comp2.isLeapMonth { if !leap1 && leap2 { return .orderedAscending } else if leap1 && !leap2 { return .orderedDescending } } } } if unit == reducedUnits { return .orderedSame } } return .orderedSame } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units. */ open func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: Unit) -> Bool { return compare(date1, to: date2, toUnitGranularity: unit) == .orderedSame } /* This API compares the Days of the given dates, reporting them equal if they are in the same Day. */ open func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool { return compare(date1, to: date2, toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "today". */ open func isDateInToday(_ date: Date) -> Bool { return compare(date, to: Date(), toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "yesterday". */ open func isDateInYesterday(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inYesterday = interval.start - 60.0 return compare(date, to: inYesterday, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within "tomorrow". */ open func isDateInTomorrow(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inTomorrow = interval.end + 60.0 return compare(date, to: inTomorrow, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale. */ open func isDateInWeekend(_ date: Date) -> Bool { return _CFCalendarIsWeekend(_cfObject, date.timeIntervalSince1970) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// Returns nil if the given date is not in a weekend. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(ofWeekendContaining date: Date) -> DateInterval? { if let next = nextWeekendAfter(date, options: []) { if let prev = nextWeekendAfter(next.start, options: .searchBackwards) { if prev.start.timeIntervalSinceReferenceDate <= date.timeIntervalSinceReferenceDate && date.timeIntervalSinceReferenceDate <= prev.end.timeIntervalSinceReferenceDate { return prev } } } return nil } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func nextWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: Options, afterDate date: NSDate) -> Bool /// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date. /// The .SearchBackwards option can be used to find the previous weekend range strictly before the date. /// Returns nil if there are no such things as weekend in the calendar and its locale. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func nextWeekendAfter(_ date: Date, options: Options) -> DateInterval? { var range = _CFCalendarWeekendRange() let res = withUnsafeMutablePointer(to: &range) { rangep in return _CFCalendarGetNextWeekend(_cfObject, rangep) } if res { var comp = DateComponents() comp.weekday = range.start if let nextStart = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) { let start = nextStart + range.onsetTime comp.weekday = range.end if let nextEnd = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) { var end = nextEnd if end.compare(start) == .orderedAscending { if let nextOrderedEnd = nextDate(after: end, matching: comp, options: options.union(.matchNextTime)) { end = nextOrderedEnd } else { return nil } } if range.ceaseTime > 0 { end = end + range.ceaseTime } else { if let dayEnd = self.range(of: .day, for: end) { end = startOfDay(for: dayEnd.end) } else { return nil } } return DateInterval(start: start, end: end) } } } return nil } /* This API returns the difference between two dates specified as date components. For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed. Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised. For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property. No options are currently defined; pass 0. */ open func components(_ unitFlags: Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: Options = []) -> DateComponents { var startDate: Date? var toDate: Date? if let startCalendar = startingDateComp.calendar { startDate = startCalendar.date(from: startingDateComp) } else { startDate = date(from: startingDateComp) } if let toCalendar = resultDateComp.calendar { toDate = toCalendar.date(from: resultDateComp) } else { toDate = date(from: resultDateComp) } if let start = startDate { if let end = toDate { return components(unitFlags, from: start, to: end, options: options) } } fatalError() } /* This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date. The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented. */ open func date(byAdding unit: Unit, value: Int, to date: Date, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return self.date(byAdding: comps, to: date, options: options) } /* This method computes the dates which match (or most closely match) a given set of components, and calls the block once for each of them, until the enumeration is stopped. There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. If the NSCalendarSearchBackwards option is used, this method finds the previous match before the given date. The intent is that the same matches as for a forwards search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). If the NSCalendarMatchStrictly option is used, the algorithm travels as far forward or backward as necessary looking for a match, but there are ultimately implementation-defined limits in how far distant the search will go. If the NSCalendarMatchStrictly option is not specified, the algorithm searches up to the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument. If you want to find the next Feb 29 in the Gregorian calendar, for example, you have to specify the NSCalendarMatchStrictly option to guarantee finding it. If an exact match is not possible, and requested with the NSCalendarMatchStrictly option, nil is passed to the block and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) If the NSCalendarMatchStrictly option is NOT used, exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified, or an illegal argument exception will be thrown. If the NSCalendarMatchPreviousTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the previous existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 1:37am, if that exists). If the NSCalendarMatchNextTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 3:37am, if that exists). If the NSCalendarMatchNextTime option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing time which exists (e.g., no 2:37am results in 3:00am, if that exists). If the NSCalendarMatchFirst option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the first occurrence. If the NSCalendarMatchLast option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the last occurrence. If neither the NSCalendarMatchFirst or NSCalendarMatchLast option is specified, the default behavior is to act as if NSCalendarMatchFirst was specified. There is no option to return middle occurrences of more than two occurrences of a matching time, if such exist. Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the NSDateComponents matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). The enumeration is stopped by setting *stop = YES in the block and return. It is not necessary to set *stop to NO to keep the enumeration going. */ open func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { NSUnimplemented() } /* This method computes the next date which matches (or most closely matches) a given set of components. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching comps: DateComponents, options: Options = []) -> Date? { var result: Date? enumerateDates(startingAfter: date, matching: comps, options: options) { date, exactMatch, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date found which matches a specific component value. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching unit: Unit, value: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return nextDate(after:date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date found which matches the given hour, minute, and second values. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue return nextDate(after: date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the unit already has that value, this may result in a date which is the same as the given date. Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other units to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. The specific behaviors here are as yet unspecified; for example, if I change the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? A likely rule is that the algorithm will try to produce a result which is in the next-larger unit to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For forwards or backwards behavior, one can use the -nextDateAfterDate:matchingUnit:value:options: method above. */ open func date(bySettingUnit unit: Unit, value v: Int, of date: Date, options opts: Options = []) -> Date? { let currentValue = component(unit, from: date) if currentValue == v { return date } var targetComp = DateComponents() targetComp.setValue(v, for: Calendar._fromCalendarUnit(unit)) var result: Date? enumerateDates(startingAfter: date, matching: targetComp, options: .matchNextTime) { date, match, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time. If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course. */ open func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: Options = []) -> Date? { if let range = range(of: .day, for: date) { var comps = DateComponents() comps.hour = h comps.minute = m comps.second = s var options: Options = .matchNextTime options.formUnion(opts.contains(.matchLast) ? .matchLast : .matchFirst) if opts.contains(.matchStrictly) { options.formUnion(.matchStrictly) } if let result = nextDate(after: range.start - 0.5, matching: comps, options: options) { if result.compare(range.start) == .orderedAscending { return nextDate(after: range.start, matching: comps, options: options) } return result } } return nil } /* This API returns YES if the date has all the matched components. Otherwise, it returns NO. It is useful to test the return value of the -nextDateAfterDate:matchingUnit:value:options:, to find out if the components were obeyed or if the method had to fudge the result value due to missing time. */ open func date(_ date: Date, matchesComponents components: DateComponents) -> Bool { let units: [Unit] = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond] var unitFlags: Unit = [] for unit in units { if components.value(for: Calendar._fromCalendarUnit(unit)) != NSDateComponentUndefined { unitFlags.formUnion(unit) } } if unitFlags == [] { if components.isLeapMonth != nil { let comp = self.components(.month, from: date) if let leap = comp.isLeapMonth { return leap } return false } } let comp = self.components(unitFlags, from: date) var compareComp = comp var tempComp = components tempComp.isLeapMonth = comp.isLeapMonth if let nanosecond = comp.value(for: .nanosecond) { if labs(nanosecond - tempComp.value(for: .nanosecond)!) > 500 { return false } else { compareComp.nanosecond = 0 tempComp.nanosecond = 0 } return tempComp == compareComp } return false } } // This notification is posted through [NSNotificationCenter defaultCenter] // when the system day changes. Register with "nil" as the object of this // notification. If the computer/device is asleep when the day changed, // this will be posted on wakeup. You'll get just one of these if the // machine has been asleep for several days. The definition of "Day" is // relative to the current calendar ([NSCalendar currentCalendar]) of the // process and its locale and time zone. There are no guarantees that this // notification is received by observers in a "timely" manner, same as // with distributed notifications. extension NSNotification.Name { public static let NSCalendarDayChanged = NSNotification.Name(rawValue: "NSCalendarDayChangedNotification") } // This is a just used as an extensible struct, basically; // note that there are two uses: one for specifying a date // via components (some components may be missing, making the // specific date ambiguous), and the other for specifying a // set of component quantities (like, 3 months and 5 hours). // Undefined fields have (or fields can be set to) the value // NSDateComponentUndefined. // NSDateComponents is not responsible for answering questions // about a date beyond the information it has been initialized // with; for example, if you initialize one with May 6, 2004, // and then ask for the weekday, you'll get Undefined, not Thurs. // A NSDateComponents is meaningless in itself, because you need // to know what calendar it is interpreted against, and you need // to know whether the values are absolute values of the units, // or quantities of the units. // When you create a new one of these, all values begin Undefined. public var NSDateComponentUndefined: Int = Int.max open class NSDateComponents : NSObject, NSCopying, NSSecureCoding { internal var _calendar: Calendar? internal var _timeZone: TimeZone? internal var _values = [Int](repeating: NSDateComponentUndefined, count: 19) public override init() { super.init() } open override var hash: Int { var calHash = 0 if let cal = calendar { calHash = cal.hashValue } if let tz = timeZone { calHash ^= tz.hashValue } var y = year if NSDateComponentUndefined == y { y = 0 } var m = month if NSDateComponentUndefined == m { m = 0 } var d = day if NSDateComponentUndefined == d { d = 0 } var h = hour if NSDateComponentUndefined == h { h = 0 } var mm = minute if NSDateComponentUndefined == mm { mm = 0 } var s = second if NSDateComponentUndefined == s { s = 0 } var yy = yearForWeekOfYear if NSDateComponentUndefined == yy { yy = 0 } return calHash + (32832013 * (y + yy) + 2678437 * m + 86413 * d + 3607 * h + 61 * mm + s) + (41 * weekOfYear + 11 * weekOfMonth + 7 * weekday + 3 * weekdayOrdinal + quarter) * (1 << 5) } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSDateComponents else { return false } return self === other || (era == other.era && year == other.year && quarter == other.quarter && month == other.month && day == other.day && hour == other.hour && minute == other.minute && second == other.second && nanosecond == other.nanosecond && weekOfYear == other.weekOfYear && weekOfMonth == other.weekOfMonth && yearForWeekOfYear == other.yearForWeekOfYear && weekday == other.weekday && weekdayOrdinal == other.weekdayOrdinal && isLeapMonth == other.isLeapMonth && calendar == other.calendar && timeZone == other.timeZone) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } self.init() self.era = aDecoder.decodeInteger(forKey: "NS.era") self.year = aDecoder.decodeInteger(forKey: "NS.year") self.quarter = aDecoder.decodeInteger(forKey: "NS.quarter") self.month = aDecoder.decodeInteger(forKey: "NS.month") self.day = aDecoder.decodeInteger(forKey: "NS.day") self.hour = aDecoder.decodeInteger(forKey: "NS.hour") self.minute = aDecoder.decodeInteger(forKey: "NS.minute") self.second = aDecoder.decodeInteger(forKey: "NS.second") self.nanosecond = aDecoder.decodeInteger(forKey: "NS.nanosec") self.weekOfYear = aDecoder.decodeInteger(forKey: "NS.weekOfYear") self.weekOfMonth = aDecoder.decodeInteger(forKey: "NS.weekOfMonth") self.yearForWeekOfYear = aDecoder.decodeInteger(forKey: "NS.yearForWOY") self.weekday = aDecoder.decodeInteger(forKey: "NS.weekday") self.weekdayOrdinal = aDecoder.decodeInteger(forKey: "NS.weekdayOrdinal") self.isLeapMonth = aDecoder.decodeBool(forKey: "NS.isLeapMonth") self.calendar = aDecoder.decodeObject(of: NSCalendar.self, forKey: "NS.calendar")?._swiftObject self.timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone")?._swiftObject } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.era, forKey: "NS.era") aCoder.encode(self.year, forKey: "NS.year") aCoder.encode(self.quarter, forKey: "NS.quarter") aCoder.encode(self.month, forKey: "NS.month") aCoder.encode(self.day, forKey: "NS.day") aCoder.encode(self.hour, forKey: "NS.hour") aCoder.encode(self.minute, forKey: "NS.minute") aCoder.encode(self.second, forKey: "NS.second") aCoder.encode(self.nanosecond, forKey: "NS.nanosec") aCoder.encode(self.weekOfYear, forKey: "NS.weekOfYear") aCoder.encode(self.weekOfMonth, forKey: "NS.weekOfMonth") aCoder.encode(self.yearForWeekOfYear, forKey: "NS.yearForWOY") aCoder.encode(self.weekday, forKey: "NS.weekday") aCoder.encode(self.weekdayOrdinal, forKey: "NS.weekdayOrdinal") aCoder.encode(self.isLeapMonth, forKey: "NS.isLeapMonth") aCoder.encode(self.calendar?._nsObject, forKey: "NS.calendar") aCoder.encode(self.timeZone?._nsObject, forKey: "NS.timezone") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let newObj = NSDateComponents() newObj.calendar = calendar newObj.timeZone = timeZone newObj.era = era newObj.year = year newObj.month = month newObj.day = day newObj.hour = hour newObj.minute = minute newObj.second = second newObj.nanosecond = nanosecond newObj.weekOfYear = weekOfYear newObj.weekOfMonth = weekOfMonth newObj.yearForWeekOfYear = yearForWeekOfYear newObj.weekday = weekday newObj.weekdayOrdinal = weekdayOrdinal newObj.quarter = quarter if leapMonthSet { newObj.isLeapMonth = isLeapMonth } return newObj } /*@NSCopying*/ open var calendar: Calendar? { get { return _calendar } set { if let val = newValue { _calendar = val } else { _calendar = nil } } } /*@NSCopying*/ open var timeZone: TimeZone? open var era: Int { get { return _values[0] } set { _values[0] = newValue } } open var year: Int { get { return _values[1] } set { _values[1] = newValue } } open var month: Int { get { return _values[2] } set { _values[2] = newValue } } open var day: Int { get { return _values[3] } set { _values[3] = newValue } } open var hour: Int { get { return _values[4] } set { _values[4] = newValue } } open var minute: Int { get { return _values[5] } set { _values[5] = newValue } } open var second: Int { get { return _values[6] } set { _values[6] = newValue } } open var weekday: Int { get { return _values[8] } set { _values[8] = newValue } } open var weekdayOrdinal: Int { get { return _values[9] } set { _values[9] = newValue } } open var quarter: Int { get { return _values[10] } set { _values[10] = newValue } } open var nanosecond: Int { get { return _values[11] } set { _values[11] = newValue } } open var weekOfYear: Int { get { return _values[12] } set { _values[12] = newValue } } open var weekOfMonth: Int { get { return _values[13] } set { _values[13] = newValue } } open var yearForWeekOfYear: Int { get { return _values[14] } set { _values[14] = newValue } } open var isLeapMonth: Bool { get { return _values[15] == 1 } set { _values[15] = newValue ? 1 : 0 } } internal var leapMonthSet: Bool { return _values[15] != NSDateComponentUndefined } /*@NSCopying*/ open var date: Date? { if let tz = timeZone { calendar?.timeZone = tz } return calendar?.date(from: self._swiftObject) } /* This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth properties cannot be set by this method. */ open func setValue(_ value: Int, forComponent unit: NSCalendar.Unit) { switch unit { case NSCalendar.Unit.era: era = value case NSCalendar.Unit.year: year = value case NSCalendar.Unit.month: month = value case NSCalendar.Unit.day: day = value case NSCalendar.Unit.hour: hour = value case NSCalendar.Unit.minute: minute = value case NSCalendar.Unit.second: second = value case NSCalendar.Unit.nanosecond: nanosecond = value case NSCalendar.Unit.weekday: weekday = value case NSCalendar.Unit.weekdayOrdinal: weekdayOrdinal = value case NSCalendar.Unit.quarter: quarter = value case NSCalendar.Unit.weekOfMonth: weekOfMonth = value case NSCalendar.Unit.weekOfYear: weekOfYear = value case NSCalendar.Unit.yearForWeekOfYear: yearForWeekOfYear = value case NSCalendar.Unit.calendar: print(".Calendar cannot be set via \(#function)") case NSCalendar.Unit.timeZone: print(".TimeZone cannot be set via \(#function)") default: break } } /* This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth property values cannot be gotten by this method. */ open func value(forComponent unit: NSCalendar.Unit) -> Int { switch unit { case NSCalendar.Unit.era: return era case NSCalendar.Unit.year: return year case NSCalendar.Unit.month: return month case NSCalendar.Unit.day: return day case NSCalendar.Unit.hour: return hour case NSCalendar.Unit.minute: return minute case NSCalendar.Unit.second: return second case NSCalendar.Unit.nanosecond: return nanosecond case NSCalendar.Unit.weekday: return weekday case NSCalendar.Unit.weekdayOrdinal: return weekdayOrdinal case NSCalendar.Unit.quarter: return quarter case NSCalendar.Unit.weekOfMonth: return weekOfMonth case NSCalendar.Unit.weekOfYear: return weekOfYear case NSCalendar.Unit.yearForWeekOfYear: return yearForWeekOfYear default: break } return NSDateComponentUndefined } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. The calendar property must be set, or NO is returned. */ open var isValidDate: Bool { if let cal = calendar { return isValidDate(in: cal) } return false } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. */ open func isValidDate(in calendar: Calendar) -> Bool { var cal = calendar if let tz = timeZone { cal.timeZone = tz } let ns = nanosecond if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns { return false } if ns != NSDateComponentUndefined && 0 < ns { nanosecond = 0 } let d = calendar.date(from: self._swiftObject) if ns != NSDateComponentUndefined && 0 < ns { nanosecond = ns } if let date = d { let all: NSCalendar.Unit = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear] let comps = calendar._bridgeToObjectiveC().components(all, from: date) var val = era if val != NSDateComponentUndefined { if comps.era != val { return false } } val = year if val != NSDateComponentUndefined { if comps.year != val { return false } } val = month if val != NSDateComponentUndefined { if comps.month != val { return false } } if leapMonthSet { if comps.isLeapMonth != isLeapMonth { return false } } val = day if val != NSDateComponentUndefined { if comps.day != val { return false } } val = hour if val != NSDateComponentUndefined { if comps.hour != val { return false } } val = minute if val != NSDateComponentUndefined { if comps.minute != val { return false } } val = second if val != NSDateComponentUndefined { if comps.second != val { return false } } val = weekday if val != NSDateComponentUndefined { if comps.weekday != val { return false } } val = weekdayOrdinal if val != NSDateComponentUndefined { if comps.weekdayOrdinal != val { return false } } val = quarter if val != NSDateComponentUndefined { if comps.quarter != val { return false } } val = weekOfMonth if val != NSDateComponentUndefined { if comps.weekOfMonth != val { return false } } val = weekOfYear if val != NSDateComponentUndefined { if comps.weekOfYear != val { return false } } val = yearForWeekOfYear if val != NSDateComponentUndefined { if comps.yearForWeekOfYear != val { return false } } return true } return false } } extension NSDateComponents : _SwiftBridgeable { typealias SwiftType = DateComponents var _swiftObject: SwiftType { return DateComponents(reference: self) } } extension DateComponents : _NSBridgeable { typealias NSType = NSDateComponents var _nsObject: NSType { return _bridgeToObjectiveC() } } extension NSCalendar: _SwiftBridgeable, _CFBridgeable { typealias SwiftType = Calendar var _swiftObject: SwiftType { return Calendar(reference: self) } } extension Calendar: _NSBridgeable, _CFBridgeable { typealias NSType = NSCalendar typealias CFType = CFCalendar var _nsObject: NSCalendar { return _bridgeToObjectiveC() } var _cfObject: CFCalendar { return _nsObject._cfObject } } extension CFCalendar : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSCalendar internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Calendar { return _nsObject._swiftObject } } extension NSCalendar : _StructTypeBridgeable { public typealias _StructType = Calendar public func _bridgeToSwift() -> Calendar { return Calendar._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateComponents : _StructTypeBridgeable { public typealias _StructType = DateComponents public func _bridgeToSwift() -> DateComponents { return DateComponents._unconditionallyBridgeFromObjectiveC(self) } }
apache-2.0
19977b94700441b487615043e004e476
43.468886
880
0.63001
5.043147
false
false
false
false
DikeyKing/WeCenterMobile-iOS
WeCenterMobile/View/Search/ArticleSearchResultCell.swift
1
1298
// // ArticleSearchResultCell.swift // WeCenterMobile // // Created by Darren Liu on 15/6/14. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import UIKit class ArticleSearchResultCell: UITableViewCell { @IBOutlet weak var containerView: UIView! @IBOutlet weak var badgeLabel: UILabel! @IBOutlet weak var articleTitleLabel: UILabel! @IBOutlet weak var articleButton: UIButton! override func awakeFromNib() { super.awakeFromNib() let theme = SettingsManager.defaultManager.currentTheme for v in [containerView, badgeLabel] { v.msr_borderColor = theme.borderColorA } containerView.backgroundColor = theme.backgroundColorB badgeLabel.backgroundColor = theme.backgroundColorA articleTitleLabel.textColor = theme.titleTextColor badgeLabel.textColor = theme.footnoteTextColor articleButton.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted) } func update(#dataObject: DataObject) { let article = dataObject as! Article articleTitleLabel.text = article.title ?? "" articleButton.msr_userInfo = article setNeedsLayout() layoutIfNeeded() } }
gpl-2.0
60702d7ae3f3f4f768507226665503e3
32.230769
99
0.699074
5.468354
false
false
false
false
DaftMobile/ios4beginners_2017
Class 2/Intermediate Swift.playground/Pages/Enums.xcplaygroundpage/Contents.swift
1
1762
import Foundation //: # Enums //: ### Basic Enumeration enum Compass { case north case south case east case west } var directionToGoFromHere = Compass.north print(directionToGoFromHere) directionToGoFromHere = .south // You could write Compass.north, but the compiler already knows the type of `directionToGoFromHere` print(directionToGoFromHere) //: ### Enum + Switch = 💪🏼 switch directionToGoFromHere { case .north: print("We're going north") case .south: print("Did you see the penguins?") case .east: print("The sun rises here") case .west: print("The sun sets here") } enum Planet { case mercury case venus case earth case mars case jupiter case saturn case uranus case neptune // case pluto 😢🌎 } let somePlanet: Planet = .earth //: Remember that switch statements must be exhaustive in Swift switch somePlanet { case .earth: print("Safe for humans") default: print("Not safe for humans!!! 💀") } //: ### Associated value enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } var productBarcode = Barcode.qrCode("ABCDEFGHIJKLMNOP") productBarcode = .upc(8, 85909, 51226, 3) switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): print("QR code: \(productCode).") } //: ### Enums with raw value enum CardSuit: Character { case clubs = "♣️" case diamonds = "♦️" case spades = "♠️" case hearts = "♥️" } let cardSuitOptional: CardSuit? = CardSuit(rawValue: "♦️") //print(cardSuitOptional?.rawValue) enum TrainStatus { case onTime case delayed(minutes: Int) } let status = TrainStatus.delayed(minutes: 10) //: [Next](@next)
apache-2.0
2d345cbe349ebe463994d538de09283f
17.569892
132
0.70469
3.399606
false
false
false
false
maicki/AsyncDisplayKit
examples_extra/Shop/Shop/Scenes/Products/ProductsCollectionViewController.swift
11
1904
// // ProductsCollectionViewController.swift // Shop // // Created by Dimitri on 15/11/2016. // Copyright © 2016 Dimitri. All rights reserved. // import UIKit class ProductsCollectionViewController: ASViewController<ASCollectionNode> { // MARK: - Variables var products: [Product] private var collectionNode: ASCollectionNode { return node } // MARK: - Object life cycle init(products: [Product]) { self.products = products super.init(node: ASCollectionNode(collectionViewLayout: ProductsLayout())) collectionNode.delegate = self collectionNode.dataSource = self collectionNode.backgroundColor = UIColor.primaryBackgroundColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() self.setupTitle() } } extension ProductsCollectionViewController: ASCollectionDataSource, ASCollectionDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.products.count } func collectionView(_ collectionView: ASCollectionView, nodeForItemAt indexPath: IndexPath) -> ASCellNode { let product = self.products[indexPath.row] return ProductCollectionNode(product: product) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let product = self.products[indexPath.row] let viewController = ProductViewController(product: product) self.navigationController?.pushViewController(viewController, animated: true) } } extension ProductsCollectionViewController { func setupTitle() { self.title = "Bears" } }
bsd-3-clause
6c74e49a3a9055f71d0d274d447ab3f4
26.57971
111
0.681555
5.286111
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/Swifter/Sources/SwifterHelp.swift
2
4773
// // SwifterHelp.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 public extension Swifter { /** GET help/configuration Returns the current configuration used by Twitter including twitter.com slugs which are not usernames, maximum photo resolutions, and t.co URL lengths. It is recommended applications request this endpoint when they are loaded, but no more than once a day. */ public func getHelpConfiguration(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "help/configuration.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure) } /** GET help/languages Returns the list of languages supported by Twitter along with their ISO 639-1 code. The ISO 639-1 code is the two letter value to use if you include lang with any of your requests. */ public func getHelpLanguages(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "help/languages.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) },failure: failure) } /** GET help/privacy Returns Twitter's Privacy Policy. */ public func getHelpPrivacy(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "help/privacy.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json["privacy"]) }, failure: failure) } /** GET help/tos Returns the Twitter Terms of Service in the requested format. These are not the same as the Developer Rules of the Road. */ public func getHelpTermsOfService(success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "help/tos.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json["tos"]) }, failure: failure) } /** GET application/rate_limit_status Returns the current rate limits for methods belonging to the specified resource families. Each 1.1 API resource belongs to a "resource family" which is indicated in its method documentation. You can typically determine a method's resource family from the first component of the path after the resource version. This method responds with a map of methods belonging to the families specified by the resources parameter, the current remaining uses for each of those resources within the current rate limiting window, and its expiration time in epoch time. It also includes a rate_limit_context field that indicates the current access token or application-only authentication context. You may also issue requests to this method without any parameters to receive a map of all rate limited GET methods. If your application only uses a few of methods, please explicitly provide a resources parameter with the specified resource families you work with. When using app-only auth, this method's response indicates the app-only auth rate limiting context. Read more about REST API Rate Limiting in v1.1 and review the limits. */ public func getRateLimits(for resources: [String], success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "application/rate_limit_status.json" let parameters = ["resources": resources.joined(separator: ",")] self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } }
mit
5d20c2b5ac267e6568b07cec43b78360
42.788991
373
0.705845
4.456583
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/MediaPicerControllerNew+ImagePicker.swift
1
5570
// // MediaPicerControllerNew+ImagePicker.swift // Pigeon-project // // Created by Roman Mizin on 11/20/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit import Photos import AssetsLibrary import MobileCoreServices import AVFoundation extension MediaPickerControllerNew { @objc func openPhotoLibrary() { imagePicker.sourceType = .photoLibrary presentImagePicker() } @objc func openCamera() { if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.sourceType = .camera presentImagePicker() } else { let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) alert.modalPresentationStyle = .overCurrentContext present(alert, animated: true, completion: nil) } } override func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if picker.sourceType == UIImagePickerController.SourceType.camera { if let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String { if mediaType == "public.image" { guard let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } PHPhotoLibrary.shared().performChanges ({ PHAssetChangeRequest.creationRequestForAsset(from: originalImage) }, completionHandler: { (isSaved, _) in guard isSaved else { self.delegate?.controller?(self, didTakeImage: originalImage) self.dismissImagePicker() return } let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] options.fetchLimit = 1 let result = PHAsset.fetchAssets(with: options) let asset = result.firstObject self.reFetchAssets(completionHandler: { (isCompleted) in if isCompleted { self.delegate?.controller?(self, didTakeImage: originalImage, with: asset!) self.dismissImagePicker() } }) }) } if mediaType == "public.movie" { if let pickedVideo = info[UIImagePickerController.InfoKey.mediaURL] as? URL { PHPhotoLibrary.shared().performChanges ({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: pickedVideo) }) { isSaved, _ in guard isSaved else { let alertMessage = videoRecordedButLibraryUnavailableError self.dismissImagePicker() basicErrorAlertWith(title: basicTitleForAccessError, message: alertMessage, controller: self) return } let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] options.fetchLimit = 1 let result = PHAsset.fetchAssets(with: options) let asset = result.firstObject self.reFetchAssets(completionHandler: { (isCompleted) in if isCompleted { self.delegate?.controller?(self, didRecordVideoAsset: asset!) self.dismissImagePicker() } }) } } } } } else { if let imageURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL { let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil) let asset = result.firstObject guard let selectedIndexPaths = self.collectionView.indexPathsForSelectedItems else { return } for selectedIndexPath in selectedIndexPaths where self.assets[selectedIndexPath.item] == asset { // if { print("you selected already selected image") dismissImagePicker() return // } } guard let indexForSelection = self.assets.firstIndex(where: { (phAsset) -> Bool in return phAsset == asset }) else { print("you selected image which is not in preview, processing...") self.delegate?.controller?(self, didSelectAsset: asset!, at: nil) dismissImagePicker() return } print("you selected not selected image, selecting...") let indexPathForSelection = IndexPath(item: indexForSelection, section: ImagePickerTrayController.librarySectionIndex) self.collectionView.selectItem(at: indexPathForSelection, animated: false, scrollPosition: .left) self.delegate?.controller?(self, didSelectAsset: asset!, at: indexPathForSelection) dismissImagePicker() } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismissImagePicker() } func presentImagePicker() { imagePicker.modalPresentationStyle = .overCurrentContext present(imagePicker, animated: true) { self.imagePicker.navigationBar.layoutSubviews() } } func dismissImagePicker () { dismiss(animated: true, completion: nil) } }
gpl-3.0
0102f505e7b39b8a79f6d40918e6d75a
34.246835
126
0.610163
5.776971
false
false
false
false
cliqz-oss/browser-ios
Client/Cliqz/Frontend/Browser/Settings/SendTelemetrySetttingsController.swift
1
1590
// // SendTelemetrySetttingsController.swift // Client // // Created by Sahakyan on 5/8/18. // Copyright © 2018 Mozilla. All rights reserved. // import Foundation class SendTelemetrySettingsController: SubSettingsTableViewController { private lazy var toggle: Bool = SettingsPrefs.shared.getSendTelemetryPref() override func getSectionFooter(section: Int) -> String { return NSLocalizedString("Send Telemetry footer", tableName: "Cliqz", comment: "[Settings -> Send Telemetry] Footer text") } override func getViewName() -> String { return "send_telemetry" } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = getUITableViewCell() cell.textLabel?.text = self.title let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggle control.accessibilityLabel = "send telemetry" cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.item return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView_ : UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } @objc func switchValueChanged(_ toggle: UISwitch) { self.toggle = toggle.isOn SettingsPrefs.shared.updateSendTelemetryPref(self.toggle) // log telemetry signal // let state = toggle.isOn == true ? "off" : "on" // we log old value } }
mpl-2.0
56d9492b69183a609b9bdad418152927
28.981132
124
0.740088
4.095361
false
false
false
false
MaxHasADHD/TraktKit
Common/Models/Sync/TraktCollectedItem.swift
1
6401
// // TraktCollectedItem.swift // TraktKit // // Created by Maximilian Litteral on 10/21/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktCollectedItem: Codable, Hashable { public var lastCollectedAt: Date public let lastUpdatedAt: Date public var movie: TraktMovie? public var show: TraktShow? public var seasons: [TraktCollectedSeason]? public var metadata: Metadata? enum MovieCodingKeys: String, CodingKey { case lastCollectedAt = "collected_at" case lastUpdatedAt = "updated_at" case movie case metadata } enum ShowCodingKeys: String, CodingKey { case lastCollectedAt = "last_collected_at" case lastUpdatedAt = "last_updated_at" case show case seasons case metadata } public init(from decoder: Decoder) throws { if let movieContainer = try? decoder.container(keyedBy: MovieCodingKeys.self), !movieContainer.allKeys.isEmpty { movie = try movieContainer.decodeIfPresent(TraktMovie.self, forKey: .movie) lastUpdatedAt = try movieContainer.decode(Date.self, forKey: .lastUpdatedAt) lastCollectedAt = try movieContainer.decode(Date.self, forKey: .lastCollectedAt) metadata = try movieContainer.decodeIfPresent(Metadata.self, forKey: .metadata) } else { let showContainer = try decoder.container(keyedBy: ShowCodingKeys.self) show = try showContainer.decodeIfPresent(TraktShow.self, forKey: .show) seasons = try showContainer.decodeIfPresent([TraktCollectedSeason].self, forKey: .seasons) lastUpdatedAt = try showContainer.decode(Date.self, forKey: .lastUpdatedAt) lastCollectedAt = try showContainer.decode(Date.self, forKey: .lastCollectedAt) metadata = nil } } public func encode(to encoder: Encoder) throws { if let movie = movie { var container = encoder.container(keyedBy: MovieCodingKeys.self) try container.encodeIfPresent(movie, forKey: .movie) try container.encode(lastCollectedAt, forKey: .lastCollectedAt) try container.encode(lastUpdatedAt, forKey: .lastUpdatedAt) } else { var container = encoder.container(keyedBy: ShowCodingKeys.self) try container.encodeIfPresent(show, forKey: .show) try container.encodeIfPresent(seasons, forKey: .seasons) try container.encode(lastCollectedAt, forKey: .lastCollectedAt) try container.encode(lastUpdatedAt, forKey: .lastUpdatedAt) } } public struct Metadata: Codable, Hashable { public let mediaType: MediaType? public let resolution: Resolution? public let hdr: HDR? public let audio: Audio? public let audioChannels: AudioChannels? public let is3D: Bool enum CodingKeys: String, CodingKey { case mediaType = "media_type" case resolution case hdr case audio case audioChannels = "audio_channels" case is3D = "3d" } /// Custom decoder to fail silently if Trakt adds new metadata option. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) mediaType = try? container.decodeIfPresent(MediaType.self, forKey: .mediaType) resolution = try? container.decodeIfPresent(Resolution.self, forKey: .resolution) hdr = try? container.decodeIfPresent(HDR.self, forKey: .hdr) audio = try? container.decodeIfPresent(Audio.self, forKey: .audio) audioChannels = try? container.decodeIfPresent(AudioChannels.self, forKey: .audioChannels) is3D = try container.decodeIfPresent(Bool.self, forKey: .is3D) ?? false } } public enum MediaType: String, Codable { case digital case bluray case hdDVD = "hddvd" case dvd case laserDisc = "laserdisc" case vhs case betamax case videoCD = "vcd" } public enum Resolution: String, Codable { case udh4k = "uhd_4k" case hd1080p = "hd_1080p" case hd1080i = "hd_1080i" case hd720p = "hd_720p" case sd480p = "sd_480p" case sd480i = "sd_480i" case sd576p = "sd_576p" case sd576i = "sd_576i" } public enum HDR: String, Codable { case dolbyVision = "dolby_vision" case hdr10 = "hdr10" case hdr10Plus = "hdr10_plus" case hlg } public enum Audio: String, Codable { case dolbyDigital = "dolby_digital" case dolbyDigitalPlus = "dolby_digital_plus" case dolbyDigitalPlusAtmos = "dolby_digital_plus_atmos" case dolbyAtmos = "dolby_atmos" case dolbyTrueHD = "dolby_truehd" case dolbyTrueHDAtmos = "dolby_truehd_atmos" case dolbyProLogic = "dolby_prologic" case dts case dtsHDMA = "dts_ma" case dtsHDHR = "dts_hr" case dtsX = "dts_x" case auro3D = "auro_3d" case mp3 case mp2 case aac case lpcm case ogg case wma case flac } public enum AudioChannels: String, Codable { case tenOne = "10.1" case nineOne = "9.1" case sevenOneFour = "7.1.4" case sevenOneTwo = "7.1.2" case sevenOne = "7.1" case sixOne = "6.1" case fiveOneFour = "5.1.4" case fiveOneTwo = "5.1.2" case fiveOne = "5.1" case five = "5.0" case fourOne = "4.1" case four = "4.0" case threeOne = "3.1" case three = "3.0" case twoOne = "2.1" case two = "2.0" case one = "1.0" } } public struct TraktCollectedSeason: Codable, Hashable { /// Season number public var number: Int public var episodes: [TraktCollectedEpisode] } public struct TraktCollectedEpisode: Codable, Hashable { public var number: Int public var collectedAt: Date public var metadata: TraktCollectedItem.Metadata? enum CodingKeys: String, CodingKey { case number case collectedAt = "collected_at" case metadata } }
mit
d66fe8d5aba701592cabfab29a0a1b7d
33.408602
120
0.615625
4.315577
false
false
false
false
webim/webim-client-sdk-ios
Example/WebimClientLibrary/Extensions/UITableView.swift
1
4155
// // UITableView.swift // WebimClientLibrary_Example // // Created by Nikita Lazarev-Zubov on 03.01.18. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit extension UITableView { // MARK: - Methods func emptyTableView(message: String) { let messageLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: self.bounds.size.width, height: self.bounds.size.height)) messageLabel.attributedText = NSAttributedString(string: message) messageLabel.textColor = textMainColour messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.sizeToFit() self.backgroundView = messageLabel self.separatorStyle = .none } func scrollToRowSafe(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { if indexPath.section >= 0 && indexPath.row >= 0 && self.numberOfSections > indexPath.section && self.numberOfRows(inSection: indexPath.section) > indexPath.row { self.scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } } private var AssociatedObjectHandle: UInt8 = 0 extension UITableView { var registeredCellsSet: Set<String> { get { let set = objc_getAssociatedObject(self, &AssociatedObjectHandle) as? Set<String> if let set = set { return set } else { self.registeredCellsSet = Set<String>() return self.registeredCellsSet } } set { objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func identifierRegistered(_ identifier: String) -> Bool { return self.registeredCellsSet.contains(identifier) } private func registerCellWithType<T>(_ type: T.Type) { let identifier = "\(type)" self.registeredCellsSet.insert(identifier) if Bundle.main.path(forResource: identifier, ofType: "nib") != nil { self.register(UINib(nibName: identifier, bundle: nil), forCellReuseIdentifier: identifier) } else { self.register(PopupActionsTableViewCell.self, forCellReuseIdentifier: identifier) } } public func dequeueReusableCellWithType<T>(_ type: T.Type) -> T { let identifier = "\(type)" if !self.identifierRegistered(identifier) { self.registerCellWithType(type) } guard let cell = self.dequeueReusableCell(withIdentifier: identifier) as? T else { let logMessage = "Cast dequeueReusableCell with identifier \(identifier) to \(type) failure in DialogController.\(#function)" print(logMessage) fatalError(logMessage) } return cell } }
mit
5c4b4696dc3861b5c5747a44357c112d
38.942308
137
0.642513
4.951132
false
false
false
false
blstream/AugmentedSzczecin_iOS
AugmentedSzczecin/AugmentedSzczecin/ASSearchViewController.swift
1
4298
// // ASSearchViewController.swift // AugmentedSzczecin // // Created by Patronage on 16.04.2015. // Copyright (c) 2015 BLStream. All rights reserved. // import UIKit import CoreData class ASSearchViewController: UITableViewController, UISearchResultsUpdating, NSFetchedResultsControllerDelegate { var resultSearchController = UISearchController() lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "ASPOI") let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] let frc = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: ASData.sharedInstance.mainContext!, sectionNameKeyPath: "ASPOI.id", cacheName: nil) frc.delegate = self return frc }() override func viewDidLoad() { super.viewDidLoad() self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: Selector("dismissViewController")) self.tableView.reloadData() } func dismissViewController() { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidAppear(animated: Bool) { } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.numberOfObjects } return 0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.name } return nil } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ASSearchCell", forIndexPath: indexPath) as! UITableViewCell let poi = fetchedResultsController.objectAtIndexPath(indexPath) as! ASPOI cell.textLabel?.text = poi.name cell.detailTextLabel?.text = poi.tag return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("ShowDetailSegue", sender: fetchedResultsController.objectAtIndexPath(indexPath)) } func updateSearchResultsForSearchController(searchController: UISearchController) { if (searchController.searchBar.text != "") { var predicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text) fetchedResultsController.fetchRequest.predicate = predicate fetchedResultsController.fetchRequest.fetchLimit = 25 } else { fetchedResultsController.fetchRequest.predicate = nil } self.tableView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowDetailSegue") { var destination = segue.destinationViewController as! ASPointDetailViewController destination.POI = sender as? ASPOI } } }
apache-2.0
0a6bffa01b11506b8f4c6dd540db311e
34.825
171
0.662168
6.502269
false
false
false
false
SusanDoggie/DoggieGP
Playground/OpenCL.playground/Contents.swift
1
1200
//: Playground - noun: a place where people can play import Cocoa import Doggie import DoggieGP if let platform = OpenCL.default { let source = """ __kernel void foo(__global char *a) { const uint i = get_global_id(0); a[i] *= 2; } """ let buf = MappedBuffer<Int8>(repeating: 1, count: 10) let library = platform.library(source: source) if let device = platform.devices.first { print(device.maxThreadsPerThreadgroup) let queue = device.makeCommandQueue() do { try library.build(device) } catch let error as OpenCL.BuildError { print(error.message) } queue.commit { context in let function = library.function(name: "foo") function.maxTotalThreadsPerThreadgroup(with: device) function.preferredThreadgroupSizeMultiple(with: device) context.perform(threadgroups: DGPSize(length: 10), threadsPerThreadgroup: DGPSize(length: 1), function: function, buf) } } print(buf) }
mit
3f4636e8affca94019a5e2ea5afd8b48
24
130
0.545833
4.819277
false
false
false
false
lukerdeluker/bagabaga
Source/Result.swift
1
11016
// // Result.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Used to represent whether a request was successful or encountered an error. /// /// - success: The request and all post processing operations were successful resulting in the serialization of the /// provided associated value. /// /// - failure: The request encountered an error resulting in a failure. The associated values are the original data /// provided by the server as well as the error that caused the failure. public enum Result<Value> { case success(Value) case rise(fire) case failure(Error) /// Returns `true` if the result is a success, `false` otherwise. public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } /// Returns `true` if the result is a failure, `false` otherwise. public var isFailure: Bool { return !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { case .success(let value): return value case .failure: return nil } } /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { case .success: return nil case .failure(let error): return error } } } // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { case .success: return "SUCCESS" case .failure: return "FAILURE" } } } // MARK: - CustomDebugStringConvertible extension Result: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes whether the result was a /// success or failure in addition to the value or error. public var debugDescription: String { switch self { case .success(let value): return "SUCCESS: \(value)" case .failure(let error): return "FAILURE: \(error)" } } } // MARK: - Functional APIs extension Result { /// Creates a `Result` instance from the result of a closure. /// /// A failure result is created when the closure throws, and a success result is created when the closure /// succeeds without throwing an error. /// /// func someString() throws -> String { ... } /// /// let result = Result(value: { /// return try someString() /// }) /// /// // The type of result is Result<String> /// /// The trailing closure syntax is also supported: /// /// let result = Result { try someString() } /// /// - parameter value: The closure to execute and create the result for. public init(value: () throws -> Value) { do { self = try .success(value()) } catch { self = .failure(error) } } /// Returns the success value, or throws the failure error. /// /// let possibleString: Result<String> = .success("success") /// try print(possibleString.unwrap()) /// // Prints "success" /// /// let noString: Result<String> = .failure(error) /// try print(noString.unwrap()) /// // Throws error public func unwrap() throws -> Value { switch self { case .success(let value): return value case .failure(let error): throw error } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: Result<Data> = .success(Data()) /// let possibleInt = possibleData.map { $0.count } /// try print(possibleInt.unwrap()) /// // Prints "0" /// /// let noData: Result<Data> = .failure(error) /// let noInt = noData.map { $0.count } /// try print(noInt.unwrap()) /// // Throws error /// /// - parameter transform: A closure that takes the success value of the `Result` instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. public func map<T>(_ transform: (Value) -> T) -> Result<T> { switch self { case .success(let value): return .success(transform(value)) case .failure(let error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: Result<Data> = .success(Data(...)) /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T> { switch self { case .success(let value): do { return try .success(transform(value)) } catch { return .failure(error) } case .failure(let error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `mapError` function with a closure that does not throw. For example: /// /// let possibleData: Result<Data> = .failure(someError) /// let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) } /// /// - Parameter transform: A closure that takes the error of the instance. /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same instance. public func mapError<T: Error>(_ transform: (Error) -> T) -> Result { switch self { case .failure(let error): return .failure(transform(error)) case .success: return self } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `flatMapError` function with a closure that may throw an error. For example: /// /// let possibleData: Result<Data> = .success(Data(...)) /// let possibleObject = possibleData.flatMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same instance. public func flatMapError<T: Error>(_ transform: (Error) throws -> T) -> Result { switch self { case .failure(let error): do { return try .failure(transform(error)) } catch { return .failure(error) } case .success: return self } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A closure that takes the success value of this instance. /// - Returns: This `Result` instance, unmodified. @discardableResult public func withValue(_ closure: (Value) -> Void) -> Result { if case let .success(value) = self { closure(value) } return self } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A closure that takes the success value of this instance. /// - Returns: This `Result` instance, unmodified. @discardableResult public func withError(_ closure: (Error) -> Void) -> Result { if case let .failure(error) = self { closure(error) } return self } /// Evaluates the specified closure when the `Result` is a success. /// /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A `Void` closure. /// - Returns: This `Result` instance, unmodified. @discardableResult public func ifSuccess(_ closure: () -> Void) -> Result { if isSuccess { closure() } return self } /// Evaluates the specified closure when the `Result` is a failure. /// /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A `Void` closure. /// - Returns: This `Result` instance, unmodified. @discardableResult public func ifFailure(_ closure: () -> Void) -> Result { if isFailure { closure() } return self } }
mit
7663a573499988aeb3c4ae4b30f68922
35.598007
119
0.611656
4.595745
false
false
false
false
steverab/WWDC-2015
Stephan Rabanser/TimelineViewController.swift
1
14063
// // TimelineViewController.swift // Stephan Rabanser // // Created by Stephan Rabanser on 17/04/15. // Copyright (c) 2015 Stephan Rabanser. All rights reserved. // import UIKit import MessageUI class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate { @IBOutlet weak var timelineTableView: UITableView! @IBOutlet var header:UIView! @IBOutlet var headerLabel:UILabel! @IBOutlet var headerDetailLabel:UILabel! @IBOutlet weak var avatarView: AvatarView! @IBOutlet weak var avatarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var avatarWidthConstraint: NSLayoutConstraint! @IBOutlet weak var avatarLeftConstraint: NSLayoutConstraint! @IBOutlet weak var avatarTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! var headerImageView:UIImageView! var headerBlurImageView:UIImageView! var blurredHeaderImageView:UIImageView? let offsetHeaderStop:CGFloat = 65.5 let offsetLabelHeader:CGFloat = 65.0 let offsetAvatarHeader:CGFloat = 0.0 let blurFadeDuration:CGFloat = 94.0 let avatarWidth:CGFloat = 76.0 var entries = [Entry]() var me = Me() // MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() navigationController?.interactivePopGestureRecognizer.delegate = nil navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) avatarView.action = { [unowned self] in self.setupActionSheet() } me = DataLoader.loadMe() setupStartAnimation() setupHeader() setupTableView() entries = DataLoader.loadTimelineEntries() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) if let index = timelineTableView.indexPathForSelectedRow() { timelineTableView.deselectRowAtIndexPath(index, animated: true) } } // MARK: Custom functions func setupStartAnimation() { avatarHeightConstraint.constant = 0 avatarWidthConstraint.constant = 0 avatarTopConstraint.constant += avatarWidth/2 avatarLeftConstraint.constant += avatarWidth/2 self.avatarView.setNeedsUpdateConstraints() self.avatarView.layoutIfNeeded() avatarHeightConstraint.constant = avatarWidth avatarWidthConstraint.constant = avatarWidth avatarTopConstraint.constant -= avatarWidth/2 avatarLeftConstraint.constant -= avatarWidth/2 self.avatarView.setNeedsUpdateConstraints() timelineTableView.alpha = 0.0 header.alpha = 0.0 UIView.animateWithDuration(1.0, delay: 0.1, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.CurveEaseInOut, animations: ({ self.avatarView.layoutIfNeeded() }), completion: nil) UIView.animateWithDuration(1.0, animations: { () -> Void in self.timelineTableView.alpha = 1.0 self.header.alpha = 1.0 }) } func setupHeader() { let headerImg: UIImage! headerImageView = UIImageView(frame: CGRectMake(0.0, 0.0, header.frame.size.width, header.frame.size.height)) headerImageView.contentMode = UIViewContentMode.ScaleAspectFit headerImageView.backgroundColor = UIColor.redColor() headerImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight header.insertSubview(headerImageView, belowSubview: headerLabel) headerBlurImageView = UIImageView(frame: headerImageView.frame) headerBlurImageView.contentMode = UIViewContentMode.ScaleAspectFit headerBlurImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight headerBlurImageView.alpha = 0.0 header.insertSubview(headerBlurImageView, belowSubview: headerLabel) if view.frame.size.width >= 375.0 { headerImg = UIImage(named: "MiamiHeader") headerBlurImageView.image = headerImg?.blurredImageWithRadius(8, iterations: 20, tintColor: UIColor.clearColor()) } else { headerImg = UIImage(named: "MiamiHeader5") headerBlurImageView.image = headerImg?.blurredImageWithRadius(8, iterations: 20, tintColor: UIColor.clearColor()) } headerImageView.image = headerImg headerDetailLabel.text = me.shortDescription header.clipsToBounds = true } func setupTableView() { timelineTableView.dataSource = self timelineTableView.delegate = self timelineTableView.separatorStyle = .None timelineTableView.rowHeight = UITableViewAutomaticDimension timelineTableView.estimatedRowHeight = 44 timelineTableView.contentInset = UIEdgeInsetsMake(131, 0, 0, 0) } // MARK: - UIScrollView delegate func scrollViewDidScroll(scrollView: UIScrollView) { let offset = scrollView.contentOffset.y + timelineTableView.contentInset.top var avatarTransform = CATransform3DIdentity var headerTransform = CATransform3DIdentity if offset == 0 { avatarView.userInteractionEnabled = true } else { avatarView.userInteractionEnabled = false } if offset < 0 { let headerScaleFactor:CGFloat = -(offset) / header.bounds.height let headerSizevariation = ((header.bounds.height * (1.0 + headerScaleFactor)) - header.bounds.height)/2.0 headerTransform = CATransform3DTranslate(headerTransform, 0, headerSizevariation, 0) headerTransform = CATransform3DScale(headerTransform, 1.0 + headerScaleFactor, 1.0 + headerScaleFactor, 0) avatarTransform = CATransform3DMakeTranslation(0, -offset, 0) headerBlurImageView.alpha = -offset/150 } else { headerTransform = CATransform3DTranslate(headerTransform, 0, max(-offsetHeaderStop, -offset), 0) let labelTransform = CATransform3DMakeTranslation(0, max(-blurFadeDuration, offsetLabelHeader - offset), 0) headerLabel.layer.transform = labelTransform headerDetailLabel.layer.transform = labelTransform avatarTransform = CATransform3DMakeTranslation(0, max(-blurFadeDuration - 30, offsetAvatarHeader - offset), 0) headerBlurImageView.alpha = min (1.0, (offset - offsetLabelHeader)/blurFadeDuration) let avatarScaleFactor = (min(offsetHeaderStop, offset)) / avatarView.bounds.height / 1.25 let avatarSizeVariation:CGFloat = ((avatarView.bounds.height * (1.0 + avatarScaleFactor)) - avatarView.bounds.height) / 2.0 avatarTransform = CATransform3DTranslate(avatarTransform, 0, avatarSizeVariation, 0) avatarTransform = CATransform3DScale(avatarTransform, 1.0 - avatarScaleFactor, 1.0 - avatarScaleFactor, 0) if offset <= offsetHeaderStop { if avatarView.layer.zPosition < header.layer.zPosition{ header.layer.zPosition = 0 } } else { if avatarView.layer.zPosition >= header.layer.zPosition{ header.layer.zPosition = 2 } } } header.layer.transform = headerTransform avatarView.transform = CGAffineTransformMake(avatarTransform.m11, avatarTransform.m12, avatarTransform.m21, avatarTransform.m22, avatarTransform.m41, avatarTransform.m42) } // MARK: - UITableView data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return entries.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { var cell = tableView.dequeueReusableCellWithIdentifier("ProfileCell") as! ProfileCell configureProfileCell(cell, forIndexPath: indexPath) return cell } else { var cell = tableView.dequeueReusableCellWithIdentifier("TimelineEntryCell") as! TimelineEntryCell configureEntryCell(cell, forIndexPath: indexPath, isForOffscreenUse: false) return cell } } // MARK: Custom functions func configureProfileCell(cell: ProfileCell, forIndexPath indexPath: NSIndexPath) { cell.nameLabel.text = me.name cell.descriptionLabel.text = me.shortDescription cell.outlineView.type = .NoCircle cell.selectionStyle = .None cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() } func configureEntryCell(cell: TimelineEntryCell, forIndexPath indexPath: NSIndexPath, isForOffscreenUse offscreenUse: Bool) { let currentEntry:Entry currentEntry = entries[indexPath.row-1] cell.titleLabel.text = currentEntry.title cell.shortDescriptionLabel.text = currentEntry.shortDescription cell.dateLabel.text = currentEntry.date cell.type = currentEntry.type if indexPath.row == 1 { cell.outlineView.type = .First } else if indexPath.row == entries.count { cell.outlineView.type = .Last } else { cell.outlineView.type = .Default } cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() } // MARK: - UITableView delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } // MARK: Custom functions func setupActionSheet() { let alertController = UIAlertController(title: nil, message: "Get in touch with me!", preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in } alertController.addAction(cancelAction) let emailAction = UIAlertAction(title: "E-Mail", style: .Default) { (action) in let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients([self.me.email]) mailComposerVC.setSubject("Hey there!") mailComposerVC.setMessageBody("Hi Stephan,\n\n", isHTML: false) if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposerVC, animated: true, completion: nil) } else { let sendMailErrorAlert = UIAlertView(title: "Error", message: "E-Mail sending failed. Please check your E-Mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } } alertController.addAction(emailAction) let twitterAction = UIAlertAction(title: "Twitter", style: .Default) { (action) in if !UIApplication.sharedApplication().openURL(NSURL(string:"twitter://user?screen_name=\(self.me.twitter)")!){ if let destinationViewController = self.storyboard!.instantiateViewControllerWithIdentifier("navigationWebViewController") as? UINavigationController { if let webViewController = destinationViewController.viewControllers.first as? WebViewController { webViewController.url = NSURL(string:"https://twitter.com/steverab")! self.navigationController?.presentViewController(destinationViewController, animated: true, completion: { () -> Void in }) } } } } alertController.addAction(twitterAction) let websiteAction = UIAlertAction(title: "Website", style: .Default) { (action) in if let destinationViewController = self.storyboard!.instantiateViewControllerWithIdentifier("navigationWebViewController") as? UINavigationController { if let webViewController = destinationViewController.viewControllers.first as? WebViewController { webViewController.url = NSURL(string:"http://\(self.me.website)")! self.navigationController?.presentViewController(destinationViewController, animated: true, completion: { () -> Void in }) } } } alertController.addAction(websiteAction) self.presentViewController(alertController, animated: true) {} } // MARK: - MFMailComposeViewController delegate func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { controller.dismissViewControllerAnimated(true, completion: nil) } // MARK: - Navigation handling override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let detailViewController = segue.destinationViewController as! DetailViewController let indexPath = timelineTableView.indexPathForSelectedRow()?.row if let indexPath = indexPath { detailViewController.timelineEntry = entries[indexPath - 1] } } // MARK: - Memory management override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
98fb7d00e29d79e4b30808172e2f9360
42.138037
198
0.664439
5.8841
false
false
false
false
nathantannar4/NTComponents
NTComponents Demo/AppDelegate.swift
1
4348
// // AppDelegate.swift // NTComponents Demo // // Created by Nathan Tannar on 4/15/17. // Copyright © 2017 Nathan Tannar. All rights reserved. // import UIKit import NTComponents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /// Set your preferred colors Color.Default.setPrimary(to: UIColor(hex: "31485e")) Color.Default.setSecondary(to: .white) Color.Default.setTertiary(to: UIColor(hex: "baa57b")) Color.Default.Background.ViewController = Color.Gray.P100 /// Set a specific default Color.Default.Tint.Toolbar = UIColor(hex: "31485e") /// Set shadow preverence // Color.Default.setCleanShadow() /// Set your preferred font Font.Default.Title = Font.Roboto.Medium.withSize(15) Font.Default.Subtitle = Font.Roboto.Regular Font.Default.Body = Font.Roboto.Regular.withSize(13) Font.Default.Caption = Font.Roboto.Medium.withSize(12) Font.Default.Subhead = Font.Roboto.Light.withSize(14) Font.Default.Headline = Font.Roboto.Medium.withSize(15) Font.Default.Callout = Font.Roboto.Regular.withSize(15) Font.Default.Footnote = Font.Roboto.Light.withSize(12) /// Setting trace level to MAX Log.setTraceLevel(to: .debug) window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = .white /// Creating a slide show controller var items = [NTOnboardingDataSet(image: #imageLiteral(resourceName: "NT Components Banner"), title: "NTComponents", subtitle: "Demo", body: "Here lies source code examples to demonstrate how easy it is to make beautiful apps with NTComponents")] for _ in 0...2 { let randomItem = NTOnboardingDataSet(image: #imageLiteral(resourceName: "NT Components Banner"), title: Lorem.words(nbWords: 3), subtitle: Lorem.sentence(), body: Lorem.paragraph()) items.append(randomItem) } let root = NTOnboardingViewController(dataSource: NTOnboardingDatasource(withValues: items)) /// Set completion to our login page root.completionViewController = NTNavigationController(rootViewController: LoginViewController()) /// Skip showing slide show window?.rootViewController = root.completionViewController 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:. } }
mit
2a9b199abab8bd71d64859d03827dfe2
47.3
285
0.700483
5.126179
false
false
false
false
guoc/excerptor
Excerptor/Helpers/error-helper.swift
1
3964
// // error-helper.swift // excerptor // // Created by Chen Guo on 17/05/2015. // Copyright (c) 2015 guoc. All rights reserved. // func printToStandardError(_ string: String) { let stderr = FileHandle.standardError let stringWithAppInfo = "Excerptor: \(string)" stderr.write(stringWithAppInfo.data(using: String.Encoding.utf8, allowLossyConversion: false)!) } func printlnToStandardError(_ string: String) { printToStandardError("\(string)\n") } var runningInCLI = false func exitWithError(_ err: String) -> Never { if runningInCLI { printlnToStandardError(err) exit(1) } else { notifyWithError("Excerptor error", informativeText: err) fatalError(err) } } private let userNotificationCenterDelegate = UserNotificationCenterDelegate() private struct Constants { static let PDFFilePathToRevealInFinder = "PDFFilePathToRevealInFinder" } func notifyWithUserNotification(_ userNotification: NSUserNotification) { if runningInCLI { var err = "" if let title = userNotification.title { err += "\(title)\n" } if let subtitle = userNotification.subtitle { err += "\(subtitle)\n" } if let informativeText = userNotification.informativeText { err += "\(informativeText)\n" } if let userInfo = userNotification.userInfo { err += userInfo.values.map { $0 as? String ?? "" }.joined(separator: "\n") err += "\n" } printlnToStandardError(err) } else { let userNotificationCenter = NSUserNotificationCenter.default userNotificationCenter.delegate = userNotificationCenterDelegate userNotificationCenter.deliver(userNotification) } } func notifyWithError(_ err: String, informativeText: String?) { let userNotification = NSUserNotification() let errComponents = err.components(separatedBy: "\n") switch errComponents.count { case 1: userNotification.title = errComponents[0] case 2: userNotification.title = errComponents[0] userNotification.subtitle = errComponents[1] default: userNotification.title = err } userNotification.informativeText = informativeText userNotification._ignoresDoNotDisturb = true notifyWithUserNotification(userNotification) } func notifyPDFFileNotFoundInDNtpWith(_ filePath: String, replacingPlaceholder: String) { let userNotification = NSUserNotification() userNotification.title = "Could Not Find The PDF File In DEVONthink" userNotification.subtitle = "\(replacingPlaceholder) applied instead" userNotification.informativeText = URL(fileURLWithPath: filePath).lastPathComponent let path = URL(fileURLWithPath: filePath).standardizedFileURL.path userNotification.userInfo = [Constants.PDFFilePathToRevealInFinder: path] userNotification._ignoresDoNotDisturb = true notifyWithUserNotification(userNotification) } class UserNotificationCenterDelegate: NSObject, NSUserNotificationCenterDelegate { // Notifications may be suppressed if the application is already frontmost, // this extension is to make sure notifications can be showed in this case, // although the case doesn't happen. func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true } // Prevent from showing preferences window when users click on notification. func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) { PreferencesWindowController.needShowPreferences = false if let userInfo = notification.userInfo, let filePath = userInfo[Constants.PDFFilePathToRevealInFinder] as? String { let url = URL(fileURLWithPath: filePath, isDirectory: false) NSWorkspace.shared.activateFileViewerSelecting([url]) } } }
mit
351a323bd6c61cd8369c5c435ee247dc
36.046729
125
0.71443
5.195282
false
false
false
false
surik00/RocketWidget
RocketWidget/Model/Structs/JSONTemplates/RocketResponseModels.swift
1
2802
// // RocketResponseModels.swift // RocketWidget // // Created by Suren Khorenyan on 01.10.17. // Copyright © 2017 Suren Khorenyan. All rights reserved. // import Foundation struct Coordinate: Decodable { var latitude: Double? var longitude: Double? var acc: Double? } struct MoneySpent: Decodable { var amount: Double var currency: String enum CodingKeys: String, CodingKey { case currency = "currency_code" case amount } } struct MerchantCategory: Decodable { var id: String var name: String enum CodingKeys: String, CodingKey { case id = "sub_icon" case name = "display_name" } } struct Merchant: Decodable { var id: Int var name: String var icon: URL? } struct RocketFriend: Decodable { var id: Int var userpic: URL? var firstName: String var lastName: String enum CodingKeys: String, CodingKey { case userpic = "userpic_url" case firstName = "first_name" case lastName = "last_name" case id } } struct RocketOperation: Decodable { var comment: String? var receipt: URL var contextType: String var name: String var friend: RocketFriend? var rocketRubles: Double var date: Int var money: MoneySpent var category: MerchantCategory var merchant: Merchant var location: Coordinate enum CodingKeys: String, CodingKey { case receipt = "receipt_url" case contextType = "context_type" case name = "details" case rocketRubles = "mimimiles" case date = "happened_at" case merchant case comment case money case category case location case friend } } struct Widget: Decodable { var recentOperations: [RocketOperation] var balance: Double var rocketRubles: Double var cashOutCount: Int var freeCashOutLimit: Int var unlimitedCashouts: Bool enum CodingKeys: String, CodingKey { case recentOperations = "recent_operations" case balance = "balace" case rocketRubles = "rocketrubles" case cashOutCount = "cash_out_count" case freeCashOutLimit = "free_cash_out_limit" case unlimitedCashouts = "unlimited_cashouts" } } // {"response":{"status":401,"description":"Авторизация по токену не удалась","code":"INCORRECT_TOKEN","show_it":false}} struct ResponseCode: Decodable { var code: String var description: String var show: Bool var status: Int enum CodingKeys: String, CodingKey { case show = "show_it" case code, description, status } } struct Response: Decodable { var response: ResponseCode }
bsd-3-clause
3df4fd9a1012bcb957975252e865d87e
21.184
120
0.631085
4.201515
false
false
false
false
certificate-helper/TLS-Inspector
TLS Inspector/External/FontAwesome/FontAwesome.swift
2
132471
/// This is a modified output from https://github.com/ecnepsnai/FontawesomeProIOS but only using the free icons import UIKit /** * Enumeration of all FontAwesome icons. Variants are suffixed with "Regular", "Light", or "Solid". * Brands are prefixed with "Brand". Duotone icons are not supported on iOS and are not included here. * * All usable icons can be seen [here](https://fontawesome.com/icons?d=gallery&s=brands,light,regular,solid) */ enum FAIcon: Int { case FAAdSolid = 400878 case FAAddressBookRegular = 300058 case FAAddressBookSolid = 400363 case FAAddressCardRegular = 300007 case FAAddressCardSolid = 400042 case FAAdjustSolid = 400497 case FAAirFreshenerSolid = 400499 case FAAlignCenterSolid = 400368 case FAAlignJustifySolid = 400536 case FAAlignLeftSolid = 400792 case FAAlignRightSolid = 400647 case FAAllergiesSolid = 400839 case FAAmbulanceSolid = 400052 case FAAmericanSignLanguageInterpretingSolid = 400406 case FAAnchorSolid = 400144 case FAAngleDoubleDownSolid = 400227 case FAAngleDoubleLeftSolid = 400238 case FAAngleDoubleRightSolid = 400446 case FAAngleDoubleUpSolid = 400738 case FAAngleDownSolid = 400457 case FAAngleLeftSolid = 400239 case FAAngleRightSolid = 400347 case FAAngleUpSolid = 400795 case FAAngryRegular = 300041 case FAAngrySolid = 400271 case FAAnkhSolid = 400566 case FAAppleAltSolid = 400921 case FAArchiveSolid = 400405 case FAArchwaySolid = 400638 case FAArrowAltCircleDownRegular = 300109 case FAArrowAltCircleDownSolid = 400626 case FAArrowAltCircleLeftRegular = 300066 case FAArrowAltCircleLeftSolid = 400420 case FAArrowAltCircleRightRegular = 300062 case FAArrowAltCircleRightSolid = 400381 case FAArrowAltCircleUpRegular = 300135 case FAArrowAltCircleUpSolid = 400817 case FAArrowCircleDownSolid = 400750 case FAArrowCircleLeftSolid = 400951 case FAArrowCircleRightSolid = 400438 case FAArrowCircleUpSolid = 400414 case FAArrowDownSolid = 400498 case FAArrowLeftSolid = 400171 case FAArrowRightSolid = 400873 case FAArrowUpSolid = 400207 case FAArrowsAltHSolid = 400610 case FAArrowsAltSolid = 400910 case FAArrowsAltVSolid = 400612 case FAAssistiveListeningSystemsSolid = 400565 case FAAsteriskSolid = 400220 case FAAtSolid = 400468 case FAAtlasSolid = 400741 case FAAtomSolid = 400710 case FAAudioDescriptionSolid = 400801 case FAAwardSolid = 400038 case FABabyCarriageSolid = 400494 case FABabySolid = 400774 case FABackspaceSolid = 400186 case FABackwardSolid = 400231 case FABaconSolid = 400022 case FABalanceScaleLeftSolid = 400594 case FABalanceScaleRightSolid = 400926 case FABalanceScaleSolid = 400014 case FABanSolid = 400122 case FABandAidSolid = 400958 case FABarcodeSolid = 400255 case FABarsSolid = 400625 case FABaseballBallSolid = 400033 case FABasketballBallSolid = 400415 case FABathSolid = 400193 case FABatteryEmptySolid = 400427 case FABatteryFullSolid = 400681 case FABatteryHalfSolid = 400058 case FABatteryQuarterSolid = 400567 case FABatteryThreeQuartersSolid = 400045 case FABedSolid = 400832 case FABeerSolid = 400139 case FABellRegular = 300111 case FABellSlashRegular = 300101 case FABellSlashSolid = 400596 case FABellSolid = 400640 case FABezierCurveSolid = 400111 case FABibleSolid = 400515 case FABicycleSolid = 400019 case FABikingSolid = 400656 case FABinocularsSolid = 400900 case FABiohazardSolid = 400335 case FABirthdayCakeSolid = 400520 case FABlenderPhoneSolid = 400346 case FABlenderSolid = 400615 case FABlindSolid = 400322 case FABlogSolid = 400760 case FABoldSolid = 400188 case FABoltSolid = 400189 case FABombSolid = 400103 case FABoneSolid = 400065 case FABongSolid = 400064 case FABookDeadSolid = 400214 case FABookMedicalSolid = 400282 case FABookOpenSolid = 400290 case FABookReaderSolid = 400074 case FABookSolid = 400949 case FABookmarkRegular = 300052 case FABookmarkSolid = 400329 case FABorderAllSolid = 400687 case FABorderNoneSolid = 400631 case FABorderStyleSolid = 400937 case FABowlingBallSolid = 400918 case FABoxOpenSolid = 400101 case FABoxSolid = 400260 case FABoxesSolid = 400172 case FABrailleSolid = 400692 case FABrainSolid = 400300 case FABrands500px = 100007 case FABrandsAccessibleIcon = 100341 case FABrandsAccusoft = 100031 case FABrandsAcquisitionsIncorporated = 100299 case FABrandsAdn = 100404 case FABrandsAdobe = 100029 case FABrandsAdversal = 100127 case FABrandsAffiliatetheme = 100398 case FABrandsAirbnb = 100349 case FABrandsAlgolia = 100074 case FABrandsAlipay = 100307 case FABrandsAmazon = 100058 case FABrandsAmazonPay = 100014 case FABrandsAmilia = 100167 case FABrandsAndroid = 100396 case FABrandsAngellist = 100099 case FABrandsAngrycreative = 100209 case FABrandsAngular = 100144 case FABrandsAppStore = 100085 case FABrandsAppStoreIos = 100339 case FABrandsApper = 100120 case FABrandsApple = 100320 case FABrandsApplePay = 100306 case FABrandsArtstation = 100090 case FABrandsAsymmetrik = 100046 case FABrandsAtlassian = 100429 case FABrandsAudible = 100410 case FABrandsAutoprefixer = 100154 case FABrandsAvianex = 100279 case FABrandsAviato = 100326 case FABrandsAws = 100364 case FABrandsBandcamp = 100172 case FABrandsBattleNet = 100215 case FABrandsBehance = 100355 case FABrandsBehanceSquare = 100108 case FABrandsBimobject = 100102 case FABrandsBitbucket = 100107 case FABrandsBitcoin = 100041 case FABrandsBity = 100145 case FABrandsBlackTie = 100135 case FABrandsBlackberry = 100189 case FABrandsBlogger = 100353 case FABrandsBloggerB = 100012 case FABrandsBluetooth = 100346 case FABrandsBluetoothB = 100409 case FABrandsBootstrap = 100023 case FABrandsBtc = 100376 case FABrandsBuffer = 100152 case FABrandsBuromobelexperte = 100231 case FABrandsBuyNLarge = 100160 case FABrandsBuysellads = 100142 case FABrandsCanadianMapleLeaf = 100123 case FABrandsCcAmazonPay = 100423 case FABrandsCcAmex = 100378 case FABrandsCcApplePay = 100278 case FABrandsCcDinersClub = 100234 case FABrandsCcDiscover = 100248 case FABrandsCcJcb = 100245 case FABrandsCcMastercard = 100141 case FABrandsCcPaypal = 100426 case FABrandsCcStripe = 100006 case FABrandsCcVisa = 100338 case FABrandsCentercode = 100408 case FABrandsCentos = 100086 case FABrandsChrome = 100068 case FABrandsChromecast = 100026 case FABrandsCloudscale = 100428 case FABrandsCloudsmith = 100071 case FABrandsCloudversify = 100203 case FABrandsCodepen = 100262 case FABrandsCodiepie = 100114 case FABrandsConfluence = 100289 case FABrandsConnectdevelop = 100386 case FABrandsContao = 100164 case FABrandsCottonBureau = 100267 case FABrandsCpanel = 100347 case FABrandsCreativeCommons = 100002 case FABrandsCreativeCommonsBy = 100227 case FABrandsCreativeCommonsNc = 100175 case FABrandsCreativeCommonsNcEu = 100179 case FABrandsCreativeCommonsNcJp = 100206 case FABrandsCreativeCommonsNd = 100174 case FABrandsCreativeCommonsPd = 100217 case FABrandsCreativeCommonsPdAlt = 100327 case FABrandsCreativeCommonsRemix = 100150 case FABrandsCreativeCommonsSa = 100241 case FABrandsCreativeCommonsSampling = 100383 case FABrandsCreativeCommonsSamplingPlus = 100079 case FABrandsCreativeCommonsShare = 100050 case FABrandsCreativeCommonsZero = 100009 case FABrandsCriticalRole = 100403 case FABrandsCss3 = 100405 case FABrandsCss3Alt = 100419 case FABrandsCuttlefish = 100302 case FABrandsDAndD = 100230 case FABrandsDAndDBeyond = 100124 case FABrandsDashcube = 100021 case FABrandsDelicious = 100040 case FABrandsDeploydog = 100075 case FABrandsDeskpro = 100392 case FABrandsDev = 100212 case FABrandsDeviantart = 100130 case FABrandsDhl = 100076 case FABrandsDiaspora = 100237 case FABrandsDigg = 100043 case FABrandsDigitalOcean = 100072 case FABrandsDiscord = 100252 case FABrandsDiscourse = 100271 case FABrandsDochub = 100418 case FABrandsDocker = 100275 case FABrandsDraft2digital = 100254 case FABrandsDribbble = 100322 case FABrandsDribbbleSquare = 100103 case FABrandsDropbox = 100205 case FABrandsDrupal = 100235 case FABrandsDyalog = 100321 case FABrandsEarlybirds = 100147 case FABrandsEbay = 100045 case FABrandsEdge = 100274 case FABrandsElementor = 100146 case FABrandsEllo = 100080 case FABrandsEmber = 100199 case FABrandsEmpire = 100415 case FABrandsEnvira = 100414 case FABrandsErlang = 100027 case FABrandsEthereum = 100195 case FABrandsEtsy = 100251 case FABrandsEvernote = 100091 case FABrandsExpeditedssl = 100259 case FABrandsFacebook = 100312 case FABrandsFacebookF = 100115 case FABrandsFacebookMessenger = 100224 case FABrandsFacebookSquare = 100128 case FABrandsFantasyFlightGames = 100243 case FABrandsFedex = 100417 case FABrandsFedora = 100270 case FABrandsFigma = 100233 case FABrandsFirefox = 100319 case FABrandsFirstOrder = 100049 case FABrandsFirstOrderAlt = 100053 case FABrandsFirstdraft = 100282 case FABrandsFlickr = 100377 case FABrandsFlipboard = 100365 case FABrandsFly = 100122 case FABrandsFontAwesome = 100116 case FABrandsFontAwesomeAlt = 100421 case FABrandsFontAwesomeFlag = 100180 case FABrandsFonticons = 100038 case FABrandsFonticonsFi = 100305 case FABrandsFortAwesome = 100382 case FABrandsFortAwesomeAlt = 100028 case FABrandsForumbee = 100366 case FABrandsFoursquare = 100113 case FABrandsFreeCodeCamp = 100200 case FABrandsFreebsd = 100337 case FABrandsFulcrum = 100110 case FABrandsGalacticRepublic = 100393 case FABrandsGalacticSenate = 100301 case FABrandsGetPocket = 100384 case FABrandsGg = 100308 case FABrandsGgCircle = 100101 case FABrandsGit = 100139 case FABrandsGitAlt = 100240 case FABrandsGitSquare = 100331 case FABrandsGithub = 100219 case FABrandsGithubAlt = 100280 case FABrandsGithubSquare = 100118 case FABrandsGitkraken = 100017 case FABrandsGitlab = 100228 case FABrandsGitter = 100263 case FABrandsGlide = 100225 case FABrandsGlideG = 100313 case FABrandsGofore = 100117 case FABrandsGoodreads = 100216 case FABrandsGoodreadsG = 100171 case FABrandsGoogle = 100285 case FABrandsGoogleDrive = 100310 case FABrandsGooglePlay = 100253 case FABrandsGooglePlus = 100005 case FABrandsGooglePlusG = 100294 case FABrandsGooglePlusSquare = 100051 case FABrandsGoogleWallet = 100202 case FABrandsGratipay = 100081 case FABrandsGrav = 100374 case FABrandsGripfire = 100344 case FABrandsGrunt = 100148 case FABrandsGulp = 100159 case FABrandsHackerNews = 100400 case FABrandsHackerNewsSquare = 100088 case FABrandsHackerrank = 100065 case FABrandsHips = 100249 case FABrandsHireAHelper = 100238 case FABrandsHooli = 100218 case FABrandsHornbill = 100151 case FABrandsHotjar = 100044 case FABrandsHouzz = 100034 case FABrandsHtml5 = 100064 case FABrandsHubspot = 100018 case FABrandsImdb = 100359 case FABrandsInstagram = 100208 case FABrandsIntercom = 100078 case FABrandsInternetExplorer = 100226 case FABrandsInvision = 100169 case FABrandsIoxhost = 100273 case FABrandsItchIo = 100035 case FABrandsItunes = 100004 case FABrandsItunesNote = 100061 case FABrandsJava = 100260 case FABrandsJediOrder = 100387 case FABrandsJenkins = 100104 case FABrandsJira = 100340 case FABrandsJoget = 100221 case FABrandsJoomla = 100094 case FABrandsJs = 100168 case FABrandsJsSquare = 100155 case FABrandsJsfiddle = 100293 case FABrandsKaggle = 100350 case FABrandsKeybase = 100092 case FABrandsKeycdn = 100192 case FABrandsKickstarter = 100336 case FABrandsKickstarterK = 100385 case FABrandsKorvue = 100162 case FABrandsLaravel = 100351 case FABrandsLastfm = 100019 case FABrandsLastfmSquare = 100190 case FABrandsLeanpub = 100188 case FABrandsLess = 100402 case FABrandsLine = 100296 case FABrandsLinkedin = 100391 case FABrandsLinkedinIn = 100173 case FABrandsLinode = 100394 case FABrandsLinux = 100412 case FABrandsLyft = 100163 case FABrandsMagento = 100214 case FABrandsMailchimp = 100397 case FABrandsMandalorian = 100073 case FABrandsMarkdown = 100257 case FABrandsMastodon = 100022 case FABrandsMaxcdn = 100087 case FABrandsMdb = 100030 case FABrandsMedapps = 100138 case FABrandsMedium = 100097 case FABrandsMediumM = 100427 case FABrandsMedrt = 100329 case FABrandsMeetup = 100077 case FABrandsMegaport = 100367 case FABrandsMendeley = 100431 case FABrandsMicrosoft = 100304 case FABrandsMix = 100362 case FABrandsMixcloud = 100317 case FABrandsMizuni = 100069 case FABrandsModx = 100183 case FABrandsMonero = 100334 case FABrandsNapster = 100197 case FABrandsNeos = 100185 case FABrandsNimblr = 100314 case FABrandsNode = 100106 case FABrandsNodeJs = 100261 case FABrandsNpm = 100335 case FABrandsNs8 = 100295 case FABrandsNutritionix = 100324 case FABrandsOdnoklassniki = 100131 case FABrandsOdnoklassnikiSquare = 100126 case FABrandsOldRepublic = 100357 case FABrandsOpencart = 100287 case FABrandsOpenid = 100204 case FABrandsOpera = 100136 case FABrandsOptinMonster = 100178 case FABrandsOrcid = 100001 case FABrandsOsi = 100111 case FABrandsPage4 = 100149 case FABrandsPagelines = 100333 case FABrandsPalfed = 100105 case FABrandsPatreon = 100291 case FABrandsPaypal = 100098 case FABrandsPennyArcade = 100354 case FABrandsPeriscope = 100066 case FABrandsPhabricator = 100196 case FABrandsPhoenixFramework = 100369 case FABrandsPhoenixSquadron = 100010 case FABrandsPhp = 100399 case FABrandsPiedPiper = 100375 case FABrandsPiedPiperAlt = 100416 case FABrandsPiedPiperHat = 100363 case FABrandsPiedPiperPp = 100112 case FABrandsPinterest = 100052 case FABrandsPinterestP = 100063 case FABrandsPinterestSquare = 100318 case FABrandsPlaystation = 100060 case FABrandsProductHunt = 100056 case FABrandsPushed = 100213 case FABrandsPython = 100395 case FABrandsQq = 100373 case FABrandsQuinscape = 100232 case FABrandsQuora = 100311 case FABrandsRProject = 100368 case FABrandsRaspberryPi = 100244 case FABrandsRavelry = 100266 case FABrandsReact = 100246 case FABrandsReacteurope = 100290 case FABrandsReadme = 100256 case FABrandsRebel = 100140 case FABrandsRedRiver = 100236 case FABrandsReddit = 100062 case FABrandsRedditAlien = 100137 case FABrandsRedditSquare = 100158 case FABrandsRedhat = 100143 case FABrandsRenren = 100380 case FABrandsReplyd = 100016 case FABrandsResearchgate = 100425 case FABrandsResolving = 100303 case FABrandsRev = 100348 case FABrandsRocketchat = 100157 case FABrandsRockrms = 100371 case FABrandsSafari = 100133 case FABrandsSalesforce = 100211 case FABrandsSass = 100432 case FABrandsSchlix = 100125 case FABrandsScribd = 100229 case FABrandsSearchengin = 100186 case FABrandsSellcast = 100332 case FABrandsSellsy = 100264 case FABrandsServicestack = 100153 case FABrandsShirtsinbulk = 100356 case FABrandsShopware = 100100 case FABrandsSimplybuilt = 100286 case FABrandsSistrix = 100008 case FABrandsSith = 100389 case FABrandsSketch = 100284 case FABrandsSkyatlas = 100407 case FABrandsSkype = 100268 case FABrandsSlack = 100358 case FABrandsSlackHash = 100370 case FABrandsSlideshare = 100181 case FABrandsSnapchat = 100345 case FABrandsSnapchatGhost = 100121 case FABrandsSnapchatSquare = 100047 case FABrandsSoundcloud = 100036 case FABrandsSourcetree = 100360 case FABrandsSpeakap = 100089 case FABrandsSpeakerDeck = 100361 case FABrandsSpotify = 100342 case FABrandsSquarespace = 100054 case FABrandsStackExchange = 100272 case FABrandsStackOverflow = 100281 case FABrandsStackpath = 100300 case FABrandsStaylinked = 100129 case FABrandsSteam = 100059 case FABrandsSteamSquare = 100011 case FABrandsSteamSymbol = 100182 case FABrandsStickerMule = 100042 case FABrandsStrava = 100406 case FABrandsStripe = 100039 case FABrandsStripeS = 100013 case FABrandsStudiovinari = 100223 case FABrandsStumbleupon = 100328 case FABrandsStumbleuponCircle = 100372 case FABrandsSuperpowers = 100070 case FABrandsSupple = 100258 case FABrandsSuse = 100210 case FABrandsSwift = 100381 case FABrandsSymfony = 100170 case FABrandsTeamspeak = 100187 case FABrandsTelegram = 100277 case FABrandsTelegramPlane = 100207 case FABrandsTencentWeibo = 100242 case FABrandsTheRedYeti = 100134 case FABrandsThemeco = 100082 case FABrandsThemeisle = 100265 case FABrandsThinkPeaks = 100193 case FABrandsTradeFederation = 100067 case FABrandsTrello = 100177 case FABrandsTripadvisor = 100379 case FABrandsTumblr = 100413 case FABrandsTumblrSquare = 100420 case FABrandsTwitch = 100095 case FABrandsTwitter = 100411 case FABrandsTwitterSquare = 100057 case FABrandsTypo3 = 100250 case FABrandsUber = 100298 case FABrandsUbuntu = 100315 case FABrandsUikit = 100316 case FABrandsUmbraco = 100422 case FABrandsUniregistry = 100430 case FABrandsUntappd = 100288 case FABrandsUps = 100037 case FABrandsUsb = 100325 case FABrandsUsps = 100003 case FABrandsUssunnah = 100292 case FABrandsVaadin = 100269 case FABrandsViacoin = 100055 case FABrandsViadeo = 100283 case FABrandsViadeoSquare = 100166 case FABrandsViber = 100033 case FABrandsVimeo = 100388 case FABrandsVimeoSquare = 100194 case FABrandsVimeoV = 100184 case FABrandsVine = 100255 case FABrandsVk = 100390 case FABrandsVnv = 100247 case FABrandsVuejs = 100032 case FABrandsWaze = 100198 case FABrandsWeebly = 100176 case FABrandsWeibo = 100165 case FABrandsWeixin = 100132 case FABrandsWhatsapp = 100083 case FABrandsWhatsappSquare = 100025 case FABrandsWhmcs = 100276 case FABrandsWikipediaW = 100109 case FABrandsWindows = 100297 case FABrandsWix = 100323 case FABrandsWizardsOfTheCoast = 100000 case FABrandsWolfPackBattalion = 100048 case FABrandsWordpress = 100096 case FABrandsWordpressSimple = 100020 case FABrandsWpbeginner = 100239 case FABrandsWpexplorer = 100119 case FABrandsWpforms = 100309 case FABrandsWpressr = 100093 case FABrandsXbox = 100084 case FABrandsXing = 100191 case FABrandsXingSquare = 100156 case FABrandsYCombinator = 100330 case FABrandsYahoo = 100015 case FABrandsYammer = 100161 case FABrandsYandex = 100222 case FABrandsYandexInternational = 100024 case FABrandsYarn = 100352 case FABrandsYelp = 100424 case FABrandsYoast = 100220 case FABrandsYoutube = 100201 case FABrandsYoutubeSquare = 100401 case FABrandsZhihu = 100343 case FABreadSliceSolid = 400080 case FABriefcaseMedicalSolid = 400683 case FABriefcaseSolid = 400047 case FABroadcastTowerSolid = 400484 case FABroomSolid = 400796 case FABrushSolid = 400929 case FABugSolid = 400940 case FABuildingRegular = 300078 case FABuildingSolid = 400477 case FABullhornSolid = 400773 case FABullseyeSolid = 400723 case FABurnSolid = 400546 case FABusAltSolid = 400177 case FABusSolid = 400936 case FABusinessTimeSolid = 400850 case FACalculatorSolid = 400657 case FACalendarAltRegular = 300144 case FACalendarAltSolid = 400899 case FACalendarCheckRegular = 300136 case FACalendarCheckSolid = 400831 case FACalendarDaySolid = 400641 case FACalendarMinusRegular = 300116 case FACalendarMinusSolid = 400662 case FACalendarPlusRegular = 300051 case FACalendarPlusSolid = 400316 case FACalendarRegular = 300054 case FACalendarSolid = 400342 case FACalendarTimesRegular = 300004 case FACalendarTimesSolid = 400029 case FACalendarWeekSolid = 400382 case FACameraRetroSolid = 400108 case FACameraSolid = 400767 case FACampgroundSolid = 400563 case FACandyCaneSolid = 400698 case FACannabisSolid = 400436 case FACapsulesSolid = 400855 case FACarAltSolid = 400386 case FACarBatterySolid = 400196 case FACarCrashSolid = 400123 case FACarSideSolid = 400575 case FACarSolid = 400279 case FACaretDownSolid = 400249 case FACaretLeftSolid = 400355 case FACaretRightSolid = 400660 case FACaretSquareDownRegular = 300113 case FACaretSquareDownSolid = 400653 case FACaretSquareLeftRegular = 300120 case FACaretSquareLeftSolid = 400699 case FACaretSquareRightRegular = 300013 case FACaretSquareRightSolid = 400066 case FACaretSquareUpRegular = 300095 case FACaretSquareUpSolid = 400564 case FACaretUpSolid = 400011 case FACarrotSolid = 400780 case FACartArrowDownSolid = 400727 case FACartPlusSolid = 400251 case FACashRegisterSolid = 400182 case FACatSolid = 400280 case FACertificateSolid = 400764 case FAChairSolid = 400237 case FAChalkboardSolid = 400881 case FAChalkboardTeacherSolid = 400628 case FAChargingStationSolid = 400556 case FAChartAreaSolid = 400100 case FAChartBarRegular = 300102 case FAChartBarSolid = 400602 case FAChartLineSolid = 400786 case FAChartPieSolid = 400437 case FACheckCircleRegular = 300039 case FACheckCircleSolid = 400246 case FACheckDoubleSolid = 400548 case FACheckSolid = 400215 case FACheckSquareRegular = 300130 case FACheckSquareSolid = 400785 case FACheeseSolid = 400323 case FAChessBishopSolid = 400485 case FAChessBoardSolid = 400225 case FAChessKingSolid = 400605 case FAChessKnightSolid = 400757 case FAChessPawnSolid = 400155 case FAChessQueenSolid = 400845 case FAChessRookSolid = 400106 case FAChessSolid = 400096 case FAChevronCircleDownSolid = 400287 case FAChevronCircleLeftSolid = 400175 case FAChevronCircleRightSolid = 400002 case FAChevronCircleUpSolid = 400690 case FAChevronDownSolid = 400574 case FAChevronLeftSolid = 400250 case FAChevronRightSolid = 400706 case FAChevronUpSolid = 400959 case FAChildSolid = 400142 case FAChurchSolid = 400644 case FACircleNotchSolid = 400931 case FACircleRegular = 300106 case FACircleSolid = 400618 case FACitySolid = 400326 case FAClinicMedicalSolid = 400820 case FAClipboardCheckSolid = 400350 case FAClipboardListSolid = 400744 case FAClipboardRegular = 300129 case FAClipboardSolid = 400754 case FAClockRegular = 300083 case FAClockSolid = 400505 case FACloneRegular = 300046 case FACloneSolid = 400293 case FAClosedCaptioningRegular = 300050 case FAClosedCaptioningSolid = 400308 case FACloudDownloadAltSolid = 400765 case FACloudMeatballSolid = 400783 case FACloudMoonRainSolid = 400447 case FACloudMoonSolid = 400880 case FACloudRainSolid = 400174 case FACloudShowersHeavySolid = 400000 case FACloudSolid = 400762 case FACloudSunRainSolid = 400591 case FACloudSunSolid = 400672 case FACloudUploadAltSolid = 400828 case FACocktailSolid = 400292 case FACodeBranchSolid = 400127 case FACodeSolid = 400735 case FACoffeeSolid = 400062 case FACogSolid = 400133 case FACogsSolid = 400675 case FACoinsSolid = 400035 case FAColumnsSolid = 400620 case FACommentAltRegular = 300072 case FACommentAltSolid = 400433 case FACommentDollarSolid = 400670 case FACommentDotsRegular = 300099 case FACommentDotsSolid = 400585 case FACommentMedicalSolid = 400021 case FACommentRegular = 300141 case FACommentSlashSolid = 400461 case FACommentSolid = 400874 case FACommentsDollarSolid = 400185 case FACommentsRegular = 300031 case FACommentsSolid = 400184 case FACompactDiscSolid = 400083 case FACompassRegular = 300108 case FACompassSolid = 400623 case FACompressArrowsAltSolid = 400443 case FACompressSolid = 400344 case FAConciergeBellSolid = 400277 case FACookieBiteSolid = 400724 case FACookieSolid = 400572 case FACopyRegular = 300000 case FACopySolid = 400001 case FACopyrightRegular = 300104 case FACopyrightSolid = 400616 case FACouchSolid = 400598 case FACreditCardRegular = 300023 case FACreditCardSolid = 400132 case FACropAltSolid = 400005 case FACropSolid = 400749 case FACrossSolid = 400893 case FACrosshairsSolid = 400483 case FACrowSolid = 400748 case FACrownSolid = 400179 case FACrutchSolid = 400654 case FACubeSolid = 400854 case FACubesSolid = 400635 case FACutSolid = 400666 case FADatabaseSolid = 400086 case FADeafSolid = 400202 case FADemocratSolid = 400243 case FADesktopSolid = 400416 case FADharmachakraSolid = 400009 case FADiagnosesSolid = 400261 case FADiceD20Solid = 400797 case FADiceD6Solid = 400528 case FADiceFiveSolid = 400401 case FADiceFourSolid = 400201 case FADiceOneSolid = 400547 case FADiceSixSolid = 400312 case FADiceSolid = 400356 case FADiceThreeSolid = 400768 case FADiceTwoSolid = 400079 case FADigitalTachographSolid = 400226 case FADirectionsSolid = 400513 case FADivideSolid = 400162 case FADizzyRegular = 300025 case FADizzySolid = 400147 case FADnaSolid = 400032 case FADogSolid = 400102 case FADollarSignSolid = 400844 case FADollyFlatbedSolid = 400775 case FADollySolid = 400550 case FADonateSolid = 400633 case FADoorClosedSolid = 400197 case FADoorOpenSolid = 400448 case FADotCircleRegular = 300033 case FADotCircleSolid = 400209 case FADoveSolid = 400295 case FADownloadSolid = 400752 case FADraftingCompassSolid = 400007 case FADragonSolid = 400541 case FADrawPolygonSolid = 400758 case FADrumSolid = 400870 case FADrumSteelpanSolid = 400089 case FADrumstickBiteSolid = 400726 case FADumbbellSolid = 400737 case FADumpsterFireSolid = 400590 case FADumpsterSolid = 400815 case FADungeonSolid = 400863 case FAEditRegular = 300134 case FAEditSolid = 400806 case FAEggSolid = 400545 case FAEjectSolid = 400848 case FAEllipsisHSolid = 400466 case FAEllipsisVSolid = 400561 case FAEnvelopeOpenRegular = 300131 case FAEnvelopeOpenSolid = 400787 case FAEnvelopeOpenTextSolid = 400464 case FAEnvelopeRegular = 300042 case FAEnvelopeSolid = 400275 case FAEnvelopeSquareSolid = 400890 case FAEqualsSolid = 400027 case FAEraserSolid = 400882 case FAEthernetSolid = 400053 case FAEuroSignSolid = 400604 case FAExchangeAltSolid = 400180 case FAExclamationCircleSolid = 400183 case FAExclamationSolid = 400314 case FAExclamationTriangleSolid = 400674 case FAExpandArrowsAltSolid = 400652 case FAExpandSolid = 400903 case FAExternalLinkAltSolid = 400421 case FAExternalLinkSquareAltSolid = 400003 case FAEyeDropperSolid = 400613 case FAEyeRegular = 300087 case FAEyeSlashRegular = 300005 case FAEyeSlashSolid = 400030 case FAEyeSolid = 400521 case FAFanSolid = 400493 case FAFastBackwardSolid = 400517 case FAFastForwardSolid = 400140 case FAFaxSolid = 400490 case FAFeatherAltSolid = 400031 case FAFeatherSolid = 400884 case FAFemaleSolid = 400930 case FAFighterJetSolid = 400862 case FAFileAltRegular = 300086 case FAFileAltSolid = 400512 case FAFileArchiveRegular = 300047 case FAFileArchiveSolid = 400294 case FAFileAudioRegular = 300149 case FAFileAudioSolid = 400952 case FAFileCodeRegular = 300030 case FAFileCodeSolid = 400178 case FAFileContractSolid = 400871 case FAFileCsvSolid = 400304 case FAFileDownloadSolid = 400305 case FAFileExcelRegular = 300127 case FAFileExcelSolid = 400732 case FAFileExportSolid = 400097 case FAFileImageRegular = 300040 case FAFileImageSolid = 400262 case FAFileImportSolid = 400934 case FAFileInvoiceDollarSolid = 400230 case FAFileInvoiceSolid = 400028 case FAFileMedicalAltSolid = 400170 case FAFileMedicalSolid = 400658 case FAFilePdfRegular = 300097 case FAFilePdfSolid = 400569 case FAFilePowerpointRegular = 300085 case FAFilePowerpointSolid = 400508 case FAFilePrescriptionSolid = 400740 case FAFileRegular = 300077 case FAFileSignatureSolid = 400455 case FAFileSolid = 400469 case FAFileUploadSolid = 400090 case FAFileVideoRegular = 300061 case FAFileVideoSolid = 400380 case FAFileWordRegular = 300132 case FAFileWordSolid = 400799 case FAFillDripSolid = 400460 case FAFillSolid = 400472 case FAFilmSolid = 400471 case FAFilterSolid = 400075 case FAFingerprintSolid = 400909 case FAFireAltSolid = 400476 case FAFireExtinguisherSolid = 400611 case FAFireSolid = 400650 case FAFirstAidSolid = 400374 case FAFishSolid = 400562 case FAFistRaisedSolid = 400204 case FAFlagCheckeredSolid = 400946 case FAFlagRegular = 300090 case FAFlagSolid = 400526 case FAFlagUsaSolid = 400424 case FAFlaskSolid = 400516 case FAFlushedRegular = 300036 case FAFlushedSolid = 400223 case FAFolderMinusSolid = 400242 case FAFolderOpenRegular = 300015 case FAFolderOpenSolid = 400076 case FAFolderPlusSolid = 400288 case FAFolderRegular = 300018 case FAFolderSolid = 400112 case FAFontAwesomeLogoFullRegular = 300088 case FAFontAwesomeLogoFullSolid = 400524 case FAFontSolid = 400614 case FAFootballBallSolid = 400935 case FAForwardSolid = 400332 case FAFrogSolid = 400766 case FAFrownOpenRegular = 300117 case FAFrownOpenSolid = 400665 case FAFrownRegular = 300067 case FAFrownSolid = 400422 case FAFunnelDollarSolid = 400319 case FAFutbolRegular = 300103 case FAFutbolSolid = 400607 case FAGamepadSolid = 400667 case FAGasPumpSolid = 400912 case FAGavelSolid = 400697 case FAGemRegular = 300059 case FAGemSolid = 400364 case FAGenderlessSolid = 400400 case FAGhostSolid = 400955 case FAGiftSolid = 400173 case FAGiftsSolid = 400475 case FAGlassCheersSolid = 400621 case FAGlassMartiniAltSolid = 400634 case FAGlassMartiniSolid = 400865 case FAGlassWhiskeySolid = 400259 case FAGlassesSolid = 400809 case FAGlobeAfricaSolid = 400689 case FAGlobeAmericasSolid = 400719 case FAGlobeAsiaSolid = 400592 case FAGlobeEuropeSolid = 400704 case FAGlobeSolid = 400810 case FAGolfBallSolid = 400906 case FAGopuramSolid = 400010 case FAGraduationCapSolid = 400025 case FAGreaterThanEqualSolid = 400518 case FAGreaterThanSolid = 400165 case FAGrimaceRegular = 300038 case FAGrimaceSolid = 400245 case FAGrinAltRegular = 300112 case FAGrinAltSolid = 400648 case FAGrinBeamRegular = 300140 case FAGrinBeamSolid = 400867 case FAGrinBeamSweatRegular = 300092 case FAGrinBeamSweatSolid = 400554 case FAGrinHeartsRegular = 300142 case FAGrinHeartsSolid = 400886 case FAGrinRegular = 300068 case FAGrinSolid = 400425 case FAGrinSquintRegular = 300049 case FAGrinSquintSolid = 400307 case FAGrinSquintTearsRegular = 300148 case FAGrinSquintTearsSolid = 400947 case FAGrinStarsRegular = 300128 case FAGrinStarsSolid = 400745 case FAGrinTearsRegular = 300091 case FAGrinTearsSolid = 400551 case FAGrinTongueRegular = 300093 case FAGrinTongueSolid = 400557 case FAGrinTongueSquintRegular = 300056 case FAGrinTongueSquintSolid = 400352 case FAGrinTongueWinkRegular = 300075 case FAGrinTongueWinkSolid = 400449 case FAGrinWinkRegular = 300107 case FAGrinWinkSolid = 400622 case FAGripHorizontalSolid = 400200 case FAGripLinesSolid = 400206 case FAGripLinesVerticalSolid = 400876 case FAGripVerticalSolid = 400811 case FAGuitarSolid = 400373 case FAHSquareSolid = 400777 case FAHamburgerSolid = 400533 case FAHammerSolid = 400125 case FAHamsaSolid = 400753 case FAHandHoldingHeartSolid = 400404 case FAHandHoldingSolid = 400391 case FAHandHoldingUsdSolid = 400763 case FAHandLizardRegular = 300082 case FAHandLizardSolid = 400504 case FAHandMiddleFingerSolid = 400875 case FAHandPaperRegular = 300003 case FAHandPaperSolid = 400026 case FAHandPeaceRegular = 300096 case FAHandPeaceSolid = 400568 case FAHandPointDownRegular = 300143 case FAHandPointDownSolid = 400897 case FAHandPointLeftRegular = 300024 case FAHandPointLeftSolid = 400145 case FAHandPointRightRegular = 300012 case FAHandPointRightSolid = 400063 case FAHandPointUpRegular = 300151 case FAHandPointUpSolid = 400960 case FAHandPointerRegular = 300057 case FAHandPointerSolid = 400359 case FAHandRockRegular = 300076 case FAHandRockSolid = 400458 case FAHandScissorsRegular = 300037 case FAHandScissorsSolid = 400229 case FAHandSpockRegular = 300079 case FAHandSpockSolid = 400482 case FAHandsHelpingSolid = 400645 case FAHandsSolid = 400804 case FAHandshakeRegular = 300028 case FAHandshakeSolid = 400163 case FAHanukiahSolid = 400134 case FAHardHatSolid = 400917 case FAHashtagSolid = 400393 case FAHatCowboySideSolid = 400559 case FAHatCowboySolid = 400187 case FAHatWizardSolid = 400341 case FAHaykalSolid = 400395 case FAHddRegular = 300064 case FAHddSolid = 400396 case FAHeadingSolid = 400018 case FAHeadphonesAltSolid = 400057 case FAHeadphonesSolid = 400050 case FAHeadsetSolid = 400601 case FAHeartBrokenSolid = 400465 case FAHeartRegular = 300043 case FAHeartSolid = 400283 case FAHeartbeatSolid = 400539 case FAHelicopterSolid = 400390 case FAHighlighterSolid = 400891 case FAHikingSolid = 400264 case FAHippoSolid = 400361 case FAHistorySolid = 400532 case FAHockeyPuckSolid = 400110 case FAHollyBerrySolid = 400904 case FAHomeSolid = 400919 case FAHorseHeadSolid = 400118 case FAHorseSolid = 400571 case FAHospitalAltSolid = 400398 case FAHospitalRegular = 300006 case FAHospitalSolid = 400034 case FAHospitalSymbolSolid = 400714 case FAHotTubSolid = 400686 case FAHotdogSolid = 400664 case FAHotelSolid = 400587 case FAHourglassEndSolid = 400849 case FAHourglassHalfSolid = 400254 case FAHourglassRegular = 300019 case FAHourglassSolid = 400126 case FAHourglassStartSolid = 400392 case FAHouseDamageSolid = 400705 case FAHryvniaSolid = 400522 case FAICursorSolid = 400278 case FAIceCreamSolid = 400823 case FAIciclesSolid = 400107 case FAIconsSolid = 400486 case FAIdBadgeRegular = 300053 case FAIdBadgeSolid = 400338 case FAIdCardAltSolid = 400784 case FAIdCardRegular = 300138 case FAIdCardSolid = 400840 case FAIglooSolid = 400232 case FAImageRegular = 300074 case FAImageSolid = 400445 case FAImagesRegular = 300124 case FAImagesSolid = 400716 case FAInboxSolid = 400450 case FAIndentSolid = 400816 case FAIndustrySolid = 400441 case FAInfinitySolid = 400896 case FAInfoCircleSolid = 400510 case FAInfoSolid = 400711 case FAItalicSolid = 400454 case FAJediSolid = 400507 case FAJointSolid = 400858 case FAJournalWhillsSolid = 400124 case FAKaabaSolid = 400093 case FAKeySolid = 400868 case FAKeyboardRegular = 300011 case FAKeyboardSolid = 400056 case FAKhandaSolid = 400808 case FAKissBeamRegular = 300001 case FAKissBeamSolid = 400004 case FAKissRegular = 300133 case FAKissSolid = 400803 case FAKissWinkHeartRegular = 300026 case FAKissWinkHeartSolid = 400148 case FAKiwiBirdSolid = 400362 case FALandmarkSolid = 400663 case FALanguageSolid = 400320 case FALaptopCodeSolid = 400410 case FALaptopMedicalSolid = 400016 case FALaptopSolid = 400158 case FALaughBeamRegular = 300147 case FALaughBeamSolid = 400922 case FALaughRegular = 300069 case FALaughSolid = 400429 case FALaughSquintRegular = 300022 case FALaughSquintSolid = 400131 case FALaughWinkRegular = 300098 case FALaughWinkSolid = 400577 case FALayerGroupSolid = 400276 case FALeafSolid = 400728 case FALemonRegular = 300125 case FALemonSolid = 400718 case FALessThanEqualSolid = 400679 case FALessThanSolid = 400847 case FALevelDownAltSolid = 400302 case FALevelUpAltSolid = 400821 case FALifeRingRegular = 300008 case FALifeRingSolid = 400043 case FALightbulbRegular = 300146 case FALightbulbSolid = 400907 case FALinkSolid = 400709 case FALiraSignSolid = 400608 case FAListAltRegular = 300021 case FAListAltSolid = 400129 case FAListOlSolid = 400117 case FAListSolid = 400496 case FAListUlSolid = 400693 case FALocationArrowSolid = 400317 case FALockOpenSolid = 400778 case FALockSolid = 400779 case FALongArrowAltDownSolid = 400730 case FALongArrowAltLeftSolid = 400747 case FALongArrowAltRightSolid = 400040 case FALongArrowAltUpSolid = 400756 case FALowVisionSolid = 400933 case FALuggageCartSolid = 400440 case FAMagicSolid = 400555 case FAMagnetSolid = 400244 case FAMailBulkSolid = 400095 case FAMaleSolid = 400531 case FAMapMarkedAltSolid = 400141 case FAMapMarkedSolid = 400902 case FAMapMarkerAltSolid = 400336 case FAMapMarkerSolid = 400898 case FAMapPinSolid = 400367 case FAMapRegular = 300045 case FAMapSignsSolid = 400370 case FAMapSolid = 400291 case FAMarkerSolid = 400268 case FAMarsDoubleSolid = 400431 case FAMarsSolid = 400389 case FAMarsStrokeHSolid = 400859 case FAMarsStrokeSolid = 400695 case FAMarsStrokeVSolid = 400856 case FAMaskSolid = 400480 case FAMedalSolid = 400846 case FAMedkitSolid = 400091 case FAMehBlankRegular = 300055 case FAMehBlankSolid = 400349 case FAMehRegular = 300020 case FAMehRollingEyesRegular = 300137 case FAMehRollingEyesSolid = 400835 case FAMehSolid = 400128 case FAMemorySolid = 400272 case FAMenorahSolid = 400168 case FAMercurySolid = 400081 case FAMeteorSolid = 400950 case FAMicrochipSolid = 400509 case FAMicrophoneAltSlashSolid = 400872 case FAMicrophoneAltSolid = 400782 case FAMicrophoneSlashSolid = 400542 case FAMicrophoneSolid = 400838 case FAMicroscopeSolid = 400121 case FAMinusCircleSolid = 400154 case FAMinusSolid = 400092 case FAMinusSquareRegular = 300118 case FAMinusSquareSolid = 400669 case FAMittenSolid = 400104 case FAMobileAltSolid = 400267 case FAMobileSolid = 400606 case FAMoneyBillAltRegular = 300110 case FAMoneyBillAltSolid = 400627 case FAMoneyBillSolid = 400573 case FAMoneyBillWaveAltSolid = 400957 case FAMoneyBillWaveSolid = 400208 case FAMoneyCheckAltSolid = 400115 case FAMoneyCheckSolid = 400135 case FAMonumentSolid = 400942 case FAMoonRegular = 300073 case FAMoonSolid = 400435 case FAMortarPestleSolid = 400176 case FAMosqueSolid = 400739 case FAMotorcycleSolid = 400793 case FAMountainSolid = 400597 case FAMousePointerSolid = 400274 case FAMouseSolid = 400149 case FAMugHotSolid = 400703 case FAMusicSolid = 400199 case FANetworkWiredSolid = 400194 case FANeuterSolid = 400478 case FANewspaperRegular = 300065 case FANewspaperSolid = 400397 case FANotEqualSolid = 400235 case FANotesMedicalSolid = 400233 case FAObjectGroupRegular = 300114 case FAObjectGroupSolid = 400655 case FAObjectUngroupRegular = 300009 case FAObjectUngroupSolid = 400046 case FAOilCanSolid = 400048 case FAOmSolid = 400439 case FAOtterSolid = 400203 case FAOutdentSolid = 400529 case FAPagerSolid = 400348 case FAPaintBrushSolid = 400824 case FAPaintRollerSolid = 400340 case FAPaletteSolid = 400371 case FAPalletSolid = 400417 case FAPaperPlaneRegular = 300081 case FAPaperPlaneSolid = 400501 case FAPaperclipSolid = 400798 case FAParachuteBoxSolid = 400825 case FAParagraphSolid = 400530 case FAParkingSolid = 400369 case FAPassportSolid = 400036 case FAPastafarianismSolid = 400938 case FAPasteSolid = 400924 case FAPauseCircleRegular = 300071 case FAPauseCircleSolid = 400432 case FAPauseSolid = 400257 case FAPawSolid = 400403 case FAPeaceSolid = 400720 case FAPenAltSolid = 400742 case FAPenFancySolid = 400334 case FAPenNibSolid = 400408 case FAPenSolid = 400684 case FAPenSquareSolid = 400769 case FAPencilAltSolid = 400143 case FAPencilRulerSolid = 400637 case FAPeopleCarrySolid = 400224 case FAPepperHotSolid = 400588 case FAPercentSolid = 400948 case FAPercentageSolid = 400084 case FAPersonBoothSolid = 400315 case FAPhoneAltSolid = 400061 case FAPhoneSlashSolid = 400252 case FAPhoneSolid = 400039 case FAPhoneSquareAltSolid = 400794 case FAPhoneSquareSolid = 400822 case FAPhoneVolumeSolid = 400894 case FAPhotoVideoSolid = 400826 case FAPiggyBankSolid = 400240 case FAPillsSolid = 400313 case FAPizzaSliceSolid = 400041 case FAPlaceOfWorshipSolid = 400851 case FAPlaneArrivalSolid = 400195 case FAPlaneDepartureSolid = 400643 case FAPlaneSolid = 400538 case FAPlayCircleRegular = 300139 case FAPlayCircleSolid = 400842 case FAPlaySolid = 400600 case FAPlugSolid = 400273 case FAPlusCircleSolid = 400222 case FAPlusSolid = 400191 case FAPlusSquareRegular = 300035 case FAPlusSquareSolid = 400219 case FAPodcastSolid = 400459 case FAPollHSolid = 400914 case FAPollSolid = 400385 case FAPooSolid = 400384 case FAPooStormSolid = 400857 case FAPoopSolid = 400474 case FAPortraitSolid = 400629 case FAPoundSignSolid = 400070 case FAPowerOffSolid = 400216 case FAPraySolid = 400549 case FAPrayingHandsSolid = 400241 case FAPrescriptionBottleAltSolid = 400956 case FAPrescriptionBottleSolid = 400905 case FAPrescriptionSolid = 400636 case FAPrintSolid = 400492 case FAProceduresSolid = 400860 case FAProjectDiagramSolid = 400059 case FAPuzzlePieceSolid = 400599 case FAQrcodeSolid = 400581 case FAQuestionCircleRegular = 300032 case FAQuestionCircleSolid = 400192 case FAQuestionSolid = 400702 case FAQuidditchSolid = 400920 case FAQuoteLeftSolid = 400266 case FAQuoteRightSolid = 400138 case FAQuranSolid = 400318 case FARadiationAltSolid = 400925 case FARadiationSolid = 400892 case FARainbowSolid = 400717 case FARandomSolid = 400105 case FAReceiptSolid = 400309 case FARecordVinylSolid = 400060 case FARecycleSolid = 400006 case FARedoAltSolid = 400841 case FARedoSolid = 400682 case FARegisteredRegular = 300122 case FARegisteredSolid = 400707 case FARemoveFormatSolid = 400843 case FAReplyAllSolid = 400927 case FAReplySolid = 400253 case FARepublicanSolid = 400805 case FARestroomSolid = 400377 case FARetweetSolid = 400630 case FARibbonSolid = 400503 case FARingSolid = 400325 case FARoadSolid = 400444 case FARobotSolid = 400788 case FARocketSolid = 400908 case FARouteSolid = 400818 case FARssSolid = 400113 case FARssSquareSolid = 400328 case FARubleSignSolid = 400357 case FARulerCombinedSolid = 400861 case FARulerHorizontalSolid = 400339 case FARulerSolid = 400423 case FARulerVerticalSolid = 400358 case FARunningSolid = 400407 case FARupeeSignSolid = 400068 case FASadCryRegular = 300126 case FASadCrySolid = 400731 case FASadTearRegular = 300094 case FASadTearSolid = 400560 case FASatelliteDishSolid = 400953 case FASatelliteSolid = 400153 case FASaveRegular = 300029 case FASaveSolid = 400166 case FASchoolSolid = 400012 case FAScrewdriverSolid = 400491 case FAScrollSolid = 400734 case FASdCardSolid = 400887 case FASearchDollarSolid = 400247 case FASearchLocationSolid = 400659 case FASearchMinusSolid = 400722 case FASearchPlusSolid = 400534 case FASearchSolid = 400514 case FASeedlingSolid = 400394 case FAServerSolid = 400426 case FAShapesSolid = 400677 case FAShareAltSolid = 400333 case FAShareAltSquareSolid = 400837 case FAShareSolid = 400535 case FAShareSquareRegular = 300121 case FAShareSquareSolid = 400700 case FAShekelSignSolid = 400595 case FAShieldAltSolid = 400941 case FAShipSolid = 400213 case FAShippingFastSolid = 400354 case FAShoePrintsSolid = 400755 case FAShoppingBagSolid = 400853 case FAShoppingBasketSolid = 400324 case FAShoppingCartSolid = 400037 case FAShowerSolid = 400088 case FAShuttleVanSolid = 400639 case FASignInAltSolid = 400830 case FASignLanguageSolid = 400098 case FASignOutAltSolid = 400829 case FASignSolid = 400248 case FASignalSolid = 400676 case FASignatureSolid = 400077 case FASimCardSolid = 400827 case FASitemapSolid = 400680 case FASkatingSolid = 400943 case FASkiingNordicSolid = 400360 case FASkiingSolid = 400236 case FASkullCrossbonesSolid = 400411 case FASkullSolid = 400712 case FASlashSolid = 400685 case FASleighSolid = 400678 case FASlidersHSolid = 400519 case FASmileBeamRegular = 300044 case FASmileBeamSolid = 400285 case FASmileRegular = 300080 case FASmileSolid = 400489 case FASmileWinkRegular = 300100 case FASmileWinkSolid = 400586 case FASmogSolid = 400812 case FASmokingBanSolid = 400694 case FASmokingSolid = 400888 case FASmsSolid = 400069 case FASnowboardingSolid = 400576 case FASnowflakeRegular = 300016 case FASnowflakeSolid = 400099 case FASnowmanSolid = 400157 case FASnowplowSolid = 400932 case FASocksSolid = 400181 case FASolarPanelSolid = 400895 case FASortAlphaDownAltSolid = 400205 case FASortAlphaDownSolid = 400866 case FASortAlphaUpAltSolid = 400167 case FASortAlphaUpSolid = 400303 case FASortAmountDownAltSolid = 400713 case FASortAmountDownSolid = 400583 case FASortAmountUpAltSolid = 400345 case FASortAmountUpSolid = 400552 case FASortDownSolid = 400082 case FASortNumericDownAltSolid = 400836 case FASortNumericDownSolid = 400649 case FASortNumericUpAltSolid = 400234 case FASortNumericUpSolid = 400495 case FASortSolid = 400770 case FASortUpSolid = 400330 case FASpaSolid = 400286 case FASpaceShuttleSolid = 400366 case FASpellCheckSolid = 400094 case FASpiderSolid = 400067 case FASpinnerSolid = 400911 case FASplotchSolid = 400211 case FASprayCanSolid = 400428 case FASquareFullSolid = 400885 case FASquareRegular = 300048 case FASquareRootAltSolid = 400023 case FASquareSolid = 400306 case FAStampSolid = 400646 case FAStarAndCrescentSolid = 400365 case FAStarHalfAltSolid = 400212 case FAStarHalfRegular = 300034 case FAStarHalfSolid = 400210 case FAStarOfDavidSolid = 400221 case FAStarOfLifeSolid = 400883 case FAStarRegular = 300150 case FAStarSolid = 400954 case FAStepBackwardSolid = 400051 case FAStepForwardSolid = 400733 case FAStethoscopeSolid = 400527 case FAStickyNoteRegular = 300145 case FAStickyNoteSolid = 400901 case FAStopCircleRegular = 300105 case FAStopCircleSolid = 400617 case FAStopSolid = 400114 case FAStopwatchSolid = 400419 case FAStoreAltSolid = 400729 case FAStoreSolid = 400584 case FAStreamSolid = 400284 case FAStreetViewSolid = 400164 case FAStrikethroughSolid = 400310 case FAStroopwafelSolid = 400085 case FASubscriptSolid = 400632 case FASubwaySolid = 400570 case FASuitcaseRollingSolid = 400688 case FASuitcaseSolid = 400462 case FASunRegular = 300084 case FASunSolid = 400506 case FASuperscriptSolid = 400298 case FASurpriseRegular = 300014 case FASurpriseSolid = 400071 case FASwatchbookSolid = 400156 case FASwimmerSolid = 400442 case FASwimmingPoolSolid = 400150 case FASynagogueSolid = 400402 case FASyncAltSolid = 400802 case FASyncSolid = 400500 case FASyringeSolid = 400451 case FATableSolid = 400877 case FATableTennisSolid = 400453 case FATabletAltSolid = 400553 case FATabletSolid = 400668 case FATabletsSolid = 400301 case FATachometerAltSolid = 400456 case FATagSolid = 400776 case FATagsSolid = 400511 case FATapeSolid = 400852 case FATasksSolid = 400263 case FATaxiSolid = 400412 case FATeethOpenSolid = 400923 case FATeethSolid = 400228 case FATemperatureHighSolid = 400523 case FATemperatureLowSolid = 400928 case FATengeSolid = 400470 case FATerminalSolid = 400270 case FATextHeightSolid = 400578 case FATextWidthSolid = 400327 case FAThLargeSolid = 400467 case FAThListSolid = 400869 case FAThSolid = 400488 case FATheaterMasksSolid = 400913 case FAThermometerEmptySolid = 400673 case FAThermometerFullSolid = 400537 case FAThermometerHalfSolid = 400701 case FAThermometerQuarterSolid = 400691 case FAThermometerSolid = 400343 case FAThermometerThreeQuartersSolid = 400721 case FAThumbsDownRegular = 300017 case FAThumbsDownSolid = 400109 case FAThumbsUpRegular = 300063 case FAThumbsUpSolid = 400387 case FAThumbtackSolid = 400078 case FATicketAltSolid = 400289 case FATimesCircleRegular = 300060 case FATimesCircleSolid = 400372 case FATimesSolid = 400819 case FATintSlashSolid = 400642 case FATintSolid = 400137 case FATiredRegular = 300002 case FATiredSolid = 400020 case FAToggleOffSolid = 400833 case FAToggleOnSolid = 400418 case FAToiletPaperSolid = 400044 case FAToiletSolid = 400463 case FAToolboxSolid = 400116 case FAToolsSolid = 400761 case FAToothSolid = 400351 case FATorahSolid = 400159 case FAToriiGateSolid = 400736 case FATractorSolid = 400337 case FATrademarkSolid = 400879 case FATrafficLightSolid = 400834 case FATrainSolid = 400772 case FATramSolid = 400915 case FATransgenderAltSolid = 400771 case FATransgenderSolid = 400218 case FATrashAltRegular = 300119 case FATrashAltSolid = 400671 case FATrashRestoreAltSolid = 400024 case FATrashRestoreSolid = 400916 case FATrashSolid = 400473 case FATreeSolid = 400087 case FATrophySolid = 400190 case FATruckLoadingSolid = 400013 case FATruckMonsterSolid = 400609 case FATruckMovingSolid = 400939 case FATruckPickupSolid = 400409 case FATruckSolid = 400297 case FATshirtSolid = 400889 case FATtySolid = 400299 case FATvSolid = 400487 case FAUmbrellaBeachSolid = 400375 case FAUmbrellaSolid = 400813 case FAUnderlineSolid = 400413 case FAUndoAltSolid = 400789 case FAUndoSolid = 400814 case FAUniversalAccessSolid = 400055 case FAUniversitySolid = 400807 case FAUnlinkSolid = 400540 case FAUnlockAltSolid = 400378 case FAUnlockSolid = 400311 case FAUploadSolid = 400015 case FAUserAltSlashSolid = 400119 case FAUserAltSolid = 400321 case FAUserAstronautSolid = 400582 case FAUserCheckSolid = 400136 case FAUserCircleRegular = 300027 case FAUserCircleSolid = 400161 case FAUserClockSolid = 400800 case FAUserCogSolid = 400130 case FAUserEditSolid = 400589 case FAUserFriendsSolid = 400169 case FAUserGraduateSolid = 400383 case FAUserInjuredSolid = 400008 case FAUserLockSolid = 400160 case FAUserMdSolid = 400791 case FAUserMinusSolid = 400198 case FAUserNinjaSolid = 400331 case FAUserNurseSolid = 400781 case FAUserPlusSolid = 400543 case FAUserRegular = 300115 case FAUserSecretSolid = 400379 case FAUserShieldSolid = 400759 case FAUserSlashSolid = 400399 case FAUserSolid = 400661 case FAUserTagSolid = 400120 case FAUserTieSolid = 400269 case FAUserTimesSolid = 400146 case FAUsersCogSolid = 400651 case FAUsersSolid = 400725 case FAUtensilSpoonSolid = 400434 case FAUtensilsSolid = 400945 case FAVectorSquareSolid = 400265 case FAVenusDoubleSolid = 400481 case FAVenusMarsSolid = 400944 case FAVenusSolid = 400017 case FAVialSolid = 400593 case FAVialsSolid = 400388 case FAVideoSlashSolid = 400072 case FAVideoSolid = 400751 case FAViharaSolid = 400746 case FAVoicemailSolid = 400376 case FAVolleyballBallSolid = 400502 case FAVolumeDownSolid = 400696 case FAVolumeMuteSolid = 400579 case FAVolumeOffSolid = 400558 case FAVolumeUpSolid = 400743 case FAVoteYeaSolid = 400580 case FAVrCardboardSolid = 400152 case FAWalkingSolid = 400353 case FAWalletSolid = 400281 case FAWarehouseSolid = 400217 case FAWaterSolid = 400256 case FAWaveSquareSolid = 400603 case FAWeightHangingSolid = 400151 case FAWeightSolid = 400452 case FAWheelchairSolid = 400296 case FAWifiSolid = 400479 case FAWindSolid = 400054 case FAWindowCloseRegular = 300123 case FAWindowCloseSolid = 400708 case FAWindowMaximizeRegular = 300010 case FAWindowMaximizeSolid = 400049 case FAWindowMinimizeRegular = 300070 case FAWindowMinimizeSolid = 400430 case FAWindowRestoreRegular = 300089 case FAWindowRestoreSolid = 400525 case FAWineBottleSolid = 400073 case FAWineGlassAltSolid = 400258 case FAWineGlassSolid = 400624 case FAWonSignSolid = 400790 case FAWrenchSolid = 400544 case FAXRaySolid = 400715 case FAYenSignSolid = 400864 case FAYinYangSolid = 400619 func string() -> String { let icons = [ FAIcon.FAAdSolid: "\u{f641}", FAIcon.FAAddressBookRegular: "\u{f2b9}", FAIcon.FAAddressBookSolid: "\u{f2b9}", FAIcon.FAAddressCardRegular: "\u{f2bb}", FAIcon.FAAddressCardSolid: "\u{f2bb}", FAIcon.FAAdjustSolid: "\u{f042}", FAIcon.FAAirFreshenerSolid: "\u{f5d0}", FAIcon.FAAlignCenterSolid: "\u{f037}", FAIcon.FAAlignJustifySolid: "\u{f039}", FAIcon.FAAlignLeftSolid: "\u{f036}", FAIcon.FAAlignRightSolid: "\u{f038}", FAIcon.FAAllergiesSolid: "\u{f461}", FAIcon.FAAmbulanceSolid: "\u{f0f9}", FAIcon.FAAmericanSignLanguageInterpretingSolid: "\u{f2a3}", FAIcon.FAAnchorSolid: "\u{f13d}", FAIcon.FAAngleDoubleDownSolid: "\u{f103}", FAIcon.FAAngleDoubleLeftSolid: "\u{f100}", FAIcon.FAAngleDoubleRightSolid: "\u{f101}", FAIcon.FAAngleDoubleUpSolid: "\u{f102}", FAIcon.FAAngleDownSolid: "\u{f107}", FAIcon.FAAngleLeftSolid: "\u{f104}", FAIcon.FAAngleRightSolid: "\u{f105}", FAIcon.FAAngleUpSolid: "\u{f106}", FAIcon.FAAngryRegular: "\u{f556}", FAIcon.FAAngrySolid: "\u{f556}", FAIcon.FAAnkhSolid: "\u{f644}", FAIcon.FAAppleAltSolid: "\u{f5d1}", FAIcon.FAArchiveSolid: "\u{f187}", FAIcon.FAArchwaySolid: "\u{f557}", FAIcon.FAArrowAltCircleDownRegular: "\u{f358}", FAIcon.FAArrowAltCircleDownSolid: "\u{f358}", FAIcon.FAArrowAltCircleLeftRegular: "\u{f359}", FAIcon.FAArrowAltCircleLeftSolid: "\u{f359}", FAIcon.FAArrowAltCircleRightRegular: "\u{f35a}", FAIcon.FAArrowAltCircleRightSolid: "\u{f35a}", FAIcon.FAArrowAltCircleUpRegular: "\u{f35b}", FAIcon.FAArrowAltCircleUpSolid: "\u{f35b}", FAIcon.FAArrowCircleDownSolid: "\u{f0ab}", FAIcon.FAArrowCircleLeftSolid: "\u{f0a8}", FAIcon.FAArrowCircleRightSolid: "\u{f0a9}", FAIcon.FAArrowCircleUpSolid: "\u{f0aa}", FAIcon.FAArrowDownSolid: "\u{f063}", FAIcon.FAArrowLeftSolid: "\u{f060}", FAIcon.FAArrowRightSolid: "\u{f061}", FAIcon.FAArrowUpSolid: "\u{f062}", FAIcon.FAArrowsAltHSolid: "\u{f337}", FAIcon.FAArrowsAltSolid: "\u{f0b2}", FAIcon.FAArrowsAltVSolid: "\u{f338}", FAIcon.FAAssistiveListeningSystemsSolid: "\u{f2a2}", FAIcon.FAAsteriskSolid: "\u{f069}", FAIcon.FAAtSolid: "\u{f1fa}", FAIcon.FAAtlasSolid: "\u{f558}", FAIcon.FAAtomSolid: "\u{f5d2}", FAIcon.FAAudioDescriptionSolid: "\u{f29e}", FAIcon.FAAwardSolid: "\u{f559}", FAIcon.FABabyCarriageSolid: "\u{f77d}", FAIcon.FABabySolid: "\u{f77c}", FAIcon.FABackspaceSolid: "\u{f55a}", FAIcon.FABackwardSolid: "\u{f04a}", FAIcon.FABaconSolid: "\u{f7e5}", FAIcon.FABalanceScaleLeftSolid: "\u{f515}", FAIcon.FABalanceScaleRightSolid: "\u{f516}", FAIcon.FABalanceScaleSolid: "\u{f24e}", FAIcon.FABanSolid: "\u{f05e}", FAIcon.FABandAidSolid: "\u{f462}", FAIcon.FABarcodeSolid: "\u{f02a}", FAIcon.FABarsSolid: "\u{f0c9}", FAIcon.FABaseballBallSolid: "\u{f433}", FAIcon.FABasketballBallSolid: "\u{f434}", FAIcon.FABathSolid: "\u{f2cd}", FAIcon.FABatteryEmptySolid: "\u{f244}", FAIcon.FABatteryFullSolid: "\u{f240}", FAIcon.FABatteryHalfSolid: "\u{f242}", FAIcon.FABatteryQuarterSolid: "\u{f243}", FAIcon.FABatteryThreeQuartersSolid: "\u{f241}", FAIcon.FABedSolid: "\u{f236}", FAIcon.FABeerSolid: "\u{f0fc}", FAIcon.FABellRegular: "\u{f0f3}", FAIcon.FABellSlashRegular: "\u{f1f6}", FAIcon.FABellSlashSolid: "\u{f1f6}", FAIcon.FABellSolid: "\u{f0f3}", FAIcon.FABezierCurveSolid: "\u{f55b}", FAIcon.FABibleSolid: "\u{f647}", FAIcon.FABicycleSolid: "\u{f206}", FAIcon.FABikingSolid: "\u{f84a}", FAIcon.FABinocularsSolid: "\u{f1e5}", FAIcon.FABiohazardSolid: "\u{f780}", FAIcon.FABirthdayCakeSolid: "\u{f1fd}", FAIcon.FABlenderPhoneSolid: "\u{f6b6}", FAIcon.FABlenderSolid: "\u{f517}", FAIcon.FABlindSolid: "\u{f29d}", FAIcon.FABlogSolid: "\u{f781}", FAIcon.FABoldSolid: "\u{f032}", FAIcon.FABoltSolid: "\u{f0e7}", FAIcon.FABombSolid: "\u{f1e2}", FAIcon.FABoneSolid: "\u{f5d7}", FAIcon.FABongSolid: "\u{f55c}", FAIcon.FABookDeadSolid: "\u{f6b7}", FAIcon.FABookMedicalSolid: "\u{f7e6}", FAIcon.FABookOpenSolid: "\u{f518}", FAIcon.FABookReaderSolid: "\u{f5da}", FAIcon.FABookSolid: "\u{f02d}", FAIcon.FABookmarkRegular: "\u{f02e}", FAIcon.FABookmarkSolid: "\u{f02e}", FAIcon.FABorderAllSolid: "\u{f84c}", FAIcon.FABorderNoneSolid: "\u{f850}", FAIcon.FABorderStyleSolid: "\u{f853}", FAIcon.FABowlingBallSolid: "\u{f436}", FAIcon.FABoxOpenSolid: "\u{f49e}", FAIcon.FABoxSolid: "\u{f466}", FAIcon.FABoxesSolid: "\u{f468}", FAIcon.FABrailleSolid: "\u{f2a1}", FAIcon.FABrainSolid: "\u{f5dc}", FAIcon.FABrands500px: "\u{f26e}", FAIcon.FABrandsAccessibleIcon: "\u{f368}", FAIcon.FABrandsAccusoft: "\u{f369}", FAIcon.FABrandsAcquisitionsIncorporated: "\u{f6af}", FAIcon.FABrandsAdn: "\u{f170}", FAIcon.FABrandsAdobe: "\u{f778}", FAIcon.FABrandsAdversal: "\u{f36a}", FAIcon.FABrandsAffiliatetheme: "\u{f36b}", FAIcon.FABrandsAirbnb: "\u{f834}", FAIcon.FABrandsAlgolia: "\u{f36c}", FAIcon.FABrandsAlipay: "\u{f642}", FAIcon.FABrandsAmazon: "\u{f270}", FAIcon.FABrandsAmazonPay: "\u{f42c}", FAIcon.FABrandsAmilia: "\u{f36d}", FAIcon.FABrandsAndroid: "\u{f17b}", FAIcon.FABrandsAngellist: "\u{f209}", FAIcon.FABrandsAngrycreative: "\u{f36e}", FAIcon.FABrandsAngular: "\u{f420}", FAIcon.FABrandsAppStore: "\u{f36f}", FAIcon.FABrandsAppStoreIos: "\u{f370}", FAIcon.FABrandsApper: "\u{f371}", FAIcon.FABrandsApple: "\u{f179}", FAIcon.FABrandsApplePay: "\u{f415}", FAIcon.FABrandsArtstation: "\u{f77a}", FAIcon.FABrandsAsymmetrik: "\u{f372}", FAIcon.FABrandsAtlassian: "\u{f77b}", FAIcon.FABrandsAudible: "\u{f373}", FAIcon.FABrandsAutoprefixer: "\u{f41c}", FAIcon.FABrandsAvianex: "\u{f374}", FAIcon.FABrandsAviato: "\u{f421}", FAIcon.FABrandsAws: "\u{f375}", FAIcon.FABrandsBandcamp: "\u{f2d5}", FAIcon.FABrandsBattleNet: "\u{f835}", FAIcon.FABrandsBehance: "\u{f1b4}", FAIcon.FABrandsBehanceSquare: "\u{f1b5}", FAIcon.FABrandsBimobject: "\u{f378}", FAIcon.FABrandsBitbucket: "\u{f171}", FAIcon.FABrandsBitcoin: "\u{f379}", FAIcon.FABrandsBity: "\u{f37a}", FAIcon.FABrandsBlackTie: "\u{f27e}", FAIcon.FABrandsBlackberry: "\u{f37b}", FAIcon.FABrandsBlogger: "\u{f37c}", FAIcon.FABrandsBloggerB: "\u{f37d}", FAIcon.FABrandsBluetooth: "\u{f293}", FAIcon.FABrandsBluetoothB: "\u{f294}", FAIcon.FABrandsBootstrap: "\u{f836}", FAIcon.FABrandsBtc: "\u{f15a}", FAIcon.FABrandsBuffer: "\u{f837}", FAIcon.FABrandsBuromobelexperte: "\u{f37f}", FAIcon.FABrandsBuyNLarge: "\u{f8a6}", FAIcon.FABrandsBuysellads: "\u{f20d}", FAIcon.FABrandsCanadianMapleLeaf: "\u{f785}", FAIcon.FABrandsCcAmazonPay: "\u{f42d}", FAIcon.FABrandsCcAmex: "\u{f1f3}", FAIcon.FABrandsCcApplePay: "\u{f416}", FAIcon.FABrandsCcDinersClub: "\u{f24c}", FAIcon.FABrandsCcDiscover: "\u{f1f2}", FAIcon.FABrandsCcJcb: "\u{f24b}", FAIcon.FABrandsCcMastercard: "\u{f1f1}", FAIcon.FABrandsCcPaypal: "\u{f1f4}", FAIcon.FABrandsCcStripe: "\u{f1f5}", FAIcon.FABrandsCcVisa: "\u{f1f0}", FAIcon.FABrandsCentercode: "\u{f380}", FAIcon.FABrandsCentos: "\u{f789}", FAIcon.FABrandsChrome: "\u{f268}", FAIcon.FABrandsChromecast: "\u{f838}", FAIcon.FABrandsCloudscale: "\u{f383}", FAIcon.FABrandsCloudsmith: "\u{f384}", FAIcon.FABrandsCloudversify: "\u{f385}", FAIcon.FABrandsCodepen: "\u{f1cb}", FAIcon.FABrandsCodiepie: "\u{f284}", FAIcon.FABrandsConfluence: "\u{f78d}", FAIcon.FABrandsConnectdevelop: "\u{f20e}", FAIcon.FABrandsContao: "\u{f26d}", FAIcon.FABrandsCottonBureau: "\u{f89e}", FAIcon.FABrandsCpanel: "\u{f388}", FAIcon.FABrandsCreativeCommons: "\u{f25e}", FAIcon.FABrandsCreativeCommonsBy: "\u{f4e7}", FAIcon.FABrandsCreativeCommonsNc: "\u{f4e8}", FAIcon.FABrandsCreativeCommonsNcEu: "\u{f4e9}", FAIcon.FABrandsCreativeCommonsNcJp: "\u{f4ea}", FAIcon.FABrandsCreativeCommonsNd: "\u{f4eb}", FAIcon.FABrandsCreativeCommonsPd: "\u{f4ec}", FAIcon.FABrandsCreativeCommonsPdAlt: "\u{f4ed}", FAIcon.FABrandsCreativeCommonsRemix: "\u{f4ee}", FAIcon.FABrandsCreativeCommonsSa: "\u{f4ef}", FAIcon.FABrandsCreativeCommonsSampling: "\u{f4f0}", FAIcon.FABrandsCreativeCommonsSamplingPlus: "\u{f4f1}", FAIcon.FABrandsCreativeCommonsShare: "\u{f4f2}", FAIcon.FABrandsCreativeCommonsZero: "\u{f4f3}", FAIcon.FABrandsCriticalRole: "\u{f6c9}", FAIcon.FABrandsCss3: "\u{f13c}", FAIcon.FABrandsCss3Alt: "\u{f38b}", FAIcon.FABrandsCuttlefish: "\u{f38c}", FAIcon.FABrandsDAndD: "\u{f38d}", FAIcon.FABrandsDAndDBeyond: "\u{f6ca}", FAIcon.FABrandsDashcube: "\u{f210}", FAIcon.FABrandsDelicious: "\u{f1a5}", FAIcon.FABrandsDeploydog: "\u{f38e}", FAIcon.FABrandsDeskpro: "\u{f38f}", FAIcon.FABrandsDev: "\u{f6cc}", FAIcon.FABrandsDeviantart: "\u{f1bd}", FAIcon.FABrandsDhl: "\u{f790}", FAIcon.FABrandsDiaspora: "\u{f791}", FAIcon.FABrandsDigg: "\u{f1a6}", FAIcon.FABrandsDigitalOcean: "\u{f391}", FAIcon.FABrandsDiscord: "\u{f392}", FAIcon.FABrandsDiscourse: "\u{f393}", FAIcon.FABrandsDochub: "\u{f394}", FAIcon.FABrandsDocker: "\u{f395}", FAIcon.FABrandsDraft2digital: "\u{f396}", FAIcon.FABrandsDribbble: "\u{f17d}", FAIcon.FABrandsDribbbleSquare: "\u{f397}", FAIcon.FABrandsDropbox: "\u{f16b}", FAIcon.FABrandsDrupal: "\u{f1a9}", FAIcon.FABrandsDyalog: "\u{f399}", FAIcon.FABrandsEarlybirds: "\u{f39a}", FAIcon.FABrandsEbay: "\u{f4f4}", FAIcon.FABrandsEdge: "\u{f282}", FAIcon.FABrandsElementor: "\u{f430}", FAIcon.FABrandsEllo: "\u{f5f1}", FAIcon.FABrandsEmber: "\u{f423}", FAIcon.FABrandsEmpire: "\u{f1d1}", FAIcon.FABrandsEnvira: "\u{f299}", FAIcon.FABrandsErlang: "\u{f39d}", FAIcon.FABrandsEthereum: "\u{f42e}", FAIcon.FABrandsEtsy: "\u{f2d7}", FAIcon.FABrandsEvernote: "\u{f839}", FAIcon.FABrandsExpeditedssl: "\u{f23e}", FAIcon.FABrandsFacebook: "\u{f09a}", FAIcon.FABrandsFacebookF: "\u{f39e}", FAIcon.FABrandsFacebookMessenger: "\u{f39f}", FAIcon.FABrandsFacebookSquare: "\u{f082}", FAIcon.FABrandsFantasyFlightGames: "\u{f6dc}", FAIcon.FABrandsFedex: "\u{f797}", FAIcon.FABrandsFedora: "\u{f798}", FAIcon.FABrandsFigma: "\u{f799}", FAIcon.FABrandsFirefox: "\u{f269}", FAIcon.FABrandsFirstOrder: "\u{f2b0}", FAIcon.FABrandsFirstOrderAlt: "\u{f50a}", FAIcon.FABrandsFirstdraft: "\u{f3a1}", FAIcon.FABrandsFlickr: "\u{f16e}", FAIcon.FABrandsFlipboard: "\u{f44d}", FAIcon.FABrandsFly: "\u{f417}", FAIcon.FABrandsFontAwesome: "\u{f2b4}", FAIcon.FABrandsFontAwesomeAlt: "\u{f35c}", FAIcon.FABrandsFontAwesomeFlag: "\u{f425}", FAIcon.FABrandsFonticons: "\u{f280}", FAIcon.FABrandsFonticonsFi: "\u{f3a2}", FAIcon.FABrandsFortAwesome: "\u{f286}", FAIcon.FABrandsFortAwesomeAlt: "\u{f3a3}", FAIcon.FABrandsForumbee: "\u{f211}", FAIcon.FABrandsFoursquare: "\u{f180}", FAIcon.FABrandsFreeCodeCamp: "\u{f2c5}", FAIcon.FABrandsFreebsd: "\u{f3a4}", FAIcon.FABrandsFulcrum: "\u{f50b}", FAIcon.FABrandsGalacticRepublic: "\u{f50c}", FAIcon.FABrandsGalacticSenate: "\u{f50d}", FAIcon.FABrandsGetPocket: "\u{f265}", FAIcon.FABrandsGg: "\u{f260}", FAIcon.FABrandsGgCircle: "\u{f261}", FAIcon.FABrandsGit: "\u{f1d3}", FAIcon.FABrandsGitAlt: "\u{f841}", FAIcon.FABrandsGitSquare: "\u{f1d2}", FAIcon.FABrandsGithub: "\u{f09b}", FAIcon.FABrandsGithubAlt: "\u{f113}", FAIcon.FABrandsGithubSquare: "\u{f092}", FAIcon.FABrandsGitkraken: "\u{f3a6}", FAIcon.FABrandsGitlab: "\u{f296}", FAIcon.FABrandsGitter: "\u{f426}", FAIcon.FABrandsGlide: "\u{f2a5}", FAIcon.FABrandsGlideG: "\u{f2a6}", FAIcon.FABrandsGofore: "\u{f3a7}", FAIcon.FABrandsGoodreads: "\u{f3a8}", FAIcon.FABrandsGoodreadsG: "\u{f3a9}", FAIcon.FABrandsGoogle: "\u{f1a0}", FAIcon.FABrandsGoogleDrive: "\u{f3aa}", FAIcon.FABrandsGooglePlay: "\u{f3ab}", FAIcon.FABrandsGooglePlus: "\u{f2b3}", FAIcon.FABrandsGooglePlusG: "\u{f0d5}", FAIcon.FABrandsGooglePlusSquare: "\u{f0d4}", FAIcon.FABrandsGoogleWallet: "\u{f1ee}", FAIcon.FABrandsGratipay: "\u{f184}", FAIcon.FABrandsGrav: "\u{f2d6}", FAIcon.FABrandsGripfire: "\u{f3ac}", FAIcon.FABrandsGrunt: "\u{f3ad}", FAIcon.FABrandsGulp: "\u{f3ae}", FAIcon.FABrandsHackerNews: "\u{f1d4}", FAIcon.FABrandsHackerNewsSquare: "\u{f3af}", FAIcon.FABrandsHackerrank: "\u{f5f7}", FAIcon.FABrandsHips: "\u{f452}", FAIcon.FABrandsHireAHelper: "\u{f3b0}", FAIcon.FABrandsHooli: "\u{f427}", FAIcon.FABrandsHornbill: "\u{f592}", FAIcon.FABrandsHotjar: "\u{f3b1}", FAIcon.FABrandsHouzz: "\u{f27c}", FAIcon.FABrandsHtml5: "\u{f13b}", FAIcon.FABrandsHubspot: "\u{f3b2}", FAIcon.FABrandsImdb: "\u{f2d8}", FAIcon.FABrandsInstagram: "\u{f16d}", FAIcon.FABrandsIntercom: "\u{f7af}", FAIcon.FABrandsInternetExplorer: "\u{f26b}", FAIcon.FABrandsInvision: "\u{f7b0}", FAIcon.FABrandsIoxhost: "\u{f208}", FAIcon.FABrandsItchIo: "\u{f83a}", FAIcon.FABrandsItunes: "\u{f3b4}", FAIcon.FABrandsItunesNote: "\u{f3b5}", FAIcon.FABrandsJava: "\u{f4e4}", FAIcon.FABrandsJediOrder: "\u{f50e}", FAIcon.FABrandsJenkins: "\u{f3b6}", FAIcon.FABrandsJira: "\u{f7b1}", FAIcon.FABrandsJoget: "\u{f3b7}", FAIcon.FABrandsJoomla: "\u{f1aa}", FAIcon.FABrandsJs: "\u{f3b8}", FAIcon.FABrandsJsSquare: "\u{f3b9}", FAIcon.FABrandsJsfiddle: "\u{f1cc}", FAIcon.FABrandsKaggle: "\u{f5fa}", FAIcon.FABrandsKeybase: "\u{f4f5}", FAIcon.FABrandsKeycdn: "\u{f3ba}", FAIcon.FABrandsKickstarter: "\u{f3bb}", FAIcon.FABrandsKickstarterK: "\u{f3bc}", FAIcon.FABrandsKorvue: "\u{f42f}", FAIcon.FABrandsLaravel: "\u{f3bd}", FAIcon.FABrandsLastfm: "\u{f202}", FAIcon.FABrandsLastfmSquare: "\u{f203}", FAIcon.FABrandsLeanpub: "\u{f212}", FAIcon.FABrandsLess: "\u{f41d}", FAIcon.FABrandsLine: "\u{f3c0}", FAIcon.FABrandsLinkedin: "\u{f08c}", FAIcon.FABrandsLinkedinIn: "\u{f0e1}", FAIcon.FABrandsLinode: "\u{f2b8}", FAIcon.FABrandsLinux: "\u{f17c}", FAIcon.FABrandsLyft: "\u{f3c3}", FAIcon.FABrandsMagento: "\u{f3c4}", FAIcon.FABrandsMailchimp: "\u{f59e}", FAIcon.FABrandsMandalorian: "\u{f50f}", FAIcon.FABrandsMarkdown: "\u{f60f}", FAIcon.FABrandsMastodon: "\u{f4f6}", FAIcon.FABrandsMaxcdn: "\u{f136}", FAIcon.FABrandsMdb: "\u{f8ca}", FAIcon.FABrandsMedapps: "\u{f3c6}", FAIcon.FABrandsMedium: "\u{f23a}", FAIcon.FABrandsMediumM: "\u{f3c7}", FAIcon.FABrandsMedrt: "\u{f3c8}", FAIcon.FABrandsMeetup: "\u{f2e0}", FAIcon.FABrandsMegaport: "\u{f5a3}", FAIcon.FABrandsMendeley: "\u{f7b3}", FAIcon.FABrandsMicrosoft: "\u{f3ca}", FAIcon.FABrandsMix: "\u{f3cb}", FAIcon.FABrandsMixcloud: "\u{f289}", FAIcon.FABrandsMizuni: "\u{f3cc}", FAIcon.FABrandsModx: "\u{f285}", FAIcon.FABrandsMonero: "\u{f3d0}", FAIcon.FABrandsNapster: "\u{f3d2}", FAIcon.FABrandsNeos: "\u{f612}", FAIcon.FABrandsNimblr: "\u{f5a8}", FAIcon.FABrandsNode: "\u{f419}", FAIcon.FABrandsNodeJs: "\u{f3d3}", FAIcon.FABrandsNpm: "\u{f3d4}", FAIcon.FABrandsNs8: "\u{f3d5}", FAIcon.FABrandsNutritionix: "\u{f3d6}", FAIcon.FABrandsOdnoklassniki: "\u{f263}", FAIcon.FABrandsOdnoklassnikiSquare: "\u{f264}", FAIcon.FABrandsOldRepublic: "\u{f510}", FAIcon.FABrandsOpencart: "\u{f23d}", FAIcon.FABrandsOpenid: "\u{f19b}", FAIcon.FABrandsOpera: "\u{f26a}", FAIcon.FABrandsOptinMonster: "\u{f23c}", FAIcon.FABrandsOrcid: "\u{f8d2}", FAIcon.FABrandsOsi: "\u{f41a}", FAIcon.FABrandsPage4: "\u{f3d7}", FAIcon.FABrandsPagelines: "\u{f18c}", FAIcon.FABrandsPalfed: "\u{f3d8}", FAIcon.FABrandsPatreon: "\u{f3d9}", FAIcon.FABrandsPaypal: "\u{f1ed}", FAIcon.FABrandsPennyArcade: "\u{f704}", FAIcon.FABrandsPeriscope: "\u{f3da}", FAIcon.FABrandsPhabricator: "\u{f3db}", FAIcon.FABrandsPhoenixFramework: "\u{f3dc}", FAIcon.FABrandsPhoenixSquadron: "\u{f511}", FAIcon.FABrandsPhp: "\u{f457}", FAIcon.FABrandsPiedPiper: "\u{f2ae}", FAIcon.FABrandsPiedPiperAlt: "\u{f1a8}", FAIcon.FABrandsPiedPiperHat: "\u{f4e5}", FAIcon.FABrandsPiedPiperPp: "\u{f1a7}", FAIcon.FABrandsPinterest: "\u{f0d2}", FAIcon.FABrandsPinterestP: "\u{f231}", FAIcon.FABrandsPinterestSquare: "\u{f0d3}", FAIcon.FABrandsPlaystation: "\u{f3df}", FAIcon.FABrandsProductHunt: "\u{f288}", FAIcon.FABrandsPushed: "\u{f3e1}", FAIcon.FABrandsPython: "\u{f3e2}", FAIcon.FABrandsQq: "\u{f1d6}", FAIcon.FABrandsQuinscape: "\u{f459}", FAIcon.FABrandsQuora: "\u{f2c4}", FAIcon.FABrandsRProject: "\u{f4f7}", FAIcon.FABrandsRaspberryPi: "\u{f7bb}", FAIcon.FABrandsRavelry: "\u{f2d9}", FAIcon.FABrandsReact: "\u{f41b}", FAIcon.FABrandsReacteurope: "\u{f75d}", FAIcon.FABrandsReadme: "\u{f4d5}", FAIcon.FABrandsRebel: "\u{f1d0}", FAIcon.FABrandsRedRiver: "\u{f3e3}", FAIcon.FABrandsReddit: "\u{f1a1}", FAIcon.FABrandsRedditAlien: "\u{f281}", FAIcon.FABrandsRedditSquare: "\u{f1a2}", FAIcon.FABrandsRedhat: "\u{f7bc}", FAIcon.FABrandsRenren: "\u{f18b}", FAIcon.FABrandsReplyd: "\u{f3e6}", FAIcon.FABrandsResearchgate: "\u{f4f8}", FAIcon.FABrandsResolving: "\u{f3e7}", FAIcon.FABrandsRev: "\u{f5b2}", FAIcon.FABrandsRocketchat: "\u{f3e8}", FAIcon.FABrandsRockrms: "\u{f3e9}", FAIcon.FABrandsSafari: "\u{f267}", FAIcon.FABrandsSalesforce: "\u{f83b}", FAIcon.FABrandsSass: "\u{f41e}", FAIcon.FABrandsSchlix: "\u{f3ea}", FAIcon.FABrandsScribd: "\u{f28a}", FAIcon.FABrandsSearchengin: "\u{f3eb}", FAIcon.FABrandsSellcast: "\u{f2da}", FAIcon.FABrandsSellsy: "\u{f213}", FAIcon.FABrandsServicestack: "\u{f3ec}", FAIcon.FABrandsShirtsinbulk: "\u{f214}", FAIcon.FABrandsShopware: "\u{f5b5}", FAIcon.FABrandsSimplybuilt: "\u{f215}", FAIcon.FABrandsSistrix: "\u{f3ee}", FAIcon.FABrandsSith: "\u{f512}", FAIcon.FABrandsSketch: "\u{f7c6}", FAIcon.FABrandsSkyatlas: "\u{f216}", FAIcon.FABrandsSkype: "\u{f17e}", FAIcon.FABrandsSlack: "\u{f198}", FAIcon.FABrandsSlackHash: "\u{f3ef}", FAIcon.FABrandsSlideshare: "\u{f1e7}", FAIcon.FABrandsSnapchat: "\u{f2ab}", FAIcon.FABrandsSnapchatGhost: "\u{f2ac}", FAIcon.FABrandsSnapchatSquare: "\u{f2ad}", FAIcon.FABrandsSoundcloud: "\u{f1be}", FAIcon.FABrandsSourcetree: "\u{f7d3}", FAIcon.FABrandsSpeakap: "\u{f3f3}", FAIcon.FABrandsSpeakerDeck: "\u{f83c}", FAIcon.FABrandsSpotify: "\u{f1bc}", FAIcon.FABrandsSquarespace: "\u{f5be}", FAIcon.FABrandsStackExchange: "\u{f18d}", FAIcon.FABrandsStackOverflow: "\u{f16c}", FAIcon.FABrandsStackpath: "\u{f842}", FAIcon.FABrandsStaylinked: "\u{f3f5}", FAIcon.FABrandsSteam: "\u{f1b6}", FAIcon.FABrandsSteamSquare: "\u{f1b7}", FAIcon.FABrandsSteamSymbol: "\u{f3f6}", FAIcon.FABrandsStickerMule: "\u{f3f7}", FAIcon.FABrandsStrava: "\u{f428}", FAIcon.FABrandsStripe: "\u{f429}", FAIcon.FABrandsStripeS: "\u{f42a}", FAIcon.FABrandsStudiovinari: "\u{f3f8}", FAIcon.FABrandsStumbleupon: "\u{f1a4}", FAIcon.FABrandsStumbleuponCircle: "\u{f1a3}", FAIcon.FABrandsSuperpowers: "\u{f2dd}", FAIcon.FABrandsSupple: "\u{f3f9}", FAIcon.FABrandsSuse: "\u{f7d6}", FAIcon.FABrandsSwift: "\u{f8e1}", FAIcon.FABrandsSymfony: "\u{f83d}", FAIcon.FABrandsTeamspeak: "\u{f4f9}", FAIcon.FABrandsTelegram: "\u{f2c6}", FAIcon.FABrandsTelegramPlane: "\u{f3fe}", FAIcon.FABrandsTencentWeibo: "\u{f1d5}", FAIcon.FABrandsTheRedYeti: "\u{f69d}", FAIcon.FABrandsThemeco: "\u{f5c6}", FAIcon.FABrandsThemeisle: "\u{f2b2}", FAIcon.FABrandsThinkPeaks: "\u{f731}", FAIcon.FABrandsTradeFederation: "\u{f513}", FAIcon.FABrandsTrello: "\u{f181}", FAIcon.FABrandsTripadvisor: "\u{f262}", FAIcon.FABrandsTumblr: "\u{f173}", FAIcon.FABrandsTumblrSquare: "\u{f174}", FAIcon.FABrandsTwitch: "\u{f1e8}", FAIcon.FABrandsTwitter: "\u{f099}", FAIcon.FABrandsTwitterSquare: "\u{f081}", FAIcon.FABrandsTypo3: "\u{f42b}", FAIcon.FABrandsUber: "\u{f402}", FAIcon.FABrandsUbuntu: "\u{f7df}", FAIcon.FABrandsUikit: "\u{f403}", FAIcon.FABrandsUmbraco: "\u{f8e8}", FAIcon.FABrandsUniregistry: "\u{f404}", FAIcon.FABrandsUntappd: "\u{f405}", FAIcon.FABrandsUps: "\u{f7e0}", FAIcon.FABrandsUsb: "\u{f287}", FAIcon.FABrandsUsps: "\u{f7e1}", FAIcon.FABrandsUssunnah: "\u{f407}", FAIcon.FABrandsVaadin: "\u{f408}", FAIcon.FABrandsViacoin: "\u{f237}", FAIcon.FABrandsViadeo: "\u{f2a9}", FAIcon.FABrandsViadeoSquare: "\u{f2aa}", FAIcon.FABrandsViber: "\u{f409}", FAIcon.FABrandsVimeo: "\u{f40a}", FAIcon.FABrandsVimeoSquare: "\u{f194}", FAIcon.FABrandsVimeoV: "\u{f27d}", FAIcon.FABrandsVine: "\u{f1ca}", FAIcon.FABrandsVk: "\u{f189}", FAIcon.FABrandsVnv: "\u{f40b}", FAIcon.FABrandsVuejs: "\u{f41f}", FAIcon.FABrandsWaze: "\u{f83f}", FAIcon.FABrandsWeebly: "\u{f5cc}", FAIcon.FABrandsWeibo: "\u{f18a}", FAIcon.FABrandsWeixin: "\u{f1d7}", FAIcon.FABrandsWhatsapp: "\u{f232}", FAIcon.FABrandsWhatsappSquare: "\u{f40c}", FAIcon.FABrandsWhmcs: "\u{f40d}", FAIcon.FABrandsWikipediaW: "\u{f266}", FAIcon.FABrandsWindows: "\u{f17a}", FAIcon.FABrandsWix: "\u{f5cf}", FAIcon.FABrandsWizardsOfTheCoast: "\u{f730}", FAIcon.FABrandsWolfPackBattalion: "\u{f514}", FAIcon.FABrandsWordpress: "\u{f19a}", FAIcon.FABrandsWordpressSimple: "\u{f411}", FAIcon.FABrandsWpbeginner: "\u{f297}", FAIcon.FABrandsWpexplorer: "\u{f2de}", FAIcon.FABrandsWpforms: "\u{f298}", FAIcon.FABrandsWpressr: "\u{f3e4}", FAIcon.FABrandsXbox: "\u{f412}", FAIcon.FABrandsXing: "\u{f168}", FAIcon.FABrandsXingSquare: "\u{f169}", FAIcon.FABrandsYCombinator: "\u{f23b}", FAIcon.FABrandsYahoo: "\u{f19e}", FAIcon.FABrandsYammer: "\u{f840}", FAIcon.FABrandsYandex: "\u{f413}", FAIcon.FABrandsYandexInternational: "\u{f414}", FAIcon.FABrandsYarn: "\u{f7e3}", FAIcon.FABrandsYelp: "\u{f1e9}", FAIcon.FABrandsYoast: "\u{f2b1}", FAIcon.FABrandsYoutube: "\u{f167}", FAIcon.FABrandsYoutubeSquare: "\u{f431}", FAIcon.FABrandsZhihu: "\u{f63f}", FAIcon.FABreadSliceSolid: "\u{f7ec}", FAIcon.FABriefcaseMedicalSolid: "\u{f469}", FAIcon.FABriefcaseSolid: "\u{f0b1}", FAIcon.FABroadcastTowerSolid: "\u{f519}", FAIcon.FABroomSolid: "\u{f51a}", FAIcon.FABrushSolid: "\u{f55d}", FAIcon.FABugSolid: "\u{f188}", FAIcon.FABuildingRegular: "\u{f1ad}", FAIcon.FABuildingSolid: "\u{f1ad}", FAIcon.FABullhornSolid: "\u{f0a1}", FAIcon.FABullseyeSolid: "\u{f140}", FAIcon.FABurnSolid: "\u{f46a}", FAIcon.FABusAltSolid: "\u{f55e}", FAIcon.FABusSolid: "\u{f207}", FAIcon.FABusinessTimeSolid: "\u{f64a}", FAIcon.FACalculatorSolid: "\u{f1ec}", FAIcon.FACalendarAltRegular: "\u{f073}", FAIcon.FACalendarAltSolid: "\u{f073}", FAIcon.FACalendarCheckRegular: "\u{f274}", FAIcon.FACalendarCheckSolid: "\u{f274}", FAIcon.FACalendarDaySolid: "\u{f783}", FAIcon.FACalendarMinusRegular: "\u{f272}", FAIcon.FACalendarMinusSolid: "\u{f272}", FAIcon.FACalendarPlusRegular: "\u{f271}", FAIcon.FACalendarPlusSolid: "\u{f271}", FAIcon.FACalendarRegular: "\u{f133}", FAIcon.FACalendarSolid: "\u{f133}", FAIcon.FACalendarTimesRegular: "\u{f273}", FAIcon.FACalendarTimesSolid: "\u{f273}", FAIcon.FACalendarWeekSolid: "\u{f784}", FAIcon.FACameraRetroSolid: "\u{f083}", FAIcon.FACameraSolid: "\u{f030}", FAIcon.FACampgroundSolid: "\u{f6bb}", FAIcon.FACandyCaneSolid: "\u{f786}", FAIcon.FACannabisSolid: "\u{f55f}", FAIcon.FACapsulesSolid: "\u{f46b}", FAIcon.FACarAltSolid: "\u{f5de}", FAIcon.FACarBatterySolid: "\u{f5df}", FAIcon.FACarCrashSolid: "\u{f5e1}", FAIcon.FACarSideSolid: "\u{f5e4}", FAIcon.FACarSolid: "\u{f1b9}", FAIcon.FACaretDownSolid: "\u{f0d7}", FAIcon.FACaretLeftSolid: "\u{f0d9}", FAIcon.FACaretRightSolid: "\u{f0da}", FAIcon.FACaretSquareDownRegular: "\u{f150}", FAIcon.FACaretSquareDownSolid: "\u{f150}", FAIcon.FACaretSquareLeftRegular: "\u{f191}", FAIcon.FACaretSquareLeftSolid: "\u{f191}", FAIcon.FACaretSquareRightRegular: "\u{f152}", FAIcon.FACaretSquareRightSolid: "\u{f152}", FAIcon.FACaretSquareUpRegular: "\u{f151}", FAIcon.FACaretSquareUpSolid: "\u{f151}", FAIcon.FACaretUpSolid: "\u{f0d8}", FAIcon.FACarrotSolid: "\u{f787}", FAIcon.FACartArrowDownSolid: "\u{f218}", FAIcon.FACartPlusSolid: "\u{f217}", FAIcon.FACashRegisterSolid: "\u{f788}", FAIcon.FACatSolid: "\u{f6be}", FAIcon.FACertificateSolid: "\u{f0a3}", FAIcon.FAChairSolid: "\u{f6c0}", FAIcon.FAChalkboardSolid: "\u{f51b}", FAIcon.FAChalkboardTeacherSolid: "\u{f51c}", FAIcon.FAChargingStationSolid: "\u{f5e7}", FAIcon.FAChartAreaSolid: "\u{f1fe}", FAIcon.FAChartBarRegular: "\u{f080}", FAIcon.FAChartBarSolid: "\u{f080}", FAIcon.FAChartLineSolid: "\u{f201}", FAIcon.FAChartPieSolid: "\u{f200}", FAIcon.FACheckCircleRegular: "\u{f058}", FAIcon.FACheckCircleSolid: "\u{f058}", FAIcon.FACheckDoubleSolid: "\u{f560}", FAIcon.FACheckSolid: "\u{f00c}", FAIcon.FACheckSquareRegular: "\u{f14a}", FAIcon.FACheckSquareSolid: "\u{f14a}", FAIcon.FACheeseSolid: "\u{f7ef}", FAIcon.FAChessBishopSolid: "\u{f43a}", FAIcon.FAChessBoardSolid: "\u{f43c}", FAIcon.FAChessKingSolid: "\u{f43f}", FAIcon.FAChessKnightSolid: "\u{f441}", FAIcon.FAChessPawnSolid: "\u{f443}", FAIcon.FAChessQueenSolid: "\u{f445}", FAIcon.FAChessRookSolid: "\u{f447}", FAIcon.FAChessSolid: "\u{f439}", FAIcon.FAChevronCircleDownSolid: "\u{f13a}", FAIcon.FAChevronCircleLeftSolid: "\u{f137}", FAIcon.FAChevronCircleRightSolid: "\u{f138}", FAIcon.FAChevronCircleUpSolid: "\u{f139}", FAIcon.FAChevronDownSolid: "\u{f078}", FAIcon.FAChevronLeftSolid: "\u{f053}", FAIcon.FAChevronRightSolid: "\u{f054}", FAIcon.FAChevronUpSolid: "\u{f077}", FAIcon.FAChildSolid: "\u{f1ae}", FAIcon.FAChurchSolid: "\u{f51d}", FAIcon.FACircleNotchSolid: "\u{f1ce}", FAIcon.FACircleRegular: "\u{f111}", FAIcon.FACircleSolid: "\u{f111}", FAIcon.FACitySolid: "\u{f64f}", FAIcon.FAClinicMedicalSolid: "\u{f7f2}", FAIcon.FAClipboardCheckSolid: "\u{f46c}", FAIcon.FAClipboardListSolid: "\u{f46d}", FAIcon.FAClipboardRegular: "\u{f328}", FAIcon.FAClipboardSolid: "\u{f328}", FAIcon.FAClockRegular: "\u{f017}", FAIcon.FAClockSolid: "\u{f017}", FAIcon.FACloneRegular: "\u{f24d}", FAIcon.FACloneSolid: "\u{f24d}", FAIcon.FAClosedCaptioningRegular: "\u{f20a}", FAIcon.FAClosedCaptioningSolid: "\u{f20a}", FAIcon.FACloudDownloadAltSolid: "\u{f381}", FAIcon.FACloudMeatballSolid: "\u{f73b}", FAIcon.FACloudMoonRainSolid: "\u{f73c}", FAIcon.FACloudMoonSolid: "\u{f6c3}", FAIcon.FACloudRainSolid: "\u{f73d}", FAIcon.FACloudShowersHeavySolid: "\u{f740}", FAIcon.FACloudSolid: "\u{f0c2}", FAIcon.FACloudSunRainSolid: "\u{f743}", FAIcon.FACloudSunSolid: "\u{f6c4}", FAIcon.FACloudUploadAltSolid: "\u{f382}", FAIcon.FACocktailSolid: "\u{f561}", FAIcon.FACodeBranchSolid: "\u{f126}", FAIcon.FACodeSolid: "\u{f121}", FAIcon.FACoffeeSolid: "\u{f0f4}", FAIcon.FACogSolid: "\u{f013}", FAIcon.FACogsSolid: "\u{f085}", FAIcon.FACoinsSolid: "\u{f51e}", FAIcon.FAColumnsSolid: "\u{f0db}", FAIcon.FACommentAltRegular: "\u{f27a}", FAIcon.FACommentAltSolid: "\u{f27a}", FAIcon.FACommentDollarSolid: "\u{f651}", FAIcon.FACommentDotsRegular: "\u{f4ad}", FAIcon.FACommentDotsSolid: "\u{f4ad}", FAIcon.FACommentMedicalSolid: "\u{f7f5}", FAIcon.FACommentRegular: "\u{f075}", FAIcon.FACommentSlashSolid: "\u{f4b3}", FAIcon.FACommentSolid: "\u{f075}", FAIcon.FACommentsDollarSolid: "\u{f653}", FAIcon.FACommentsRegular: "\u{f086}", FAIcon.FACommentsSolid: "\u{f086}", FAIcon.FACompactDiscSolid: "\u{f51f}", FAIcon.FACompassRegular: "\u{f14e}", FAIcon.FACompassSolid: "\u{f14e}", FAIcon.FACompressArrowsAltSolid: "\u{f78c}", FAIcon.FACompressSolid: "\u{f066}", FAIcon.FAConciergeBellSolid: "\u{f562}", FAIcon.FACookieBiteSolid: "\u{f564}", FAIcon.FACookieSolid: "\u{f563}", FAIcon.FACopyRegular: "\u{f0c5}", FAIcon.FACopySolid: "\u{f0c5}", FAIcon.FACopyrightRegular: "\u{f1f9}", FAIcon.FACopyrightSolid: "\u{f1f9}", FAIcon.FACouchSolid: "\u{f4b8}", FAIcon.FACreditCardRegular: "\u{f09d}", FAIcon.FACreditCardSolid: "\u{f09d}", FAIcon.FACropAltSolid: "\u{f565}", FAIcon.FACropSolid: "\u{f125}", FAIcon.FACrossSolid: "\u{f654}", FAIcon.FACrosshairsSolid: "\u{f05b}", FAIcon.FACrowSolid: "\u{f520}", FAIcon.FACrownSolid: "\u{f521}", FAIcon.FACrutchSolid: "\u{f7f7}", FAIcon.FACubeSolid: "\u{f1b2}", FAIcon.FACubesSolid: "\u{f1b3}", FAIcon.FACutSolid: "\u{f0c4}", FAIcon.FADatabaseSolid: "\u{f1c0}", FAIcon.FADeafSolid: "\u{f2a4}", FAIcon.FADemocratSolid: "\u{f747}", FAIcon.FADesktopSolid: "\u{f108}", FAIcon.FADharmachakraSolid: "\u{f655}", FAIcon.FADiagnosesSolid: "\u{f470}", FAIcon.FADiceD20Solid: "\u{f6cf}", FAIcon.FADiceD6Solid: "\u{f6d1}", FAIcon.FADiceFiveSolid: "\u{f523}", FAIcon.FADiceFourSolid: "\u{f524}", FAIcon.FADiceOneSolid: "\u{f525}", FAIcon.FADiceSixSolid: "\u{f526}", FAIcon.FADiceSolid: "\u{f522}", FAIcon.FADiceThreeSolid: "\u{f527}", FAIcon.FADiceTwoSolid: "\u{f528}", FAIcon.FADigitalTachographSolid: "\u{f566}", FAIcon.FADirectionsSolid: "\u{f5eb}", FAIcon.FADivideSolid: "\u{f529}", FAIcon.FADizzyRegular: "\u{f567}", FAIcon.FADizzySolid: "\u{f567}", FAIcon.FADnaSolid: "\u{f471}", FAIcon.FADogSolid: "\u{f6d3}", FAIcon.FADollarSignSolid: "\u{f155}", FAIcon.FADollyFlatbedSolid: "\u{f474}", FAIcon.FADollySolid: "\u{f472}", FAIcon.FADonateSolid: "\u{f4b9}", FAIcon.FADoorClosedSolid: "\u{f52a}", FAIcon.FADoorOpenSolid: "\u{f52b}", FAIcon.FADotCircleRegular: "\u{f192}", FAIcon.FADotCircleSolid: "\u{f192}", FAIcon.FADoveSolid: "\u{f4ba}", FAIcon.FADownloadSolid: "\u{f019}", FAIcon.FADraftingCompassSolid: "\u{f568}", FAIcon.FADragonSolid: "\u{f6d5}", FAIcon.FADrawPolygonSolid: "\u{f5ee}", FAIcon.FADrumSolid: "\u{f569}", FAIcon.FADrumSteelpanSolid: "\u{f56a}", FAIcon.FADrumstickBiteSolid: "\u{f6d7}", FAIcon.FADumbbellSolid: "\u{f44b}", FAIcon.FADumpsterFireSolid: "\u{f794}", FAIcon.FADumpsterSolid: "\u{f793}", FAIcon.FADungeonSolid: "\u{f6d9}", FAIcon.FAEditRegular: "\u{f044}", FAIcon.FAEditSolid: "\u{f044}", FAIcon.FAEggSolid: "\u{f7fb}", FAIcon.FAEjectSolid: "\u{f052}", FAIcon.FAEllipsisHSolid: "\u{f141}", FAIcon.FAEllipsisVSolid: "\u{f142}", FAIcon.FAEnvelopeOpenRegular: "\u{f2b6}", FAIcon.FAEnvelopeOpenSolid: "\u{f2b6}", FAIcon.FAEnvelopeOpenTextSolid: "\u{f658}", FAIcon.FAEnvelopeRegular: "\u{f0e0}", FAIcon.FAEnvelopeSolid: "\u{f0e0}", FAIcon.FAEnvelopeSquareSolid: "\u{f199}", FAIcon.FAEqualsSolid: "\u{f52c}", FAIcon.FAEraserSolid: "\u{f12d}", FAIcon.FAEthernetSolid: "\u{f796}", FAIcon.FAEuroSignSolid: "\u{f153}", FAIcon.FAExchangeAltSolid: "\u{f362}", FAIcon.FAExclamationCircleSolid: "\u{f06a}", FAIcon.FAExclamationSolid: "\u{f12a}", FAIcon.FAExclamationTriangleSolid: "\u{f071}", FAIcon.FAExpandArrowsAltSolid: "\u{f31e}", FAIcon.FAExpandSolid: "\u{f065}", FAIcon.FAExternalLinkAltSolid: "\u{f35d}", FAIcon.FAExternalLinkSquareAltSolid: "\u{f360}", FAIcon.FAEyeDropperSolid: "\u{f1fb}", FAIcon.FAEyeRegular: "\u{f06e}", FAIcon.FAEyeSlashRegular: "\u{f070}", FAIcon.FAEyeSlashSolid: "\u{f070}", FAIcon.FAEyeSolid: "\u{f06e}", FAIcon.FAFanSolid: "\u{f863}", FAIcon.FAFastBackwardSolid: "\u{f049}", FAIcon.FAFastForwardSolid: "\u{f050}", FAIcon.FAFaxSolid: "\u{f1ac}", FAIcon.FAFeatherAltSolid: "\u{f56b}", FAIcon.FAFeatherSolid: "\u{f52d}", FAIcon.FAFemaleSolid: "\u{f182}", FAIcon.FAFighterJetSolid: "\u{f0fb}", FAIcon.FAFileAltRegular: "\u{f15c}", FAIcon.FAFileAltSolid: "\u{f15c}", FAIcon.FAFileArchiveRegular: "\u{f1c6}", FAIcon.FAFileArchiveSolid: "\u{f1c6}", FAIcon.FAFileAudioRegular: "\u{f1c7}", FAIcon.FAFileAudioSolid: "\u{f1c7}", FAIcon.FAFileCodeRegular: "\u{f1c9}", FAIcon.FAFileCodeSolid: "\u{f1c9}", FAIcon.FAFileContractSolid: "\u{f56c}", FAIcon.FAFileCsvSolid: "\u{f6dd}", FAIcon.FAFileDownloadSolid: "\u{f56d}", FAIcon.FAFileExcelRegular: "\u{f1c3}", FAIcon.FAFileExcelSolid: "\u{f1c3}", FAIcon.FAFileExportSolid: "\u{f56e}", FAIcon.FAFileImageRegular: "\u{f1c5}", FAIcon.FAFileImageSolid: "\u{f1c5}", FAIcon.FAFileImportSolid: "\u{f56f}", FAIcon.FAFileInvoiceDollarSolid: "\u{f571}", FAIcon.FAFileInvoiceSolid: "\u{f570}", FAIcon.FAFileMedicalAltSolid: "\u{f478}", FAIcon.FAFileMedicalSolid: "\u{f477}", FAIcon.FAFilePdfRegular: "\u{f1c1}", FAIcon.FAFilePdfSolid: "\u{f1c1}", FAIcon.FAFilePowerpointRegular: "\u{f1c4}", FAIcon.FAFilePowerpointSolid: "\u{f1c4}", FAIcon.FAFilePrescriptionSolid: "\u{f572}", FAIcon.FAFileRegular: "\u{f15b}", FAIcon.FAFileSignatureSolid: "\u{f573}", FAIcon.FAFileSolid: "\u{f15b}", FAIcon.FAFileUploadSolid: "\u{f574}", FAIcon.FAFileVideoRegular: "\u{f1c8}", FAIcon.FAFileVideoSolid: "\u{f1c8}", FAIcon.FAFileWordRegular: "\u{f1c2}", FAIcon.FAFileWordSolid: "\u{f1c2}", FAIcon.FAFillDripSolid: "\u{f576}", FAIcon.FAFillSolid: "\u{f575}", FAIcon.FAFilmSolid: "\u{f008}", FAIcon.FAFilterSolid: "\u{f0b0}", FAIcon.FAFingerprintSolid: "\u{f577}", FAIcon.FAFireAltSolid: "\u{f7e4}", FAIcon.FAFireExtinguisherSolid: "\u{f134}", FAIcon.FAFireSolid: "\u{f06d}", FAIcon.FAFirstAidSolid: "\u{f479}", FAIcon.FAFishSolid: "\u{f578}", FAIcon.FAFistRaisedSolid: "\u{f6de}", FAIcon.FAFlagCheckeredSolid: "\u{f11e}", FAIcon.FAFlagRegular: "\u{f024}", FAIcon.FAFlagSolid: "\u{f024}", FAIcon.FAFlagUsaSolid: "\u{f74d}", FAIcon.FAFlaskSolid: "\u{f0c3}", FAIcon.FAFlushedRegular: "\u{f579}", FAIcon.FAFlushedSolid: "\u{f579}", FAIcon.FAFolderMinusSolid: "\u{f65d}", FAIcon.FAFolderOpenRegular: "\u{f07c}", FAIcon.FAFolderOpenSolid: "\u{f07c}", FAIcon.FAFolderPlusSolid: "\u{f65e}", FAIcon.FAFolderRegular: "\u{f07b}", FAIcon.FAFolderSolid: "\u{f07b}", FAIcon.FAFontAwesomeLogoFullRegular: "\u{f4e6}", FAIcon.FAFontAwesomeLogoFullSolid: "\u{f4e6}", FAIcon.FAFontSolid: "\u{f031}", FAIcon.FAFootballBallSolid: "\u{f44e}", FAIcon.FAForwardSolid: "\u{f04e}", FAIcon.FAFrogSolid: "\u{f52e}", FAIcon.FAFrownOpenRegular: "\u{f57a}", FAIcon.FAFrownOpenSolid: "\u{f57a}", FAIcon.FAFrownRegular: "\u{f119}", FAIcon.FAFrownSolid: "\u{f119}", FAIcon.FAFunnelDollarSolid: "\u{f662}", FAIcon.FAFutbolRegular: "\u{f1e3}", FAIcon.FAFutbolSolid: "\u{f1e3}", FAIcon.FAGamepadSolid: "\u{f11b}", FAIcon.FAGasPumpSolid: "\u{f52f}", FAIcon.FAGavelSolid: "\u{f0e3}", FAIcon.FAGemRegular: "\u{f3a5}", FAIcon.FAGemSolid: "\u{f3a5}", FAIcon.FAGenderlessSolid: "\u{f22d}", FAIcon.FAGhostSolid: "\u{f6e2}", FAIcon.FAGiftSolid: "\u{f06b}", FAIcon.FAGiftsSolid: "\u{f79c}", FAIcon.FAGlassCheersSolid: "\u{f79f}", FAIcon.FAGlassMartiniAltSolid: "\u{f57b}", FAIcon.FAGlassMartiniSolid: "\u{f000}", FAIcon.FAGlassWhiskeySolid: "\u{f7a0}", FAIcon.FAGlassesSolid: "\u{f530}", FAIcon.FAGlobeAfricaSolid: "\u{f57c}", FAIcon.FAGlobeAmericasSolid: "\u{f57d}", FAIcon.FAGlobeAsiaSolid: "\u{f57e}", FAIcon.FAGlobeEuropeSolid: "\u{f7a2}", FAIcon.FAGlobeSolid: "\u{f0ac}", FAIcon.FAGolfBallSolid: "\u{f450}", FAIcon.FAGopuramSolid: "\u{f664}", FAIcon.FAGraduationCapSolid: "\u{f19d}", FAIcon.FAGreaterThanEqualSolid: "\u{f532}", FAIcon.FAGreaterThanSolid: "\u{f531}", FAIcon.FAGrimaceRegular: "\u{f57f}", FAIcon.FAGrimaceSolid: "\u{f57f}", FAIcon.FAGrinAltRegular: "\u{f581}", FAIcon.FAGrinAltSolid: "\u{f581}", FAIcon.FAGrinBeamRegular: "\u{f582}", FAIcon.FAGrinBeamSolid: "\u{f582}", FAIcon.FAGrinBeamSweatRegular: "\u{f583}", FAIcon.FAGrinBeamSweatSolid: "\u{f583}", FAIcon.FAGrinHeartsRegular: "\u{f584}", FAIcon.FAGrinHeartsSolid: "\u{f584}", FAIcon.FAGrinRegular: "\u{f580}", FAIcon.FAGrinSolid: "\u{f580}", FAIcon.FAGrinSquintRegular: "\u{f585}", FAIcon.FAGrinSquintSolid: "\u{f585}", FAIcon.FAGrinSquintTearsRegular: "\u{f586}", FAIcon.FAGrinSquintTearsSolid: "\u{f586}", FAIcon.FAGrinStarsRegular: "\u{f587}", FAIcon.FAGrinStarsSolid: "\u{f587}", FAIcon.FAGrinTearsRegular: "\u{f588}", FAIcon.FAGrinTearsSolid: "\u{f588}", FAIcon.FAGrinTongueRegular: "\u{f589}", FAIcon.FAGrinTongueSolid: "\u{f589}", FAIcon.FAGrinTongueSquintRegular: "\u{f58a}", FAIcon.FAGrinTongueSquintSolid: "\u{f58a}", FAIcon.FAGrinTongueWinkRegular: "\u{f58b}", FAIcon.FAGrinTongueWinkSolid: "\u{f58b}", FAIcon.FAGrinWinkRegular: "\u{f58c}", FAIcon.FAGrinWinkSolid: "\u{f58c}", FAIcon.FAGripHorizontalSolid: "\u{f58d}", FAIcon.FAGripLinesSolid: "\u{f7a4}", FAIcon.FAGripLinesVerticalSolid: "\u{f7a5}", FAIcon.FAGripVerticalSolid: "\u{f58e}", FAIcon.FAGuitarSolid: "\u{f7a6}", FAIcon.FAHSquareSolid: "\u{f0fd}", FAIcon.FAHamburgerSolid: "\u{f805}", FAIcon.FAHammerSolid: "\u{f6e3}", FAIcon.FAHamsaSolid: "\u{f665}", FAIcon.FAHandHoldingHeartSolid: "\u{f4be}", FAIcon.FAHandHoldingSolid: "\u{f4bd}", FAIcon.FAHandHoldingUsdSolid: "\u{f4c0}", FAIcon.FAHandLizardRegular: "\u{f258}", FAIcon.FAHandLizardSolid: "\u{f258}", FAIcon.FAHandMiddleFingerSolid: "\u{f806}", FAIcon.FAHandPaperRegular: "\u{f256}", FAIcon.FAHandPaperSolid: "\u{f256}", FAIcon.FAHandPeaceRegular: "\u{f25b}", FAIcon.FAHandPeaceSolid: "\u{f25b}", FAIcon.FAHandPointDownRegular: "\u{f0a7}", FAIcon.FAHandPointDownSolid: "\u{f0a7}", FAIcon.FAHandPointLeftRegular: "\u{f0a5}", FAIcon.FAHandPointLeftSolid: "\u{f0a5}", FAIcon.FAHandPointRightRegular: "\u{f0a4}", FAIcon.FAHandPointRightSolid: "\u{f0a4}", FAIcon.FAHandPointUpRegular: "\u{f0a6}", FAIcon.FAHandPointUpSolid: "\u{f0a6}", FAIcon.FAHandPointerRegular: "\u{f25a}", FAIcon.FAHandPointerSolid: "\u{f25a}", FAIcon.FAHandRockRegular: "\u{f255}", FAIcon.FAHandRockSolid: "\u{f255}", FAIcon.FAHandScissorsRegular: "\u{f257}", FAIcon.FAHandScissorsSolid: "\u{f257}", FAIcon.FAHandSpockRegular: "\u{f259}", FAIcon.FAHandSpockSolid: "\u{f259}", FAIcon.FAHandsHelpingSolid: "\u{f4c4}", FAIcon.FAHandsSolid: "\u{f4c2}", FAIcon.FAHandshakeRegular: "\u{f2b5}", FAIcon.FAHandshakeSolid: "\u{f2b5}", FAIcon.FAHanukiahSolid: "\u{f6e6}", FAIcon.FAHardHatSolid: "\u{f807}", FAIcon.FAHashtagSolid: "\u{f292}", FAIcon.FAHatCowboySideSolid: "\u{f8c1}", FAIcon.FAHatCowboySolid: "\u{f8c0}", FAIcon.FAHatWizardSolid: "\u{f6e8}", FAIcon.FAHaykalSolid: "\u{f666}", FAIcon.FAHddRegular: "\u{f0a0}", FAIcon.FAHddSolid: "\u{f0a0}", FAIcon.FAHeadingSolid: "\u{f1dc}", FAIcon.FAHeadphonesAltSolid: "\u{f58f}", FAIcon.FAHeadphonesSolid: "\u{f025}", FAIcon.FAHeadsetSolid: "\u{f590}", FAIcon.FAHeartBrokenSolid: "\u{f7a9}", FAIcon.FAHeartRegular: "\u{f004}", FAIcon.FAHeartSolid: "\u{f004}", FAIcon.FAHeartbeatSolid: "\u{f21e}", FAIcon.FAHelicopterSolid: "\u{f533}", FAIcon.FAHighlighterSolid: "\u{f591}", FAIcon.FAHikingSolid: "\u{f6ec}", FAIcon.FAHippoSolid: "\u{f6ed}", FAIcon.FAHistorySolid: "\u{f1da}", FAIcon.FAHockeyPuckSolid: "\u{f453}", FAIcon.FAHollyBerrySolid: "\u{f7aa}", FAIcon.FAHomeSolid: "\u{f015}", FAIcon.FAHorseHeadSolid: "\u{f7ab}", FAIcon.FAHorseSolid: "\u{f6f0}", FAIcon.FAHospitalAltSolid: "\u{f47d}", FAIcon.FAHospitalRegular: "\u{f0f8}", FAIcon.FAHospitalSolid: "\u{f0f8}", FAIcon.FAHospitalSymbolSolid: "\u{f47e}", FAIcon.FAHotTubSolid: "\u{f593}", FAIcon.FAHotdogSolid: "\u{f80f}", FAIcon.FAHotelSolid: "\u{f594}", FAIcon.FAHourglassEndSolid: "\u{f253}", FAIcon.FAHourglassHalfSolid: "\u{f252}", FAIcon.FAHourglassRegular: "\u{f254}", FAIcon.FAHourglassSolid: "\u{f254}", FAIcon.FAHourglassStartSolid: "\u{f251}", FAIcon.FAHouseDamageSolid: "\u{f6f1}", FAIcon.FAHryvniaSolid: "\u{f6f2}", FAIcon.FAICursorSolid: "\u{f246}", FAIcon.FAIceCreamSolid: "\u{f810}", FAIcon.FAIciclesSolid: "\u{f7ad}", FAIcon.FAIconsSolid: "\u{f86d}", FAIcon.FAIdBadgeRegular: "\u{f2c1}", FAIcon.FAIdBadgeSolid: "\u{f2c1}", FAIcon.FAIdCardAltSolid: "\u{f47f}", FAIcon.FAIdCardRegular: "\u{f2c2}", FAIcon.FAIdCardSolid: "\u{f2c2}", FAIcon.FAIglooSolid: "\u{f7ae}", FAIcon.FAImageRegular: "\u{f03e}", FAIcon.FAImageSolid: "\u{f03e}", FAIcon.FAImagesRegular: "\u{f302}", FAIcon.FAImagesSolid: "\u{f302}", FAIcon.FAInboxSolid: "\u{f01c}", FAIcon.FAIndentSolid: "\u{f03c}", FAIcon.FAIndustrySolid: "\u{f275}", FAIcon.FAInfinitySolid: "\u{f534}", FAIcon.FAInfoCircleSolid: "\u{f05a}", FAIcon.FAInfoSolid: "\u{f129}", FAIcon.FAItalicSolid: "\u{f033}", FAIcon.FAJediSolid: "\u{f669}", FAIcon.FAJointSolid: "\u{f595}", FAIcon.FAJournalWhillsSolid: "\u{f66a}", FAIcon.FAKaabaSolid: "\u{f66b}", FAIcon.FAKeySolid: "\u{f084}", FAIcon.FAKeyboardRegular: "\u{f11c}", FAIcon.FAKeyboardSolid: "\u{f11c}", FAIcon.FAKhandaSolid: "\u{f66d}", FAIcon.FAKissBeamRegular: "\u{f597}", FAIcon.FAKissBeamSolid: "\u{f597}", FAIcon.FAKissRegular: "\u{f596}", FAIcon.FAKissSolid: "\u{f596}", FAIcon.FAKissWinkHeartRegular: "\u{f598}", FAIcon.FAKissWinkHeartSolid: "\u{f598}", FAIcon.FAKiwiBirdSolid: "\u{f535}", FAIcon.FALandmarkSolid: "\u{f66f}", FAIcon.FALanguageSolid: "\u{f1ab}", FAIcon.FALaptopCodeSolid: "\u{f5fc}", FAIcon.FALaptopMedicalSolid: "\u{f812}", FAIcon.FALaptopSolid: "\u{f109}", FAIcon.FALaughBeamRegular: "\u{f59a}", FAIcon.FALaughBeamSolid: "\u{f59a}", FAIcon.FALaughRegular: "\u{f599}", FAIcon.FALaughSolid: "\u{f599}", FAIcon.FALaughSquintRegular: "\u{f59b}", FAIcon.FALaughSquintSolid: "\u{f59b}", FAIcon.FALaughWinkRegular: "\u{f59c}", FAIcon.FALaughWinkSolid: "\u{f59c}", FAIcon.FALayerGroupSolid: "\u{f5fd}", FAIcon.FALeafSolid: "\u{f06c}", FAIcon.FALemonRegular: "\u{f094}", FAIcon.FALemonSolid: "\u{f094}", FAIcon.FALessThanEqualSolid: "\u{f537}", FAIcon.FALessThanSolid: "\u{f536}", FAIcon.FALevelDownAltSolid: "\u{f3be}", FAIcon.FALevelUpAltSolid: "\u{f3bf}", FAIcon.FALifeRingRegular: "\u{f1cd}", FAIcon.FALifeRingSolid: "\u{f1cd}", FAIcon.FALightbulbRegular: "\u{f0eb}", FAIcon.FALightbulbSolid: "\u{f0eb}", FAIcon.FALinkSolid: "\u{f0c1}", FAIcon.FALiraSignSolid: "\u{f195}", FAIcon.FAListAltRegular: "\u{f022}", FAIcon.FAListAltSolid: "\u{f022}", FAIcon.FAListOlSolid: "\u{f0cb}", FAIcon.FAListSolid: "\u{f03a}", FAIcon.FAListUlSolid: "\u{f0ca}", FAIcon.FALocationArrowSolid: "\u{f124}", FAIcon.FALockOpenSolid: "\u{f3c1}", FAIcon.FALockSolid: "\u{f023}", FAIcon.FALongArrowAltDownSolid: "\u{f309}", FAIcon.FALongArrowAltLeftSolid: "\u{f30a}", FAIcon.FALongArrowAltRightSolid: "\u{f30b}", FAIcon.FALongArrowAltUpSolid: "\u{f30c}", FAIcon.FALowVisionSolid: "\u{f2a8}", FAIcon.FALuggageCartSolid: "\u{f59d}", FAIcon.FAMagicSolid: "\u{f0d0}", FAIcon.FAMagnetSolid: "\u{f076}", FAIcon.FAMailBulkSolid: "\u{f674}", FAIcon.FAMaleSolid: "\u{f183}", FAIcon.FAMapMarkedAltSolid: "\u{f5a0}", FAIcon.FAMapMarkedSolid: "\u{f59f}", FAIcon.FAMapMarkerAltSolid: "\u{f3c5}", FAIcon.FAMapMarkerSolid: "\u{f041}", FAIcon.FAMapPinSolid: "\u{f276}", FAIcon.FAMapRegular: "\u{f279}", FAIcon.FAMapSignsSolid: "\u{f277}", FAIcon.FAMapSolid: "\u{f279}", FAIcon.FAMarkerSolid: "\u{f5a1}", FAIcon.FAMarsDoubleSolid: "\u{f227}", FAIcon.FAMarsSolid: "\u{f222}", FAIcon.FAMarsStrokeHSolid: "\u{f22b}", FAIcon.FAMarsStrokeSolid: "\u{f229}", FAIcon.FAMarsStrokeVSolid: "\u{f22a}", FAIcon.FAMaskSolid: "\u{f6fa}", FAIcon.FAMedalSolid: "\u{f5a2}", FAIcon.FAMedkitSolid: "\u{f0fa}", FAIcon.FAMehBlankRegular: "\u{f5a4}", FAIcon.FAMehBlankSolid: "\u{f5a4}", FAIcon.FAMehRegular: "\u{f11a}", FAIcon.FAMehRollingEyesRegular: "\u{f5a5}", FAIcon.FAMehRollingEyesSolid: "\u{f5a5}", FAIcon.FAMehSolid: "\u{f11a}", FAIcon.FAMemorySolid: "\u{f538}", FAIcon.FAMenorahSolid: "\u{f676}", FAIcon.FAMercurySolid: "\u{f223}", FAIcon.FAMeteorSolid: "\u{f753}", FAIcon.FAMicrochipSolid: "\u{f2db}", FAIcon.FAMicrophoneAltSlashSolid: "\u{f539}", FAIcon.FAMicrophoneAltSolid: "\u{f3c9}", FAIcon.FAMicrophoneSlashSolid: "\u{f131}", FAIcon.FAMicrophoneSolid: "\u{f130}", FAIcon.FAMicroscopeSolid: "\u{f610}", FAIcon.FAMinusCircleSolid: "\u{f056}", FAIcon.FAMinusSolid: "\u{f068}", FAIcon.FAMinusSquareRegular: "\u{f146}", FAIcon.FAMinusSquareSolid: "\u{f146}", FAIcon.FAMittenSolid: "\u{f7b5}", FAIcon.FAMobileAltSolid: "\u{f3cd}", FAIcon.FAMobileSolid: "\u{f10b}", FAIcon.FAMoneyBillAltRegular: "\u{f3d1}", FAIcon.FAMoneyBillAltSolid: "\u{f3d1}", FAIcon.FAMoneyBillSolid: "\u{f0d6}", FAIcon.FAMoneyBillWaveAltSolid: "\u{f53b}", FAIcon.FAMoneyBillWaveSolid: "\u{f53a}", FAIcon.FAMoneyCheckAltSolid: "\u{f53d}", FAIcon.FAMoneyCheckSolid: "\u{f53c}", FAIcon.FAMonumentSolid: "\u{f5a6}", FAIcon.FAMoonRegular: "\u{f186}", FAIcon.FAMoonSolid: "\u{f186}", FAIcon.FAMortarPestleSolid: "\u{f5a7}", FAIcon.FAMosqueSolid: "\u{f678}", FAIcon.FAMotorcycleSolid: "\u{f21c}", FAIcon.FAMountainSolid: "\u{f6fc}", FAIcon.FAMousePointerSolid: "\u{f245}", FAIcon.FAMouseSolid: "\u{f8cc}", FAIcon.FAMugHotSolid: "\u{f7b6}", FAIcon.FAMusicSolid: "\u{f001}", FAIcon.FANetworkWiredSolid: "\u{f6ff}", FAIcon.FANeuterSolid: "\u{f22c}", FAIcon.FANewspaperRegular: "\u{f1ea}", FAIcon.FANewspaperSolid: "\u{f1ea}", FAIcon.FANotEqualSolid: "\u{f53e}", FAIcon.FANotesMedicalSolid: "\u{f481}", FAIcon.FAObjectGroupRegular: "\u{f247}", FAIcon.FAObjectGroupSolid: "\u{f247}", FAIcon.FAObjectUngroupRegular: "\u{f248}", FAIcon.FAObjectUngroupSolid: "\u{f248}", FAIcon.FAOilCanSolid: "\u{f613}", FAIcon.FAOmSolid: "\u{f679}", FAIcon.FAOtterSolid: "\u{f700}", FAIcon.FAOutdentSolid: "\u{f03b}", FAIcon.FAPagerSolid: "\u{f815}", FAIcon.FAPaintBrushSolid: "\u{f1fc}", FAIcon.FAPaintRollerSolid: "\u{f5aa}", FAIcon.FAPaletteSolid: "\u{f53f}", FAIcon.FAPalletSolid: "\u{f482}", FAIcon.FAPaperPlaneRegular: "\u{f1d8}", FAIcon.FAPaperPlaneSolid: "\u{f1d8}", FAIcon.FAPaperclipSolid: "\u{f0c6}", FAIcon.FAParachuteBoxSolid: "\u{f4cd}", FAIcon.FAParagraphSolid: "\u{f1dd}", FAIcon.FAParkingSolid: "\u{f540}", FAIcon.FAPassportSolid: "\u{f5ab}", FAIcon.FAPastafarianismSolid: "\u{f67b}", FAIcon.FAPasteSolid: "\u{f0ea}", FAIcon.FAPauseCircleRegular: "\u{f28b}", FAIcon.FAPauseCircleSolid: "\u{f28b}", FAIcon.FAPauseSolid: "\u{f04c}", FAIcon.FAPawSolid: "\u{f1b0}", FAIcon.FAPeaceSolid: "\u{f67c}", FAIcon.FAPenAltSolid: "\u{f305}", FAIcon.FAPenFancySolid: "\u{f5ac}", FAIcon.FAPenNibSolid: "\u{f5ad}", FAIcon.FAPenSolid: "\u{f304}", FAIcon.FAPenSquareSolid: "\u{f14b}", FAIcon.FAPencilAltSolid: "\u{f303}", FAIcon.FAPencilRulerSolid: "\u{f5ae}", FAIcon.FAPeopleCarrySolid: "\u{f4ce}", FAIcon.FAPepperHotSolid: "\u{f816}", FAIcon.FAPercentSolid: "\u{f295}", FAIcon.FAPercentageSolid: "\u{f541}", FAIcon.FAPersonBoothSolid: "\u{f756}", FAIcon.FAPhoneAltSolid: "\u{f879}", FAIcon.FAPhoneSlashSolid: "\u{f3dd}", FAIcon.FAPhoneSolid: "\u{f095}", FAIcon.FAPhoneSquareAltSolid: "\u{f87b}", FAIcon.FAPhoneSquareSolid: "\u{f098}", FAIcon.FAPhoneVolumeSolid: "\u{f2a0}", FAIcon.FAPhotoVideoSolid: "\u{f87c}", FAIcon.FAPiggyBankSolid: "\u{f4d3}", FAIcon.FAPillsSolid: "\u{f484}", FAIcon.FAPizzaSliceSolid: "\u{f818}", FAIcon.FAPlaceOfWorshipSolid: "\u{f67f}", FAIcon.FAPlaneArrivalSolid: "\u{f5af}", FAIcon.FAPlaneDepartureSolid: "\u{f5b0}", FAIcon.FAPlaneSolid: "\u{f072}", FAIcon.FAPlayCircleRegular: "\u{f144}", FAIcon.FAPlayCircleSolid: "\u{f144}", FAIcon.FAPlaySolid: "\u{f04b}", FAIcon.FAPlugSolid: "\u{f1e6}", FAIcon.FAPlusCircleSolid: "\u{f055}", FAIcon.FAPlusSolid: "\u{f067}", FAIcon.FAPlusSquareRegular: "\u{f0fe}", FAIcon.FAPlusSquareSolid: "\u{f0fe}", FAIcon.FAPodcastSolid: "\u{f2ce}", FAIcon.FAPollHSolid: "\u{f682}", FAIcon.FAPollSolid: "\u{f681}", FAIcon.FAPooSolid: "\u{f2fe}", FAIcon.FAPooStormSolid: "\u{f75a}", FAIcon.FAPoopSolid: "\u{f619}", FAIcon.FAPortraitSolid: "\u{f3e0}", FAIcon.FAPoundSignSolid: "\u{f154}", FAIcon.FAPowerOffSolid: "\u{f011}", FAIcon.FAPraySolid: "\u{f683}", FAIcon.FAPrayingHandsSolid: "\u{f684}", FAIcon.FAPrescriptionBottleAltSolid: "\u{f486}", FAIcon.FAPrescriptionBottleSolid: "\u{f485}", FAIcon.FAPrescriptionSolid: "\u{f5b1}", FAIcon.FAPrintSolid: "\u{f02f}", FAIcon.FAProceduresSolid: "\u{f487}", FAIcon.FAProjectDiagramSolid: "\u{f542}", FAIcon.FAPuzzlePieceSolid: "\u{f12e}", FAIcon.FAQrcodeSolid: "\u{f029}", FAIcon.FAQuestionCircleRegular: "\u{f059}", FAIcon.FAQuestionCircleSolid: "\u{f059}", FAIcon.FAQuestionSolid: "\u{f128}", FAIcon.FAQuidditchSolid: "\u{f458}", FAIcon.FAQuoteLeftSolid: "\u{f10d}", FAIcon.FAQuoteRightSolid: "\u{f10e}", FAIcon.FAQuranSolid: "\u{f687}", FAIcon.FARadiationAltSolid: "\u{f7ba}", FAIcon.FARadiationSolid: "\u{f7b9}", FAIcon.FARainbowSolid: "\u{f75b}", FAIcon.FARandomSolid: "\u{f074}", FAIcon.FAReceiptSolid: "\u{f543}", FAIcon.FARecordVinylSolid: "\u{f8d9}", FAIcon.FARecycleSolid: "\u{f1b8}", FAIcon.FARedoAltSolid: "\u{f2f9}", FAIcon.FARedoSolid: "\u{f01e}", FAIcon.FARegisteredRegular: "\u{f25d}", FAIcon.FARegisteredSolid: "\u{f25d}", FAIcon.FARemoveFormatSolid: "\u{f87d}", FAIcon.FAReplyAllSolid: "\u{f122}", FAIcon.FAReplySolid: "\u{f3e5}", FAIcon.FARepublicanSolid: "\u{f75e}", FAIcon.FARestroomSolid: "\u{f7bd}", FAIcon.FARetweetSolid: "\u{f079}", FAIcon.FARibbonSolid: "\u{f4d6}", FAIcon.FARingSolid: "\u{f70b}", FAIcon.FARoadSolid: "\u{f018}", FAIcon.FARobotSolid: "\u{f544}", FAIcon.FARocketSolid: "\u{f135}", FAIcon.FARouteSolid: "\u{f4d7}", FAIcon.FARssSolid: "\u{f09e}", FAIcon.FARssSquareSolid: "\u{f143}", FAIcon.FARubleSignSolid: "\u{f158}", FAIcon.FARulerCombinedSolid: "\u{f546}", FAIcon.FARulerHorizontalSolid: "\u{f547}", FAIcon.FARulerSolid: "\u{f545}", FAIcon.FARulerVerticalSolid: "\u{f548}", FAIcon.FARunningSolid: "\u{f70c}", FAIcon.FARupeeSignSolid: "\u{f156}", FAIcon.FASadCryRegular: "\u{f5b3}", FAIcon.FASadCrySolid: "\u{f5b3}", FAIcon.FASadTearRegular: "\u{f5b4}", FAIcon.FASadTearSolid: "\u{f5b4}", FAIcon.FASatelliteDishSolid: "\u{f7c0}", FAIcon.FASatelliteSolid: "\u{f7bf}", FAIcon.FASaveRegular: "\u{f0c7}", FAIcon.FASaveSolid: "\u{f0c7}", FAIcon.FASchoolSolid: "\u{f549}", FAIcon.FAScrewdriverSolid: "\u{f54a}", FAIcon.FAScrollSolid: "\u{f70e}", FAIcon.FASdCardSolid: "\u{f7c2}", FAIcon.FASearchDollarSolid: "\u{f688}", FAIcon.FASearchLocationSolid: "\u{f689}", FAIcon.FASearchMinusSolid: "\u{f010}", FAIcon.FASearchPlusSolid: "\u{f00e}", FAIcon.FASearchSolid: "\u{f002}", FAIcon.FASeedlingSolid: "\u{f4d8}", FAIcon.FAServerSolid: "\u{f233}", FAIcon.FAShapesSolid: "\u{f61f}", FAIcon.FAShareAltSolid: "\u{f1e0}", FAIcon.FAShareAltSquareSolid: "\u{f1e1}", FAIcon.FAShareSolid: "\u{f064}", FAIcon.FAShareSquareRegular: "\u{f14d}", FAIcon.FAShareSquareSolid: "\u{f14d}", FAIcon.FAShekelSignSolid: "\u{f20b}", FAIcon.FAShieldAltSolid: "\u{f3ed}", FAIcon.FAShipSolid: "\u{f21a}", FAIcon.FAShippingFastSolid: "\u{f48b}", FAIcon.FAShoePrintsSolid: "\u{f54b}", FAIcon.FAShoppingBagSolid: "\u{f290}", FAIcon.FAShoppingBasketSolid: "\u{f291}", FAIcon.FAShoppingCartSolid: "\u{f07a}", FAIcon.FAShowerSolid: "\u{f2cc}", FAIcon.FAShuttleVanSolid: "\u{f5b6}", FAIcon.FASignInAltSolid: "\u{f2f6}", FAIcon.FASignLanguageSolid: "\u{f2a7}", FAIcon.FASignOutAltSolid: "\u{f2f5}", FAIcon.FASignSolid: "\u{f4d9}", FAIcon.FASignalSolid: "\u{f012}", FAIcon.FASignatureSolid: "\u{f5b7}", FAIcon.FASimCardSolid: "\u{f7c4}", FAIcon.FASitemapSolid: "\u{f0e8}", FAIcon.FASkatingSolid: "\u{f7c5}", FAIcon.FASkiingNordicSolid: "\u{f7ca}", FAIcon.FASkiingSolid: "\u{f7c9}", FAIcon.FASkullCrossbonesSolid: "\u{f714}", FAIcon.FASkullSolid: "\u{f54c}", FAIcon.FASlashSolid: "\u{f715}", FAIcon.FASleighSolid: "\u{f7cc}", FAIcon.FASlidersHSolid: "\u{f1de}", FAIcon.FASmileBeamRegular: "\u{f5b8}", FAIcon.FASmileBeamSolid: "\u{f5b8}", FAIcon.FASmileRegular: "\u{f118}", FAIcon.FASmileSolid: "\u{f118}", FAIcon.FASmileWinkRegular: "\u{f4da}", FAIcon.FASmileWinkSolid: "\u{f4da}", FAIcon.FASmogSolid: "\u{f75f}", FAIcon.FASmokingBanSolid: "\u{f54d}", FAIcon.FASmokingSolid: "\u{f48d}", FAIcon.FASmsSolid: "\u{f7cd}", FAIcon.FASnowboardingSolid: "\u{f7ce}", FAIcon.FASnowflakeRegular: "\u{f2dc}", FAIcon.FASnowflakeSolid: "\u{f2dc}", FAIcon.FASnowmanSolid: "\u{f7d0}", FAIcon.FASnowplowSolid: "\u{f7d2}", FAIcon.FASocksSolid: "\u{f696}", FAIcon.FASolarPanelSolid: "\u{f5ba}", FAIcon.FASortAlphaDownAltSolid: "\u{f881}", FAIcon.FASortAlphaDownSolid: "\u{f15d}", FAIcon.FASortAlphaUpAltSolid: "\u{f882}", FAIcon.FASortAlphaUpSolid: "\u{f15e}", FAIcon.FASortAmountDownAltSolid: "\u{f884}", FAIcon.FASortAmountDownSolid: "\u{f160}", FAIcon.FASortAmountUpAltSolid: "\u{f885}", FAIcon.FASortAmountUpSolid: "\u{f161}", FAIcon.FASortDownSolid: "\u{f0dd}", FAIcon.FASortNumericDownAltSolid: "\u{f886}", FAIcon.FASortNumericDownSolid: "\u{f162}", FAIcon.FASortNumericUpAltSolid: "\u{f887}", FAIcon.FASortNumericUpSolid: "\u{f163}", FAIcon.FASortSolid: "\u{f0dc}", FAIcon.FASortUpSolid: "\u{f0de}", FAIcon.FASpaSolid: "\u{f5bb}", FAIcon.FASpaceShuttleSolid: "\u{f197}", FAIcon.FASpellCheckSolid: "\u{f891}", FAIcon.FASpiderSolid: "\u{f717}", FAIcon.FASpinnerSolid: "\u{f110}", FAIcon.FASplotchSolid: "\u{f5bc}", FAIcon.FASprayCanSolid: "\u{f5bd}", FAIcon.FASquareFullSolid: "\u{f45c}", FAIcon.FASquareRegular: "\u{f0c8}", FAIcon.FASquareRootAltSolid: "\u{f698}", FAIcon.FASquareSolid: "\u{f0c8}", FAIcon.FAStampSolid: "\u{f5bf}", FAIcon.FAStarAndCrescentSolid: "\u{f699}", FAIcon.FAStarHalfAltSolid: "\u{f5c0}", FAIcon.FAStarHalfRegular: "\u{f089}", FAIcon.FAStarHalfSolid: "\u{f089}", FAIcon.FAStarOfDavidSolid: "\u{f69a}", FAIcon.FAStarOfLifeSolid: "\u{f621}", FAIcon.FAStarRegular: "\u{f005}", FAIcon.FAStarSolid: "\u{f005}", FAIcon.FAStepBackwardSolid: "\u{f048}", FAIcon.FAStepForwardSolid: "\u{f051}", FAIcon.FAStethoscopeSolid: "\u{f0f1}", FAIcon.FAStickyNoteRegular: "\u{f249}", FAIcon.FAStickyNoteSolid: "\u{f249}", FAIcon.FAStopCircleRegular: "\u{f28d}", FAIcon.FAStopCircleSolid: "\u{f28d}", FAIcon.FAStopSolid: "\u{f04d}", FAIcon.FAStopwatchSolid: "\u{f2f2}", FAIcon.FAStoreAltSolid: "\u{f54f}", FAIcon.FAStoreSolid: "\u{f54e}", FAIcon.FAStreamSolid: "\u{f550}", FAIcon.FAStreetViewSolid: "\u{f21d}", FAIcon.FAStrikethroughSolid: "\u{f0cc}", FAIcon.FAStroopwafelSolid: "\u{f551}", FAIcon.FASubscriptSolid: "\u{f12c}", FAIcon.FASubwaySolid: "\u{f239}", FAIcon.FASuitcaseRollingSolid: "\u{f5c1}", FAIcon.FASuitcaseSolid: "\u{f0f2}", FAIcon.FASunRegular: "\u{f185}", FAIcon.FASunSolid: "\u{f185}", FAIcon.FASuperscriptSolid: "\u{f12b}", FAIcon.FASurpriseRegular: "\u{f5c2}", FAIcon.FASurpriseSolid: "\u{f5c2}", FAIcon.FASwatchbookSolid: "\u{f5c3}", FAIcon.FASwimmerSolid: "\u{f5c4}", FAIcon.FASwimmingPoolSolid: "\u{f5c5}", FAIcon.FASynagogueSolid: "\u{f69b}", FAIcon.FASyncAltSolid: "\u{f2f1}", FAIcon.FASyncSolid: "\u{f021}", FAIcon.FASyringeSolid: "\u{f48e}", FAIcon.FATableSolid: "\u{f0ce}", FAIcon.FATableTennisSolid: "\u{f45d}", FAIcon.FATabletAltSolid: "\u{f3fa}", FAIcon.FATabletSolid: "\u{f10a}", FAIcon.FATabletsSolid: "\u{f490}", FAIcon.FATachometerAltSolid: "\u{f3fd}", FAIcon.FATagSolid: "\u{f02b}", FAIcon.FATagsSolid: "\u{f02c}", FAIcon.FATapeSolid: "\u{f4db}", FAIcon.FATasksSolid: "\u{f0ae}", FAIcon.FATaxiSolid: "\u{f1ba}", FAIcon.FATeethOpenSolid: "\u{f62f}", FAIcon.FATeethSolid: "\u{f62e}", FAIcon.FATemperatureHighSolid: "\u{f769}", FAIcon.FATemperatureLowSolid: "\u{f76b}", FAIcon.FATengeSolid: "\u{f7d7}", FAIcon.FATerminalSolid: "\u{f120}", FAIcon.FATextHeightSolid: "\u{f034}", FAIcon.FATextWidthSolid: "\u{f035}", FAIcon.FAThLargeSolid: "\u{f009}", FAIcon.FAThListSolid: "\u{f00b}", FAIcon.FAThSolid: "\u{f00a}", FAIcon.FATheaterMasksSolid: "\u{f630}", FAIcon.FAThermometerEmptySolid: "\u{f2cb}", FAIcon.FAThermometerFullSolid: "\u{f2c7}", FAIcon.FAThermometerHalfSolid: "\u{f2c9}", FAIcon.FAThermometerQuarterSolid: "\u{f2ca}", FAIcon.FAThermometerSolid: "\u{f491}", FAIcon.FAThermometerThreeQuartersSolid: "\u{f2c8}", FAIcon.FAThumbsDownRegular: "\u{f165}", FAIcon.FAThumbsDownSolid: "\u{f165}", FAIcon.FAThumbsUpRegular: "\u{f164}", FAIcon.FAThumbsUpSolid: "\u{f164}", FAIcon.FAThumbtackSolid: "\u{f08d}", FAIcon.FATicketAltSolid: "\u{f3ff}", FAIcon.FATimesCircleRegular: "\u{f057}", FAIcon.FATimesCircleSolid: "\u{f057}", FAIcon.FATimesSolid: "\u{f00d}", FAIcon.FATintSlashSolid: "\u{f5c7}", FAIcon.FATintSolid: "\u{f043}", FAIcon.FATiredRegular: "\u{f5c8}", FAIcon.FATiredSolid: "\u{f5c8}", FAIcon.FAToggleOffSolid: "\u{f204}", FAIcon.FAToggleOnSolid: "\u{f205}", FAIcon.FAToiletPaperSolid: "\u{f71e}", FAIcon.FAToiletSolid: "\u{f7d8}", FAIcon.FAToolboxSolid: "\u{f552}", FAIcon.FAToolsSolid: "\u{f7d9}", FAIcon.FAToothSolid: "\u{f5c9}", FAIcon.FATorahSolid: "\u{f6a0}", FAIcon.FAToriiGateSolid: "\u{f6a1}", FAIcon.FATractorSolid: "\u{f722}", FAIcon.FATrademarkSolid: "\u{f25c}", FAIcon.FATrafficLightSolid: "\u{f637}", FAIcon.FATrainSolid: "\u{f238}", FAIcon.FATramSolid: "\u{f7da}", FAIcon.FATransgenderAltSolid: "\u{f225}", FAIcon.FATransgenderSolid: "\u{f224}", FAIcon.FATrashAltRegular: "\u{f2ed}", FAIcon.FATrashAltSolid: "\u{f2ed}", FAIcon.FATrashRestoreAltSolid: "\u{f82a}", FAIcon.FATrashRestoreSolid: "\u{f829}", FAIcon.FATrashSolid: "\u{f1f8}", FAIcon.FATreeSolid: "\u{f1bb}", FAIcon.FATrophySolid: "\u{f091}", FAIcon.FATruckLoadingSolid: "\u{f4de}", FAIcon.FATruckMonsterSolid: "\u{f63b}", FAIcon.FATruckMovingSolid: "\u{f4df}", FAIcon.FATruckPickupSolid: "\u{f63c}", FAIcon.FATruckSolid: "\u{f0d1}", FAIcon.FATshirtSolid: "\u{f553}", FAIcon.FATtySolid: "\u{f1e4}", FAIcon.FATvSolid: "\u{f26c}", FAIcon.FAUmbrellaBeachSolid: "\u{f5ca}", FAIcon.FAUmbrellaSolid: "\u{f0e9}", FAIcon.FAUnderlineSolid: "\u{f0cd}", FAIcon.FAUndoAltSolid: "\u{f2ea}", FAIcon.FAUndoSolid: "\u{f0e2}", FAIcon.FAUniversalAccessSolid: "\u{f29a}", FAIcon.FAUniversitySolid: "\u{f19c}", FAIcon.FAUnlinkSolid: "\u{f127}", FAIcon.FAUnlockAltSolid: "\u{f13e}", FAIcon.FAUnlockSolid: "\u{f09c}", FAIcon.FAUploadSolid: "\u{f093}", FAIcon.FAUserAltSlashSolid: "\u{f4fa}", FAIcon.FAUserAltSolid: "\u{f406}", FAIcon.FAUserAstronautSolid: "\u{f4fb}", FAIcon.FAUserCheckSolid: "\u{f4fc}", FAIcon.FAUserCircleRegular: "\u{f2bd}", FAIcon.FAUserCircleSolid: "\u{f2bd}", FAIcon.FAUserClockSolid: "\u{f4fd}", FAIcon.FAUserCogSolid: "\u{f4fe}", FAIcon.FAUserEditSolid: "\u{f4ff}", FAIcon.FAUserFriendsSolid: "\u{f500}", FAIcon.FAUserGraduateSolid: "\u{f501}", FAIcon.FAUserInjuredSolid: "\u{f728}", FAIcon.FAUserLockSolid: "\u{f502}", FAIcon.FAUserMdSolid: "\u{f0f0}", FAIcon.FAUserMinusSolid: "\u{f503}", FAIcon.FAUserNinjaSolid: "\u{f504}", FAIcon.FAUserNurseSolid: "\u{f82f}", FAIcon.FAUserPlusSolid: "\u{f234}", FAIcon.FAUserRegular: "\u{f007}", FAIcon.FAUserSecretSolid: "\u{f21b}", FAIcon.FAUserShieldSolid: "\u{f505}", FAIcon.FAUserSlashSolid: "\u{f506}", FAIcon.FAUserSolid: "\u{f007}", FAIcon.FAUserTagSolid: "\u{f507}", FAIcon.FAUserTieSolid: "\u{f508}", FAIcon.FAUserTimesSolid: "\u{f235}", FAIcon.FAUsersCogSolid: "\u{f509}", FAIcon.FAUsersSolid: "\u{f0c0}", FAIcon.FAUtensilSpoonSolid: "\u{f2e5}", FAIcon.FAUtensilsSolid: "\u{f2e7}", FAIcon.FAVectorSquareSolid: "\u{f5cb}", FAIcon.FAVenusDoubleSolid: "\u{f226}", FAIcon.FAVenusMarsSolid: "\u{f228}", FAIcon.FAVenusSolid: "\u{f221}", FAIcon.FAVialSolid: "\u{f492}", FAIcon.FAVialsSolid: "\u{f493}", FAIcon.FAVideoSlashSolid: "\u{f4e2}", FAIcon.FAVideoSolid: "\u{f03d}", FAIcon.FAViharaSolid: "\u{f6a7}", FAIcon.FAVoicemailSolid: "\u{f897}", FAIcon.FAVolleyballBallSolid: "\u{f45f}", FAIcon.FAVolumeDownSolid: "\u{f027}", FAIcon.FAVolumeMuteSolid: "\u{f6a9}", FAIcon.FAVolumeOffSolid: "\u{f026}", FAIcon.FAVolumeUpSolid: "\u{f028}", FAIcon.FAVoteYeaSolid: "\u{f772}", FAIcon.FAVrCardboardSolid: "\u{f729}", FAIcon.FAWalkingSolid: "\u{f554}", FAIcon.FAWalletSolid: "\u{f555}", FAIcon.FAWarehouseSolid: "\u{f494}", FAIcon.FAWaterSolid: "\u{f773}", FAIcon.FAWaveSquareSolid: "\u{f83e}", FAIcon.FAWeightHangingSolid: "\u{f5cd}", FAIcon.FAWeightSolid: "\u{f496}", FAIcon.FAWheelchairSolid: "\u{f193}", FAIcon.FAWifiSolid: "\u{f1eb}", FAIcon.FAWindSolid: "\u{f72e}", FAIcon.FAWindowCloseRegular: "\u{f410}", FAIcon.FAWindowCloseSolid: "\u{f410}", FAIcon.FAWindowMaximizeRegular: "\u{f2d0}", FAIcon.FAWindowMaximizeSolid: "\u{f2d0}", FAIcon.FAWindowMinimizeRegular: "\u{f2d1}", FAIcon.FAWindowMinimizeSolid: "\u{f2d1}", FAIcon.FAWindowRestoreRegular: "\u{f2d2}", FAIcon.FAWindowRestoreSolid: "\u{f2d2}", FAIcon.FAWineBottleSolid: "\u{f72f}", FAIcon.FAWineGlassAltSolid: "\u{f5ce}", FAIcon.FAWineGlassSolid: "\u{f4e3}", FAIcon.FAWonSignSolid: "\u{f159}", FAIcon.FAWrenchSolid: "\u{f0ad}", FAIcon.FAXRaySolid: "\u{f497}", FAIcon.FAYenSignSolid: "\u{f157}", FAIcon.FAYinYangSolid: "\u{f6ad}", ] guard let code = icons[self] else { return "" } return code } func font(size: CGFloat) -> UIFont { var font: UIFont? if self.rawValue >= 100000 && self.rawValue <= 199999 { font = UIFont(name: "FontAwesome5Brands-Regular", size: size) } else if self.rawValue >= 200000 && self.rawValue <= 299999 { font = UIFont(name: "FontAwesome5Free-Light", size: size) } else if self.rawValue >= 400000 && self.rawValue <= 499999 { font = UIFont(name: "FontAwesome5Free-Solid", size: size) } else { font = UIFont(name: "FontAwesome5Free-Regular", size: size) } if let f = font { return f } LogError("FontAwesome font not located - failing to LastResort font") for family in UIFont.familyNames { LogError("Family name " + family) let fontNames = UIFont.fontNames(forFamilyName: family) for font in fontNames { LogError(" - Font name: " + font) } } return UIFont.systemFont(ofSize: size) // Last resort } }
gpl-3.0
3f42afe4ae01baacaa6a076fc1baa022
41.188217
111
0.633022
3.814091
false
false
false
false
dn-m/Collections
Collections/Tree.swift
1
10498
// // ImmutableTree.swift // Collections // // Created by James Bean on 12/9/16. // // /// Value-semantic, immutable Tree structure. public enum Tree <Branch,Leaf> { /// Things that can go wrong when doing things to a `Tree`. public enum Error: Swift.Error { case indexOutOfBounds case branchOperationPerformedOnLeaf case illFormedIndexPath } /// Transforms for `branch` and `leaf` cases. public struct Transform <B,L> { let branch: (Branch) -> B let leaf: (Leaf) -> L public init(branch: @escaping (Branch) -> B, leaf: @escaping (Leaf) -> L) { self.branch = branch self.leaf = leaf } } // MARK: - Cases /// Leaf. case leaf(Leaf) /// Branch. indirect case branch(Branch, [Tree]) // MARK: - Instance Properties /// Leaves of this `Tree`. public var leaves: [Leaf] { func flattened(accum: [Leaf], tree: Tree) -> [Leaf] { switch tree { case .branch(_, let trees): return trees.reduce(accum, flattened) case .leaf(let value): return accum + [value] } } return flattened(accum: [], tree: self) } /// All of the values along the paths from this node to each leaf public var paths: [[Either<Branch,Leaf>]] { func traverse(_ tree: Tree, accum: [[Either<Branch,Leaf>]]) -> [[Either<Branch,Leaf>]] { var accum = accum let path = accum.popLast() ?? [] switch tree { case .leaf(let value): return accum + (path + .right(value)) case .branch(let value, let trees): return trees.flatMap { traverse($0, accum: accum + (path + .left(value))) } } } return traverse(self, accum: []) } /// Height of a `Tree`. public var height: Int { func traverse(_ tree: Tree, height: Int) -> Int { switch tree { case .leaf: return height case .branch(_, let trees): return trees.map { traverse($0, height: height + 1) }.max()! } } return traverse(self, height: 0) } // MARK: - Initializers /// Replace the subtree at the given `index` for the given `tree`. /// /// - throws: `TreeError` if `self` is a `leaf`. public func replacingTree(at index: Int, with tree: Tree) throws -> Tree { switch self { case .leaf: throw Error.branchOperationPerformedOnLeaf case .branch(let value, let trees): return .branch(value, try trees.replacingElement(at: index, with: tree)) } } /// Replace the subtree at the given `path`. /// /// - throws: `TreeError` if the given `path` is valid. public func replacingTree(through path: [Int], with tree: Tree) throws -> Tree { func traverse(_ tree: Tree, inserting newTree: Tree, path: [Int]) throws -> Tree { switch tree { // This should never be called on a leaf case .leaf: throw Error.branchOperationPerformedOnLeaf // Either `traverse` futher, or replace at last index specified in `path`. case .branch(let value, let trees): // Ensure that the `indexPath` given is valid guard let (index, remainingPath) = path.destructured, let subTree = trees[safe: index] else { throw Error.illFormedIndexPath } // We are done if only one `index` remaining in `indexPath` guard path.count > 1 else { return .branch(value, try trees.replacingElement(at: index, with: newTree)) } // Otherwise, keep recursing down return try tree.replacingTree( at: index, with: try traverse(subTree, inserting: newTree, path: remainingPath) ) } } return try traverse(self, inserting: tree, path: path) } /// - returns: A new `Tree` with the given `tree` inserted at the given `index`, through /// the given `path`. /// /// - throws: `TreeError` in the case of ill-formed index paths and indexes out-of-range. public func inserting(_ tree: Tree, through path: [Int] = [], at index: Int) throws -> Tree { func traverse( _ tree: Tree, inserting newTree: Tree, through path: [Int], at index: Int ) throws -> Tree { switch tree { // We should never get to a `leaf`. case .leaf: throw Error.branchOperationPerformedOnLeaf // Either `traverse` further, or insert to accumulated path case .branch(let value, let trees): // If we have exhausted our path, attempt to insert `newTree` at `index` guard let (head, tail) = path.destructured else { return Tree.branch(value, try insert(newTree, into: trees, at: index)) } guard let subTree = trees[safe: head] else { throw Error.illFormedIndexPath } let newBranch = try traverse(subTree, inserting: newTree, through: tail, at: index ) return try tree.replacingTree(at: index, with: newBranch) } } return try traverse(self, inserting: tree, through: path, at: index) } public func mapLeaves <T> (_ transform: @escaping (Leaf) -> T) -> Tree<Branch,T> { switch self { case .leaf(let value): return .leaf(transform(value)) case let .branch(value, trees): return .branch(value, trees.map { $0.mapLeaves(transform) }) } } public func zipLeaves <C: RangeReplaceableCollection> (_ collection: C) -> Tree<Branch, C.Iterator.Element> { return zipLeaves(collection) { _, value in value } } // FIXME: Instead of copying `collection`, increment an `index`, pointing to `collection`. public func zipLeaves <C: RangeReplaceableCollection, T> ( _ collection: C, _ transform: @escaping (Leaf, C.Iterator.Element) -> T ) -> Tree<Branch,T> { var newValues = collection func traverse(_ tree: Tree) -> Tree<Branch,T> { switch tree { case .leaf(let leaf): guard let value = newValues.first else { fatalError("Incompatible collection for leaves") } return .leaf(transform(leaf,value)) case let .branch(branch, trees): var newTrees: [Tree<Branch,T>] = [] for tree in trees { switch tree { case .leaf: newTrees.append(traverse(tree)) newValues.removeFirst() case .branch: newTrees.append(traverse(tree)) } } return .branch(branch, newTrees) } } return traverse(self) } public func map <B,L> (_ transform: Transform<B,L>) -> Tree<B,L> { switch self { case .leaf(let value): return .leaf(transform.leaf(value)) case .branch(let value, let trees): return .branch(transform.branch(value), trees.map { $0.map(transform) }) } } private func insert <A> (_ element: A, into elements: [A], at index: Int) throws -> [A] { guard let (left, right) = elements.split(at: index) else { throw Error.illFormedIndexPath } return left + [element] + right } } extension Tree: CustomStringConvertible { /// Printed description. public var description: String { func indents(_ amount: Int) -> String { return (0 ..< amount).reduce("") { accum, _ in accum + " " } } func traverse(tree: Tree, indentation: Int = 0) -> String { switch tree { case .leaf(let value): return indents(indentation) + "\(value)" case .branch(let value, let trees): return ( indents(indentation) + "\(value)\n" + trees .map { traverse(tree: $0, indentation: indentation + 1) } .joined(separator: "\n") ) } } return traverse(tree: self) } } /// - returns: A new `Tree` resulting from applying the given function `f` to each /// corresponding node in the given trees `a` and `b`. /// /// - invariant: `a` and `b` are the same shape. public func zip <T,U,V> (_ a: Tree<T,T>, _ b: Tree<U,U>, _ f: (T, U) -> V) -> Tree<V,V> { switch (a,b) { case (.leaf(let a), .leaf(let b)): return .leaf(f(a,b)) case (.branch(let a, let aTrees), .branch(let b, let bTrees)): return .branch(f(a,b), zip(aTrees,bTrees).map { a,b in zip(a,b,f) }) default: fatalError("Incompatible trees") } } /// - TODO: Make extension, retroactively conforming to `Equatable` when Swift allows it /// - returns: `true` if two `Tree` values are equivalent. Otherwise, `false`. public func == <T: Equatable, U: Equatable> (lhs: Tree<T,U>, rhs: Tree<T,U>) -> Bool { switch (lhs, rhs) { case (.leaf(let a), .leaf(let b)): return a == b case (.branch(let valueA, let treesA), .branch(let valueB, let treesB)): return valueA == valueB && treesA == treesB default: return false } } /// - returns: `true` if two `Tree` values are not equivalent. Otherwise, `false`. public func != <T: Equatable, U: Equatable> (lhs: Tree<T,U>, rhs: Tree<T,U>) -> Bool { return !(lhs == rhs) } /// - returns: `true` if two arrays of `Tree` values are equivalent. Otherwise, `false.` public func == <T: Equatable, U: Equatable> (lhs: [Tree<T,U>], rhs: [Tree<T,U>]) -> Bool { guard lhs.count == rhs.count else { return false } for (lhs, rhs) in zip(lhs, rhs) { if lhs != rhs { return false } } return true }
mit
d4c6c3fcc14dcff064e0946f1f2ab9dd
29.517442
95
0.524576
4.250202
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Source/ColorEffectImageContainer.swift
1
4674
import UIKit import RxDataSources import RxSwift import SnapKit /** * Allows us to use an image as a mask and set its color, similar to text. * Image is displayed in the subview `imageView` which should be positioned and * sized in the container as the user wishes. Default size is image's size. */ class ColorEffectImageContainer: UIView { private var disposeBag = DisposeBag() lazy var imageView: ColorEffectImageView = { return ColorEffectImageView(container: self) }() var image: UIImage? { didSet { imageView.setNeedsDisplay() remakeImageViewConstraints() } } var blendMode: CGBlendMode { didSet { imageView.setNeedsDisplay() } } var fillColor: UIColor = .white { didSet { imageView.setNeedsDisplay() } } enum ImageViewSizing { case intrinsic case scaleFit case scaleFill } var imageViewSizing: ImageViewSizing = .intrinsic { didSet { imageView.setNeedsDisplay() remakeImageViewConstraints() } } private var imageViewConstraints = [Constraint]() public init(image: UIImage?, blendMode: CGBlendMode = .multiply) { self.image = image self.blendMode = blendMode super.init(frame: CGRect.zero) isUserInteractionEnabled = false clipsToBounds = true addSubview(imageView) remakeImageViewConstraints() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func makeDefaultImageViewConstraints() { imageView.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } } func centerImageView() { imageView.snp.makeConstraints { (make) in make.center.equalToSuperview() } } private func remakeImageViewConstraints() { for constraint in imageViewConstraints { constraint.deactivate() } imageViewConstraints = [] imageView.snp.makeConstraints { (make) in let imageSize = image?.size ?? CGSize.zero let sizing = imageViewSizing if sizing == .intrinsic { imageViewConstraints.append(make.width.equalTo(imageSize.width).constraint) imageViewConstraints.append(make.height.equalTo(imageSize.height).constraint) return } var aspectRatio = imageSize.height / imageSize.width if !aspectRatio.isFinite { aspectRatio = 0 } imageViewConstraints.append( make.height.equalTo(imageView.snp.width).multipliedBy(aspectRatio).constraint) if aspectRatio > 0 && (sizing == .scaleFit || sizing == .scaleFill) { if aspectRatio > 1 || (aspectRatio <= 1 && sizing == .scaleFill) { imageViewConstraints.append(make.height.equalToSuperview().constraint) } else { imageViewConstraints.append(make.width.equalToSuperview().constraint) } } } } } class ColorEffectImageView: UIView { weak var container: ColorEffectImageContainer? public init(container: ColorEffectImageContainer) { super.init(frame: CGRect.zero) isOpaque = false self.container = container } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UIView override open func draw(_ rect: CGRect) { super.draw(rect) let ctx = UIGraphicsGetCurrentContext() ctx?.setFillColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0).cgColor) ctx?.fill(bounds) if let container = container, let image = container.image { let drawRect = CGRect(origin: CGPoint.zero, size: bounds.size) image.draw(in: drawRect, blendMode: .normal, alpha: container.fillColor.cgColor.alpha) ctx?.translateBy(x: 0, y: drawRect.size.height) ctx?.scaleBy(x: 1, y: -1) ctx?.clip(to: drawRect, mask: image.cgImage!) ctx?.setFillColor(container.fillColor.cgColor) ctx?.setBlendMode(container.blendMode) ctx?.fill(drawRect) } } }
mit
aa9c75a7aa61723f008285c6d2302288
28.961538
98
0.575524
5.415991
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
GeekSpeak Show Timer/SettingsViewController.swift
2
7910
import UIKit class SettingsViewController: UIViewController { var timer: Timer? var backgroundBlurringInProgress = false // Required properties @IBOutlet weak var contentView: UIView! // The backupImageView is only a gross fix to hide that the backgroundImageView // is disappearing when the REFrostedViewController animates is out of view @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var add1SecondButton: UIButton! @IBOutlet weak var add5SecondsButton: UIButton! @IBOutlet weak var add10SecondsButton: UIButton! @IBOutlet weak var remove1SecondButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var segment1Label: UILabel! @IBOutlet weak var segment2Label: UILabel! @IBOutlet weak var segment3Label: UILabel! @IBOutlet weak var postShowLabel: UILabel! // MARK: Convience Properties var timerViewController: TimerViewController? var blurredImageLeftsideContraint: NSLayoutConstraint? var useDemoDurations = false func updateUseDemoDurations() { useDemoDurations = UserDefaults.standard .bool(forKey: Timer.Constants.UseDemoDurations) } // MARK: ViewController override func viewDidLoad() { addContraintsForContentView() } override func viewWillAppear(_ animated: Bool) { generateBlurredBackground() updateElapsedTimeLabels() registerForTimerNotifications() addContraintForBlurredImage() } override func viewDidAppear(_ animated: Bool) { } override func viewWillDisappear(_ animated: Bool) { unregisterForTimerNotifications() } override func viewDidDisappear(_ animated: Bool) { removeContraintForBlurredImage() } // MARK: Actions @IBAction func add1SecondButtonPressed(_ sender: UIButton) { timer?.duration += 1.0 generateBlurredBackground() } @IBAction func add5SecondsButtonPressed(_ sender: UIButton) { timer?.duration += 5.0 generateBlurredBackground() } @IBAction func add10SecondsButtonPressed(_ sender: UIButton) { timer?.duration += 10.0 generateBlurredBackground() } @IBAction func remove1SecondButtonPressed(_ sender: UIButton) { timer?.duration -= 1.0 generateBlurredBackground() } @IBAction func resetButtonPressed(_ sender: UIButton) { resetTimer() generateBlurredBackground() } // MARK: - // MARK: Timer management func resetTimer() { updateUseDemoDurations() timer?.reset(usingDemoTiming: useDemoDurations) // Delay the generateBlurredBackground until the TimerViews are drawn // by waiting until the next run loop. self.perform(#selector(SettingsViewController.generateBlurredBackground), with: .none, afterDelay: 0.0) } @objc func generateBlurredBackground() { if backgroundBlurringInProgress { return } backgroundBlurringInProgress = true if let underneathViewController = timerViewController { // set up the graphics context to render the screen snapshot. // Note the scale value... Values greater than 1 make a context smaller // than the detail view controller. Smaller context means faster rendering // of the final blurred background image let scaleValue = CGFloat(16) let underneathViewControllerSize = underneathViewController.view.frame.size let contextSize = CGSize(width: underneathViewControllerSize.width / scaleValue, height: underneathViewControllerSize.height / scaleValue) UIGraphicsBeginImageContextWithOptions(contextSize, true, 1) let drawingRect = CGRect(x: 0, y: 0, width: contextSize.width, height: contextSize.height) // Now grab the snapshot of the detail view controllers content underneathViewController.view.drawHierarchy( in: drawingRect, afterScreenUpdates: false) let snapshotImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Now get a sub-image of our snapshot. Just grab the portion of the // shapshot that would be covered by the master view controller when // it becomes visible. // Pulling out the sub-image means we can supply an appropriately sized // background image for the master controller, and makes application of // the blur effect run faster since we are only only blurring image data // that will actually be visible. let subRect = CGRect(x: 0, y: 0, width: self.view.frame.size.width / scaleValue, height: self.view.frame.size.height / scaleValue) if let subImage = snapshotImage?.cgImage?.cropping(to: subRect) { let backgroundImage = UIImage(cgImage: subImage) // CGImageRelease(subImage) // Now actually apply the blur to the snapshot and set the background // behind our master view controller DispatchQueue.global(qos: .userInteractive).async() { let blurredBackgroundImage = backgroundImage.applyBlur(withRadius: 2, tintColor: UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5), saturationDeltaFactor: 1.8, maskImage: nil) DispatchQueue.main.sync() { self.backgroundImageView.image = blurredBackgroundImage self.backgroundBlurringInProgress = false } } } else { backgroundImageView.image = UIImage.imageWithColor(UIColor.black) } } } //generateBlurredBackground func addContraintsForContentView() { let leftConstraint = NSLayoutConstraint(item: contentView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 0.0) view.addConstraint(leftConstraint) let rightConstraint = NSLayoutConstraint(item: contentView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: 0.0) view.addConstraint(rightConstraint) } func addContraintForBlurredImage() { guard let parent = parent else {return} if blurredImageLeftsideContraint.hasNoValue { let leftConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .left, relatedBy: .equal, toItem: parent.view, attribute: .left, multiplier: 1.0, constant: 0.0) blurredImageLeftsideContraint = leftConstraint parent.view.addConstraint(leftConstraint) } } func removeContraintForBlurredImage() { guard let parent = parent else { blurredImageLeftsideContraint = .none return } if let contraint = blurredImageLeftsideContraint { parent.view.removeConstraint(contraint) blurredImageLeftsideContraint = .none } } }
mit
fe66ba7f27a3083334f36b50c3a78ee4
35.284404
96
0.600632
5.951843
false
false
false
false
keithbox/AngularJS-CRUD-PHP
third-party/js-xlsx/js-xlsx-0.13.5/demos/altjs/SheetJSCore.swift
4
3490
/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */ import JavaScriptCore; enum SJSError: Error { case badJSContext; case badJSWorkbook; case badJSWorksheet; }; class SJSWorksheet { var context: JSContext!; var wb: JSValue!; var ws: JSValue!; var idx: Int32; func toCSV() throws -> String { let XLSX: JSValue! = context.objectForKeyedSubscript("XLSX"); let utils: JSValue! = XLSX.objectForKeyedSubscript("utils"); let sheet_to_csv: JSValue! = utils.objectForKeyedSubscript("sheet_to_csv"); return sheet_to_csv.call(withArguments: [ws]).toString(); } init(ctx: JSContext, workbook: JSValue, worksheet: JSValue, idx: Int32) throws { self.context = ctx; self.wb = workbook; self.ws = worksheet; self.idx = idx; } } class SJSWorkbook { var context: JSContext!; var wb: JSValue!; var SheetNames: JSValue!; var Sheets: JSValue!; func getSheetAtIndex(idx: Int32) throws -> SJSWorksheet { let SheetName: String = SheetNames.atIndex(Int(idx)).toString(); let ws: JSValue! = Sheets.objectForKeyedSubscript(SheetName); return try SJSWorksheet(ctx: context, workbook: wb, worksheet: ws, idx: idx); } func writeBStr(bookType: String = "xlsx") throws -> String { let XLSX: JSValue! = context.objectForKeyedSubscript("XLSX"); context.evaluateScript(String(format: "var writeopts = {type:'binary', bookType:'%@'}", bookType)); let writeopts: JSValue! = context.objectForKeyedSubscript("writeopts"); let writefunc: JSValue! = XLSX.objectForKeyedSubscript("write"); return writefunc.call(withArguments: [wb, writeopts]).toString(); } init(ctx: JSContext, wb: JSValue) throws { self.context = ctx; self.wb = wb; self.SheetNames = wb.objectForKeyedSubscript("SheetNames"); self.Sheets = wb.objectForKeyedSubscript("Sheets"); } } class SheetJSCore { var context: JSContext!; var XLSX: JSValue!; func init_context() throws -> JSContext { var context: JSContext! do { context = JSContext(); context.exceptionHandler = { ctx, X in if let e = X { print(e.toString()); }; }; context.evaluateScript("var global = (function(){ return this; }).call(null);"); context.evaluateScript("if(typeof wbs == 'undefined') wbs = [];"); let src = try String(contentsOfFile: "xlsx.full.min.js"); context.evaluateScript(src); if context != nil { return context!; } } catch { print(error.localizedDescription); } throw SJSError.badJSContext; } func version() throws -> String { if let version = XLSX.objectForKeyedSubscript("version") { return version.toString(); } throw SJSError.badJSContext; } func readFile(file: String) throws -> SJSWorkbook { let data: String! = try String(contentsOfFile: file, encoding: String.Encoding.isoLatin1); return try readBStr(data: data); } func readBStr(data: String) throws -> SJSWorkbook { context.setObject(data, forKeyedSubscript: "payload" as (NSCopying & NSObjectProtocol)!); context.evaluateScript("var wb = XLSX.read(payload, {type:'binary'});"); let wb: JSValue! = context.objectForKeyedSubscript("wb"); if wb == nil { throw SJSError.badJSWorkbook; } return try SJSWorkbook(ctx: context, wb: wb); } init() throws { do { self.context = try init_context(); self.XLSX = self.context.objectForKeyedSubscript("XLSX"); if self.XLSX == nil { throw SJSError.badJSContext; } } catch { print(error.localizedDescription); } } }
mit
8a811cfa5d24e6607f13f08ae1b16b21
35.354167
103
0.680229
3.93018
false
false
false
false
aquarchitect/MyKit
Sources/Shared/Extensions/Foundation/Scanner+.swift
1
2561
// // Scanner+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // import Foundation public extension Scanner { // MARK: String public func scan(characters: CharacterSet) -> String? { var result: NSString? = "" return self.scanCharacters(from: characters, into: &result) ? (result as String?) : nil } public func scan(upto characters: CharacterSet) -> String? { var result: NSString? = "" return self.scanUpToCharacters(from: characters, into: &result) ? (result as String?) : nil } public func scan(string: String) -> String? { var result: NSString? = "" return self.scanString(string, into: &result) ? (result as String?) : nil } public func scanUpTo(string: String) -> String? { var result: NSString? = "" return self.scanUpTo(string, into: &result) ? (result as String?) : nil } // MARK: Number public func scanDouble() -> Double? { var result: Double = 0 return self.scanDouble(&result) ? result : nil } public func scanFloat() -> Float? { var result: Float = 0 return self.scanFloat(&result) ? result : nil } public func scanInt() -> Int? { var result: Int = 0 return self.scanInt(&result) ? result : nil } public func scanInt32() -> Int32? { var result: Int32 = 0 return self.scanInt32(&result) ? result : nil } public func scanInt64() -> Int64? { var result: Int64 = 0 return self.scanInt64(&result) ? result : nil } public func scanUInt64() -> UInt64? { var result: UInt64 = 0 return self.scanUnsignedLongLong(&result) ? result : nil } public func scanDecimal() -> Decimal? { var result = Decimal() return self.scanDecimal(&result) ? result : nil } // MARK: Hex Number public func scanHexDouble() -> Double? { var result: Double = 0 return self.scanHexDouble(&result) ? result : nil } public func scanHexFloat() -> Float? { var result: Float = 0 return self.scanHexFloat(&result) ? result : nil } public func scanHexUInt32() -> UInt32? { var result: UInt32 = 0 return self.scanHexInt32(&result) ? result : nil } public func scanHexUInt64() -> UInt64? { var result: UInt64 = 0 return self.scanHexInt64(&result) ? result : nil } }
mit
49d1bdb6bc06f511b60f9bcf80351f4a
23.625
71
0.564233
4.205255
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Base/Data Controllers/Data Sources/TableViewDataSource.swift
1
1494
import Foundation import UIKit protocol TableViewDataSourceDelegate: AnyObject { func title(forSection section: Int) -> String? } /// TableViewDataSource is a wrapper around a UITableViewDiffableDataSource that implements /// UITableViewDataSource for TBA where we manage no data states and whatnot for table views class TableViewDataSource<Section: Hashable, Item: Hashable>: UITableViewDiffableDataSource<Section, Item> { weak var delegate: TableViewDataSourceDelegate? weak var statefulDelegate: (Stateful & Refreshable)? // MARK: - Public Methods var isDataSourceEmpty: Bool { let snapshot = snapshot() return snapshot.itemIdentifiers.isEmpty } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { let sections = super.numberOfSections(in: tableView) if sections == 0 { statefulDelegate?.showNoDataView() } return sections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rows = super.tableView(tableView, numberOfRowsInSection: section) if rows == 0 { statefulDelegate?.showNoDataView() } else { statefulDelegate?.removeNoDataView() } return rows } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return delegate?.title(forSection: section) } }
mit
c39dc5d980e52aeaabb29ea774b9e98b
31.478261
108
0.695448
5.533333
false
false
false
false
rdgonzalez85/Contacts
Contacts/Contacts/ContactTableViewCell.swift
1
1701
// // ContactTableViewCell.swift // Contacts // // Created by Rodrigo Gonzalez on 4/22/16. // Copyright © 2016 Rodrigo Gonzalez. All rights reserved. // import UIKit class ContactTableViewCell: UITableViewCell { @IBOutlet weak var contactName: UILabel! @IBOutlet weak var contactDetail: UILabel! @IBOutlet weak var contactImageContainer: UIView! @IBOutlet weak var contactImage: UIImageView! @IBOutlet weak var contactImageLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code contactImageContainer.layer.masksToBounds = true contactImageContainer.layer.cornerRadius = contactImageContainer.frame.size.width/2 contactImageContainer.backgroundColor = ContactUtils.randomBackgroundColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setContactInformation(contact : Contact) { contactName.text = contact.displayName() contactDetail.text = contact.detail if let contactImage = contact.image { ImageLoader.sharedLoader.imageForUrl(contactImage, completionHandler:{(image: UIImage?, url: String) in self.contactImage.image = image self.contactImage.hidden = false }) contactImageLabel.hidden = true contactImageContainer.backgroundColor = .clearColor() } else { contactImage.hidden = true contactImageLabel.hidden = false contactImageLabel.text = contact.initials() } } }
mit
00170fcebda4f7fae2c186459ea38ed8
33.693878
115
0.674706
5.43131
false
false
false
false
khoogheem/GenesisKit
Shared/Internal/Error.swift
1
2938
// // Error.swift // GenesisKit // // Created by Kevin A. Hoogheem on 10/26/14. // Copyright (c) 2014 Kevin A. Hoogheem. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Internal Error Class to make sending errors regarding the framework easier */ let kGenesisKitErrorDomain = "com.GenesisKit.framework" public enum GKErrorCode: Int { /** A General Success */ case kGKErrorCodeSuccess = 200 /** A General Faluire */ case kGKErrorCodeFaluire = 400 /** Provides a description of the error Codes :returns: Returns The description of the error code in english */ public func description() -> String { switch self { case .kGKErrorCodeSuccess: return "Success" case .kGKErrorCodeFaluire: return "Faliure" } } } internal extension NSError { /** Constructs an NSError with the given message and Code :param: message A message to attach to the NSError :param: code A numeric code that is attached to the NSError :returns: returns a constructed NSError */ class func createError(message: String?, code: Int) -> NSError { if message != nil { return NSError(domain: kGenesisKitErrorDomain, code: code, userInfo: [NSLocalizedDescriptionKey: message!]) } return NSError(domain: kGenesisKitErrorDomain, code: code, userInfo: nil) } /** Constructs an NSError with the given message and Code :param: message A message to attach to the NSError :param: code A GKErrorCode that is attached to the NSError :returns: returns a constructed NSError */ class func createError(message: String?, code: GKErrorCode) -> NSError { if message != nil { return NSError(domain: kGenesisKitErrorDomain, code: code.rawValue, userInfo: [NSLocalizedDescriptionKey: message!]) } return NSError(domain: kGenesisKitErrorDomain, code: code.rawValue, userInfo: [NSLocalizedDescriptionKey: code.description()]) } }
mit
a8b87d74d6cb3517c1b03f2923cf7589
32.022472
128
0.742342
4.052414
false
false
false
false
milseman/swift
test/Parse/errors.swift
7
5413
// RUN: %target-typecheck-verify-swift enum MSV : Error { case Foo, Bar, Baz case CarriesInt(Int) var domain: String { return "" } var code: Int { return 0 } } func opaque_error() -> Error { return MSV.Foo } func one() { do { true ? () : throw opaque_error() // expected-error {{expected expression after '? ... :' in ternary expression}} } catch _ { } do { } catch { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } do { } catch where true { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } catch { } // <rdar://problem/20985280> QoI: improve diagnostic on improper pattern match on type do { throw opaque_error() } catch MSV { // expected-error {{'is' keyword required to pattern match against type name}} {{11-11=is }} } catch { } do { throw opaque_error() } catch is Error { // expected-warning {{'is' test is always true}} } func foo() throws {} do { #if false try foo() #endif } catch { // don't warn, #if code should be scanned. } do { #if false throw opaque_error() #endif } catch { // don't warn, #if code should be scanned. } } func takesAutoclosure(_ fn : @autoclosure () -> Int) {} func takesThrowingAutoclosure(_ fn : @autoclosure () throws -> Int) {} func genError() throws -> Int { throw MSV.Foo } func genNoError() -> Int { return 0 } func testAutoclosures() throws { takesAutoclosure(genError()) // expected-error {{call can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} takesAutoclosure(genNoError()) try takesAutoclosure(genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} try takesAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesAutoclosure(try genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} takesAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(try genError()) takesThrowingAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} try takesThrowingAutoclosure(genError()) try takesThrowingAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(genError()) // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{28-28=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{28-28=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{28-28=try! }} takesThrowingAutoclosure(genNoError()) } struct IllegalContext { var x: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} func foo(_ x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}} func catcher() throws { do { _ = try genError() } catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}} } catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} } } } func illformed() throws { do { _ = try genError() // TODO: this recovery is terrible } catch MSV.CarriesInt(let i) where i == genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} expected-error {{expected '{'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{58-58=do }} } } func postThrows() -> Int throws { // expected-error{{'throws' may only occur before '->'}}{{19-19=throws }}{{25-32=}} return 5 } func postThrows2() -> throws Int { // expected-error{{'throws' may only occur before '->'}}{{20-22=throws}}{{23-29=->}} return try postThrows() } func postRethrows(_ f: () throws -> Int) -> Int rethrows { // expected-error{{'rethrows' may only occur before '->'}}{{42-42=rethrows }}{{48-57=}} return try f() } func postRethrows2(_ f: () throws -> Int) -> rethrows Int { // expected-error{{'rethrows' may only occur before '->'}}{{43-45=rethrows}}{{46-54=->}} return try f() } func incompleteThrowType() { // FIXME: Bad recovery for incomplete function type. let _: () throws // expected-error @-1 {{consecutive statements on a line must be separated by ';'}} // expected-error @-2 {{expected expression}} } // rdar://21328447 func fixitThrow0() throw {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow1() throw -> Int {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow2() throws { var _: (Int) throw MSV.Foo var _: (Int) throw -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{16-21=throws}} }
apache-2.0
40d2e6ef1851f59eecd677bb779492c0
37.119718
306
0.654535
4.113222
false
false
false
false
nickdex/cosmos
code/graph_algorithms/test/matrix_transformation/test_matrix_transformation.swift
3
4520
// Part of Cosmos by OpenGenus Foundation import Foundation class TestMatrixTransformation { let mt = MatrixTransformation() var matrix: [[Int]] = [] let m0: [[Int]] = [] let m1 = [[1]] let m2 = [[1, 2], [3, 4]] let m4 = [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]] let m5 = [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] func test() { testRotate() testSquareTranspose() testSquareShear() } func testSquareShear() { let c2 = [[1, 2], [0, 1]], c4 = [[1, 0, 0, 0], [2, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], c5 = [[1, 0, 0, 0, 0], [2, 1, 2, 1, 0], [1, 0, 1, 2, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] let s2 = [[1, 4], [3,10]], s4 = [[ 5, 2, 3, 4], [17, 6, 7, 8], [29, 10, 11, 12], [41, 14, 15, 16]], s5 = [[ 8, 2, 7, 12, 5], [28, 7, 22, 32, 10], [48, 12, 37, 52, 15], [68, 17, 52, 72, 20], [88, 22, 67, 92, 25]] let ms = [m0, m1, m2, m4, m5], cs = [m0, m1, c2, c4, c5], ss = [m0, m1, s2, s4, s5] for i in 0..<ms.count { matrix = ms[i] mt.squareShearing(matrix: &matrix, coefficient: cs[i], init_value: 0, multiply: ({return $0 * $1}), add: ({return $0 + $1})) assert(same(matrix, ss[i])) } } func testSquareTranspose() { let s2 = [[1, 3], [2, 4]] let s4 = [[ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15], [ 4, 8, 12, 16]] let s5 = [[ 1, 6, 11, 16, 21], [ 2, 7, 12, 17, 22], [ 3, 8, 13, 18, 23], [ 4, 9, 14, 19, 24], [ 5, 10, 15, 20, 25]] let r2 = [[4, 2], [3, 1]] let r4 = [[16, 12, 8, 4], [15, 11, 7, 3], [14, 10, 6, 2], [13, 9, 5, 1]] let r5 = [[25, 20, 15, 10, 5], [24, 19, 14, 9, 4], [23, 18, 13, 8, 3], [22, 17, 12, 7, 2], [21, 16, 11, 6, 1]] let ms = [m0, m1, m2, m4, m5] // transpose of the matrices let ss = [m0, m1, s2, s4, s5] // reverse transpose of the matrices let rs = [m0, m1, r2, r4, r5] for i in 0..<ms.count { matrix = ms[i] mt.squareTranspose(&matrix) assert(same(matrix, ss[i])) } for i in 0..<ms.count { matrix = ms[i] mt.antiSquareTranspose(&matrix) assert(same(matrix, rs[i])) } } func testRotate() { let r2 = [[3, 1], [4, 2]] let r4 = [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] let r5 = [[21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10, 5]] let ms = [m0, m1, m2, m4, m5] // rotate of the matrices let rs = [m0, m1, r2, r4, r5] for i in 0..<ms.count { matrix = ms[i] mt.rotate(&matrix) assert(same(matrix, rs[i])) mt.reverseRotate(&matrix) assert(same(matrix, ms[i])) } } private func same(_ matrix1: [[Int]], _ matrix2: [[Int]]) -> Bool { if matrix1.count != matrix2.count { return false } for i in 0..<matrix1.count { if matrix1[i].count != matrix2[i].count { return false } for j in 0..<matrix1[i].count { if matrix1[i][j] != matrix2[i][j] { return false } } } return true } }
gpl-3.0
c5d38f937a1d472ab4039866c53029c8
26.560976
71
0.31792
3.203402
false
false
false
false
Darkhorse-Fraternity/EasyIOS-Swift
Pod/Classes/Extend/EUI/EUI+ScrollViewProperty.swift
1
3586
// // EUI+ScrollViewProperty.swift // medical // // Created by zhuchao on 15/5/2. // Copyright (c) 2015年 zhuchao. All rights reserved. // import Foundation class ScrollViewProperty:ViewProperty{ var contentInset = UIEdgeInsetsZero var contentOffset = CGPointZero var contentSize = CGSizeZero var scrollIndicatorInsets = UIEdgeInsetsZero var indicatorStyle:UIScrollViewIndicatorStyle = .Default var pullToRefresh:PullRefreshAction? var infiniteScrolling:InfiniteScrollingAction? override func view() -> UIScrollView{ var view = UIScrollView() view.tagProperty = self self.renderViewStyle(view) for subTag in self.subTags { view.addSubview(subTag.getView()) } return view } override func renderViewStyle(view: UIView) { super.renderViewStyle(view) var sview = view as! UIScrollView sview.contentInset = self.contentInset sview.contentOffset = self.contentOffset sview.contentSize = self.contentSize sview.scrollIndicatorInsets = self.scrollIndicatorInsets sview.indicatorStyle = self.indicatorStyle } override func renderTag(pelement:OGElement){ self.tagOut += ["content-offset","content-inset","content-size","scroll-indicator-insets","indicator-style","pull-to-refresh","infinite-scrolling"] super.renderTag(pelement) if let contentInset = EUIParse.string(pelement,key:"content-inset") { self.contentInset = UIEdgeInsetsFromString(contentInset) } if let contentOffset = EUIParse.string(pelement,key:"content-offset") { self.contentOffset = CGPointFromString(contentOffset) } if let contentSize = EUIParse.string(pelement,key:"content-size") { self.contentSize = CGSizeFromString(contentSize) } if let indicatorStyle = EUIParse.string(pelement,key:"indicator-style") { if indicatorStyle == "white" { self.indicatorStyle = .White }else if indicatorStyle == "Black"{ self.indicatorStyle = .Black } } if let scrollIndicatorInsets = EUIParse.string(pelement,key:"scroll-indicator-insets") { self.scrollIndicatorInsets = UIEdgeInsetsFromString(scrollIndicatorInsets) } if let thePullRefresh = EUIParse.string(pelement, key: "pull-to-refresh") { var values = thePullRefresh.trimArray if values.count == 1 { self.pullToRefresh = PullRefreshAction(selector: values[0]) }else if values.count == 2 { self.pullToRefresh = PullRefreshAction(selector: values[0], viewClass: values[1]) }else if values.count >= 3 { self.pullToRefresh = PullRefreshAction(selector: values[0], viewClass: values[1], target: values[2]) } } if let theInfiniteScrolling = EUIParse.string(pelement, key: "infinite-scrolling") { var values = theInfiniteScrolling.trimArray if values.count == 1 { self.infiniteScrolling = InfiniteScrollingAction(selector: values[0]) }else if values.count == 2 { self.infiniteScrolling = InfiniteScrollingAction(selector: values[0], viewClass: values[1]) }else if values.count >= 3 { self.infiniteScrolling = InfiniteScrollingAction(selector: values[0], viewClass: values[1], target: values[2]) } } } }
mit
af78f47d964fac71f2ec28985605e133
38.833333
155
0.637556
5.005587
false
false
false
false
USAssignmentWarehouse/EnglishNow
EnglishNow/Controller/HomeTimeline/DetailStatusVC.swift
1
25422
// // DetailStatusVC.swift // EnglishNow // // Created by Nha T.Tran on 6/18/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import UIKit import Firebase import FirebaseDatabase class DetailStatusVC: UIViewController , UITableViewDelegate, UITableViewDataSource{ //MARK: -declare var commentList: [Comment] = [Comment]() var status: Status? @IBOutlet var mainView: UIView! //MARK: -setup view let avatar: UIImageView = { let imageview = UIImageView() imageview.image = UIImage(named: ResourceName.avatarPlaceholder) imageview.translatesAutoresizingMaskIntoConstraints = false imageview.layer.cornerRadius = 16 imageview.layer.masksToBounds = true imageview.contentMode = .scaleAspectFill return imageview }() let photo: UIImageView = { let imageview = UIImageView() imageview.image = UIImage(named: ResourceName.avatarPlaceholder) imageview.translatesAutoresizingMaskIntoConstraints = false imageview.layer.cornerRadius = 16 imageview.layer.masksToBounds = true imageview.contentMode = .scaleAspectFill return imageview }() let btnComment: UIImageView = { let imageview = UIImageView() imageview.image = UIImage(named:"iconComment.png") imageview.translatesAutoresizingMaskIntoConstraints = false imageview.layer.masksToBounds = true imageview.contentMode = .scaleAspectFit return imageview }() let btnLike: UIImageView = { let imageview = UIImageView() imageview.image = UIImage(named:"like.png") imageview.translatesAutoresizingMaskIntoConstraints = false imageview.layer.masksToBounds = true imageview.contentMode = .scaleAspectFit return imageview }() let txtComment: UILabel = { let label = UILabel() label.text = "Comment" label.textAlignment = NSTextAlignment.left label.font = UIFont(name: "Georgia" , size: 16) label.translatesAutoresizingMaskIntoConstraints = false return label }() let txtLike: UILabel = { let label = UILabel() label.text = "like" label.textAlignment = NSTextAlignment.left label.font = UIFont(name: "Georgia" , size: 16) label.translatesAutoresizingMaskIntoConstraints = false return label }() let txtUserName: UILabel = { let label = UILabel() label.text = "username" label.textAlignment = NSTextAlignment.left label.font = UIFont(name:"Georgia-Bold", size: 18.0) label.translatesAutoresizingMaskIntoConstraints = false return label }() let txtTime: UILabel = { let label = UILabel() label.text = "" label.textAlignment = NSTextAlignment.left label.textColor = UIColor.lightGray label.font = UIFont(name: "Georgia" , size: 16) label.translatesAutoresizingMaskIntoConstraints = false return label }() let txtLikeNumber: UILabel = { let label = UILabel() label.text = "" label.textAlignment = NSTextAlignment.left label.font = UIFont(name: "Georgia" , size: 16) label.translatesAutoresizingMaskIntoConstraints = false return label }() let actionView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() let inputCommentView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() let txtContent: UILabel = { let label = UILabel() label.text = "" label.textAlignment = NSTextAlignment.left label.font = UIFont(name: "Georgia" , size: 17) label.translatesAutoresizingMaskIntoConstraints = false return label }() let txtInputComment: UITextField = { let txt = UITextField() txt.placeholder = "Enter your comment" txt.textAlignment = NSTextAlignment.left txt.font = UIFont(name: "Georgia" , size: 17) txt.translatesAutoresizingMaskIntoConstraints = false return txt }() let btnPostComment: UIButton = { let btn = UIButton() btn.setTitle("Post", for: .normal) btn.backgroundColor = UIColor(red: 30/255, green: 136/255, blue: 229/255, alpha: 1.0) btn.translatesAutoresizingMaskIntoConstraints = false return btn }() let commentTable: UITableView = { let table = UITableView() table.translatesAutoresizingMaskIntoConstraints = false return table }() var inputBigHeightAnchor: NSLayoutConstraint? var inputSmallHeightAnchor: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() if status != nil { initShow() } // Initialization code } //MARK: -init to show func initShow(){ avatar.layer.masksToBounds = true avatar.layer.cornerRadius = 10 mainView.addSubview(avatar) mainView.addSubview(txtUserName) mainView.addSubview(txtTime) mainView.addSubview(txtContent) mainView.addSubview(photo) mainView.addSubview(actionView) mainView.addSubview(txtLikeNumber) mainView.addSubview(inputCommentView) mainView.addSubview(commentTable) inputCommentView.addSubview(txtInputComment) inputCommentView.addSubview(btnPostComment) commentTable.delegate = self commentTable.dataSource = self commentTable.register(CommentCell.self, forCellReuseIdentifier: "Cell") actionView.addSubview(btnComment) actionView.addSubview(btnLike) actionView.addSubview(txtComment) actionView.addSubview(txtLike) avatar.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true avatar.topAnchor.constraint(equalTo: mainView.topAnchor, constant: -40).isActive = true avatar.widthAnchor.constraint(equalToConstant: 82).isActive = true avatar.heightAnchor.constraint(equalToConstant: 74).isActive = true txtUserName.topAnchor.constraint(equalTo: mainView.topAnchor, constant: -40).isActive = true txtUserName.leftAnchor.constraint(equalTo: avatar.rightAnchor, constant: 8).isActive = true txtUserName.heightAnchor.constraint(equalToConstant: 24).isActive = true txtUserName.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -8).isActive = true txtTime.topAnchor.constraint(equalTo: txtUserName.bottomAnchor, constant: 2).isActive = true txtTime.leftAnchor.constraint(equalTo: avatar.rightAnchor, constant: 8).isActive = true txtTime.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -8).isActive = true txtTime.heightAnchor.constraint(equalToConstant: 24).isActive = true txtContent.topAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 16).isActive = true txtContent.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true txtContent.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -8).isActive = true if status?.photo == nil { photo.heightAnchor.constraint(equalToConstant: 1).isActive = true photo.heightAnchor.constraint(equalToConstant: 150).isActive = false } else { photo.heightAnchor.constraint(equalToConstant: 150).isActive = true photo.heightAnchor.constraint(equalToConstant: 1).isActive = false } photo.topAnchor.constraint(equalTo: txtContent.bottomAnchor, constant: 8).isActive = true photo.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true photo.widthAnchor.constraint(equalToConstant: 200).isActive = true txtLikeNumber.topAnchor.constraint(equalTo: photo.bottomAnchor, constant: 16).isActive = true txtLikeNumber.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true txtLikeNumber.heightAnchor.constraint(equalToConstant: 24).isActive = true actionView.topAnchor.constraint(equalTo: txtLikeNumber.bottomAnchor, constant: 16).isActive = true actionView.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -16).isActive = true actionView.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true actionView.heightAnchor.constraint(equalToConstant: 40).isActive = true actionView.layer.borderWidth = 1 actionView.layer.borderColor = UIColor(red: 229/255, green: 232/255, blue: 232/255, alpha: 1.0).cgColor btnLike.topAnchor.constraint(equalTo: actionView.topAnchor, constant: 8).isActive = true btnLike.leftAnchor.constraint(equalTo: actionView.leftAnchor, constant: 32).isActive = true btnLike.widthAnchor.constraint(equalToConstant: 24).isActive = true btnLike.heightAnchor.constraint(equalToConstant: 24).isActive = true btnLike.bottomAnchor.constraint(equalTo: actionView.bottomAnchor, constant: -8).isActive = true txtLike.topAnchor.constraint(equalTo: actionView.topAnchor, constant: 8).isActive = true txtLike.leftAnchor.constraint(equalTo: btnLike.rightAnchor, constant: 4).isActive = true txtLike.widthAnchor.constraint(equalToConstant: 32).isActive = true txtLike.heightAnchor.constraint(equalToConstant: 32).isActive = true txtLike.bottomAnchor.constraint(equalTo: actionView.bottomAnchor, constant: -8).isActive = true btnComment.topAnchor.constraint(equalTo: actionView.topAnchor, constant: 8).isActive = true btnComment.rightAnchor.constraint(equalTo: txtComment.leftAnchor, constant: -4).isActive = true btnComment.heightAnchor.constraint(equalToConstant: 24).isActive = true btnComment.widthAnchor.constraint(equalToConstant: 24).isActive = true btnComment.bottomAnchor.constraint(equalTo: actionView.bottomAnchor, constant: -8).isActive = true txtComment.topAnchor.constraint(equalTo: actionView.topAnchor, constant: 8).isActive = true txtComment.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -56).isActive = true txtComment.heightAnchor.constraint(equalToConstant: 32).isActive = true txtComment.bottomAnchor.constraint(equalTo: actionView.bottomAnchor, constant: -8).isActive = true inputCommentView.topAnchor.constraint(equalTo: actionView.bottomAnchor, constant: 8).isActive = true inputCommentView.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true inputCommentView.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -16).isActive = true inputCommentView.layer.borderWidth = 1 inputCommentView.layer.borderColor = UIColor(red: 229/255, green: 232/255, blue: 232/255, alpha: 1.0).cgColor inputCommentView.heightAnchor.constraint(equalToConstant: 36).isActive = true txtInputComment.topAnchor.constraint(equalTo: inputCommentView.topAnchor).isActive = true txtInputComment.leftAnchor.constraint(equalTo: inputCommentView.leftAnchor).isActive = true txtInputComment.bottomAnchor.constraint(equalTo: inputCommentView.bottomAnchor).isActive = true txtInputComment.rightAnchor.constraint(equalTo: btnPostComment.leftAnchor).isActive = true btnPostComment.topAnchor.constraint(equalTo: inputCommentView.topAnchor ).isActive = true btnPostComment.rightAnchor.constraint(equalTo: inputCommentView.rightAnchor).isActive = true btnPostComment.bottomAnchor.constraint(equalTo: inputCommentView.bottomAnchor).isActive = true btnPostComment.widthAnchor.constraint(equalToConstant: 56).isActive = true commentTable.topAnchor.constraint(equalTo: inputCommentView.bottomAnchor, constant: 8).isActive = true commentTable.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 16).isActive = true commentTable.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -16).isActive = true commentTable.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: -8).isActive = true avatar.layer.masksToBounds = true avatar.layer.cornerRadius = 5 avatar.image = status?.avatar txtUserName.text = status?.username var milliseconds = status?.time let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds!)) let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy HH:mm:ss" formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale! txtTime.text = formatter.string(from: date as Date) txtContent.text = status?.content var likenumber:Int = (status?.likeNumber)! txtLikeNumber.text = "\(likenumber)" + " LIKES" photo.image = status?.photo if (status?.isUserLiked)! { btnLike.image = UIImage(named: "liked.png") } btnLike.isUserInteractionEnabled = true let likeTapRecognizer = UITapGestureRecognizer(target:self, action: #selector(tappedLikeImage)) btnLike.addGestureRecognizer(likeTapRecognizer) txtLike.isUserInteractionEnabled = true txtLike.addGestureRecognizer(likeTapRecognizer) btnComment.isUserInteractionEnabled = true let commentTapRecognizer = UITapGestureRecognizer(target:self, action: #selector(tappedCommentImage)) btnComment.addGestureRecognizer(commentTapRecognizer) txtComment.isUserInteractionEnabled = true txtComment.addGestureRecognizer(commentTapRecognizer) avatar.isUserInteractionEnabled = true let avatarTapRecognizer = UITapGestureRecognizer(target:self, action: #selector(tappedAvatarImage)) avatar.addGestureRecognizer(avatarTapRecognizer) self.mainView.isUserInteractionEnabled = true let mainViewTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap)) self.mainView.addGestureRecognizer(mainViewTapGesture) loadComment() onClickBtnLike() } //MARK: -tap event func handleTap(recognizer: UITapGestureRecognizer) { self.view.endEditing(true) } func tappedAvatarImage(gestureRecognizer: UIGestureRecognizer){ performSegue(withIdentifier: SegueIdentifier.SegueProfile, sender: self) } func onClickBtnLike (){ btnPostComment.addTarget(self, action: #selector(onPost), for: .touchUpInside) } func tappedCommentImage(gestureRecognizer: UIGestureRecognizer){ txtInputComment.becomeFirstResponder() } func tappedLikeImage(gestureRecognizer: UIGestureRecognizer){ if (status?.isUserLiked == false){ if let user = Auth.auth().currentUser{ Database.database().reference().child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(true) var likeNumber = (status?.likeNumber)! + 1 Database.database().reference().child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber) txtLikeNumber.text = "\(likeNumber)" + " LIKES" print("status?.user: \(status?.user)") print("status?.statusId: \(status?.statusId)") print("user.uid: \(user.uid)") Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(true) Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber) status?.isUserLiked = true status?.likeNumber = likeNumber btnLike.image = UIImage(named: "liked.png") //, for: UIControlState.normal) } } else { if let user = Auth.auth().currentUser{ Database.database().reference().child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(false) var likeNumber = (status?.likeNumber)! - 1 Database.database().reference().child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber) txtLikeNumber.text = "\(likeNumber)" + " LIKES" Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like").child(user.uid).setValue(false) Database.database().reference().child("user_profile").child((status?.user)!).child("status").child((status?.statusId)!).child("like_number").setValue(likeNumber) status?.isUserLiked = false status?.likeNumber = likeNumber btnLike.image = UIImage(named: "like.png") //, for: UIControlState.normal) } } } //MARK: -post event func onPost(btn: UIButton) { if (txtInputComment.text != ""){ if let user = Auth.auth().currentUser{ let queryRef = Database.database().reference().child("user_profile/\(user.uid)").observe(.value, with: { (snapshot) -> Void in if let dictionary = snapshot.value as? [String:Any] { let username = dictionary["username"] as? String ?? "" var useravatarUrl: String = "" var userAvatar:UIImage = UIImage(named: ResourceName.avatarPlaceholder)! if dictionary.index(forKey: "profile_pic") != nil { useravatarUrl = dictionary["profile_pic"] as! String if let imgUrl = URL(string: useravatarUrl as! String){ let data = try? Data(contentsOf: imgUrl) if let imageData = data { let profilePic = UIImage(data: data!) userAvatar = profilePic! } } } let ref = Database.database().reference().child("status").child((self.status?.statusId)!).child("comment").childByAutoId() ref.child("userId").setValue(user.uid) ref.child("username").setValue(username) ref.child("content").setValue(self.txtInputComment.text) ref.child("time").setValue(Date.timeIntervalBetween1970AndReferenceDate) self.txtInputComment.text = "" self.commentList.append(Comment(userId: user.uid, username: username,avatar: userAvatar,content:self.txtInputComment.text!, commentId: ref.key,time: Date.timeIntervalBetween1970AndReferenceDate)) self.commentTable.reloadData() } }) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.mainView.endEditing(true) } //MARK: -load data func loadComment(){ let ref = Database.database().reference().child("status").child((self.status?.statusId)!).observe(.value, with: { (snapshot) -> Void in let status = (snapshot as! DataSnapshot).value as! [String:AnyObject] if (status.index(forKey: "comment") != nil) { let comment = ((snapshot as! DataSnapshot).childSnapshot(forPath: "comment") as! DataSnapshot) self.commentList.removeAll() for item in comment.children { let dictionary = (item as! DataSnapshot).value as! [String:AnyObject] if dictionary.count == FirebaseUtils.numberChildComment { let userId = dictionary["userId"] as! String let username = dictionary["username"] as! String let content = dictionary["content"] as! String let time = dictionary["time"] as! TimeInterval let commentId = (item as! DataSnapshot).key as! String var userAvatar: UIImage = UIImage(named: ResourceName.avatarPlaceholder)! let queryRef = Database.database().reference().child("user_profile/\(userId)").observe(.value, with: { (snapshot) -> Void in if let dictionary = snapshot.value as? [String:Any] { if let url = dictionary["profile_pic"] { if let imgUrl = URL(string: url as! String){ let data = try? Data(contentsOf: imgUrl) if let imageData = data { let profilePic = UIImage(data: data!) userAvatar = profilePic! } } } } self.commentList.append(Comment(userId: userId, username: username,avatar: userAvatar,content:content, commentId: commentId,time: time)) self.commentTable.reloadData() }) } } } }) } //MARK: -table datasource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return commentList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath ) as! CommentCell let image = UIImageView() image.frame = CGRect(x: 4, y: 4, width: 36, height: 36) image.image = commentList[indexPath.row].avatar image.translatesAutoresizingMaskIntoConstraints = false let _txtUsername = UILabel() _txtUsername.text = "username" _txtUsername.frame = CGRect(x: 48, y: 4, width: cell.frame.width - 56 , height: 24) _txtUsername.textAlignment = NSTextAlignment.left _txtUsername.font = UIFont(name:"Georgia-Bold", size: 18.0) _txtUsername.text = commentList[indexPath.row].username let _txtComment = UILabel() _txtComment.text = "" _txtComment.textAlignment = NSTextAlignment.left _txtComment.sizeToFit() _txtComment.frame = CGRect(x: 48, y: 32, width: cell.frame.width - 56 , height: cell.frame.height - 40) _txtComment.font = UIFont(name: "Georgia" , size: 16) _txtComment.text = commentList[indexPath.row].content _txtComment.numberOfLines = 10 cell.addSubview(_txtComment) cell.addSubview(_txtUsername) cell.addSubview(image) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SegueProfile" { let des = segue.destination as! ProfileVC des.currentID = (status?.user)! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
98dc6da442e0205054eebdd7ea7029aa
40.67377
219
0.604343
5.621628
false
false
false
false
SPECURE/rmbt-ios-client
Sources/DNSRecordClass.swift
1
2106
/***************************************************************************************************** * Copyright 2014-2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation let DNS_RCODE_TABLE: [UInt8: String] = [ 0: "NOERROR", 1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", //4: "NOTIMPL", 5: "REFUSED", 6: "YXDOMAIN", 7: "YXRRSET", 8: "NXRRSET", 9: "NOTAUTH", 10: "NOTZONE", 16: "BADVERS", //16: "BADSIG", 17: "BADKEY", 18: "BADTIME", 19: "BADMODE" ] /// class DNSRecordClass: CustomStringConvertible { let name: String var qType: UInt16! var qClass: UInt16! var ttl: UInt32! let rcode: UInt8 // TODO: improve...use struct... /// var ipAddress: String? /// var mxPreference: UInt16? var mxExchange: String? // /// var description: String { if let addr = ipAddress { return addr } return "\(String(describing: ipAddress))" } // /// init(name: String, qType: UInt16, qClass: UInt16, ttl: UInt32, rcode: UInt8) { self.name = name self.qType = qType self.qClass = qClass self.ttl = ttl self.rcode = rcode } /// init(name: String, rcode: UInt8) { self.name = name self.rcode = rcode } /// func rcodeString() -> String { return DNS_RCODE_TABLE[rcode] ?? "UNKNOWN" // ! } }
apache-2.0
388ec317b6a16c4f114693d578f29567
22.4
103
0.531339
3.95122
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Source/RxSwift/repeatWithBehavior.swift
1
3358
// // repeatWithBehavior.swift // RxSwiftExt // // Created by Marin Todorov on 05/08/2017. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift public typealias RepeatPredicate = () -> Bool /* Uses RepeatBehavior defined in retryWithBehavior */ /** Dummy error to use with catchError to restart the observable */ private enum RepeatError: Error { case catchable } extension ObservableType { /** Repeats the source observable sequence using given behavior when it completes - parameter behavior: Behavior that will be used when the observable completes - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRepeat: Custom optional closure for decided whether the observable should repeat another round - returns: Observable sequence that will be automatically repeat when it completes */ public func repeatWithBehavior(_ behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRepeat: RepeatPredicate? = nil) -> Observable<Element> { return repeatWithBehavior(1, behavior: behavior, scheduler: scheduler, shouldRepeat: shouldRepeat) } /** Repeats the source observable sequence using given behavior when it completes - parameter currentRepeat: Number of the current repetition - parameter behavior: Behavior that will be used in case of completion - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRepeat: Custom optional closure for decided whether the observable should repeat another round - returns: Observable sequence that will be automatically repeat when it completes */ internal func repeatWithBehavior(_ currentRepeat: UInt, behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRepeat: RepeatPredicate? = nil) -> Observable<Element> { guard currentRepeat > 0 else { return Observable.empty() } // calculate conditions for bahavior let conditions = behavior.calculateConditions(currentRepeat) return concat(Observable.error(RepeatError.catchable)) .catch { error in //if observable errors, forward the error guard error is RepeatError else { return Observable.error(error) } //repeat guard conditions.maxCount > currentRepeat else { return Observable.empty() } if let shouldRepeat = shouldRepeat, !shouldRepeat() { // also return error if predicate says so return Observable.empty() } guard conditions.delay != .never else { // if there is no delay, simply retry return self.repeatWithBehavior(currentRepeat + 1, behavior: behavior, scheduler: scheduler, shouldRepeat: shouldRepeat) } // otherwise retry after specified delay return Observable<Void>.just(()).delaySubscription(conditions.delay, scheduler: scheduler).flatMapLatest { self.repeatWithBehavior(currentRepeat + 1, behavior: behavior, scheduler: scheduler, shouldRepeat: shouldRepeat) } } } }
mit
1780ef12ef1a7e1a5590e6b07f70451d
42.597403
173
0.685136
5.414516
false
false
false
false
ocrickard/Theodolite
Theodolite/View/Reuse/ViewPool.swift
1
2224
// // ViewPool.swift // components-swift // // Created by Oliver Rickard on 10/9/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import UIKit /** Internal view pool. Holds a list of views that Theodolite has constructed, and is responsible for keeping track of which views are vended out of its list, and is responsible for hiding any views that haven't been vended in any particular mount cycle. */ public class ViewPool: Hashable, Equatable { private struct View { let view: UIView var identifier: ScopeIdentifier } private var views: [View] = [] func reset() { for view in views { if !view.view.isHidden { view.view.isHidden = true } } } func checkoutView(component: Component, parent: UIView, config: ViewConfiguration) -> UIView? { let applyView = { (view: UIView) -> UIView in if view.isHidden { view.isHidden = false } config.applyToView(v: view) return view } let scopeHandleIdentifier = getIdentifier(component: component) // First search for a view that exactly matches this component, if we can find one. This is to avoid re-shuffling // views unless we absolutely have to if the component was previously mounted. for i in 0 ..< views.count { let v = views[i] if scopeHandleIdentifier == v.identifier { views.remove(at: i) return applyView(v.view) } } if let view = views.first { views.removeFirst() return applyView(view.view) } let newView = config.buildView() parent.addSubview(newView) return newView } func checkinView(component: Component, view: UIView) { views.append(View(view: view, identifier: getIdentifier(component: component))) if views.count > 100 { print("View pool is too big for the linear algorithms.") } } func getIdentifier(component: Component) -> ScopeIdentifier { return getScopeHandle(component: component)?.identifier ?? ScopeIdentifier(path:[]) } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } static public func ==(lhs: ViewPool, rhs: ViewPool) -> Bool { return lhs === rhs } }
mit
c23f8876aa5b114b70ec3525b0d9fd02
26.7875
117
0.665767
4.15514
false
false
false
false
qkrqjadn/BWTVController
BWTVController/Classes/BWTVController.swift
1
4317
//Copyright (c) 2017 qkrqjadn <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit open class BWTVController: UITableViewController { //MARK: - Delegate & DataSource open var headerView: BWTVHeaderView? open var headerViews: [BWTVHeaderView]? //MARK: - Property open var heightForRowAt: CGFloat? open var heightForHeaderInSection: CGFloat? open var tableViewEventType: UITableViewRowAnimation = .fade open var isTopSectionDisplay: Bool = true var delegate: BWTVControllerDelegate? var dataSource: BWTVControllerDataSource? //MARK: - Init override open func viewDidLoad() { super.viewDidLoad() print(isTopSectionDisplay) } //MARK: - Header Tap Action open func tapCellAction(_ sender: UITapGestureRecognizer){ if let tapHeaderView = sender.view as? BWTVHeaderView{ switch tapHeaderView.expandState { case .reduce: tapHeaderView.expandState = expandType.expand case .expand: tapHeaderView.expandState = expandType.reduce default: break } self.tableView.reloadSections(IndexSet(integer: tapHeaderView.tag), with: tableViewEventType) } } } //MARK: - TableViewDelegate extension BWTVController { open override func numberOfSections(in tableView: UITableView) -> Int { return headerViews?.count ?? 0 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let expandStateCheck: expandType = headerViews?[section].expandState ?? .reduce return expandStateCheck == .reduce ? 0 : headerViews?[section].childRows ?? 0 } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return self.delegate?.tableView(tableView, cellForRowAt: indexPath) ?? UITableViewCell() } override open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = headerViews?[section] headerView?.tag = section let tap = UITapGestureRecognizer(target: self, action: #selector(tapCellAction(_:))) headerView?.isUserInteractionEnabled = true headerView?.addGestureRecognizer(tap) return headerView } } //MARK: - TableViewDataSource extension BWTVController{ override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if self.dataSource == nil { return self.heightForRowAt ?? 0 } return dataSource?.tableView(tableView, heightForRowAt: indexPath) ?? 0 } override open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if self.dataSource == nil { if isTopSectionDisplay == false && section == 0 { return 0 } else { return self.heightForHeaderInSection ?? 0 } } return dataSource?.tableView(tableView, heightForHeaderInSection: section) ?? 0 } }
mit
afc3440677c91d58f935e20cd0431d11
34.385246
114
0.672458
5.316502
false
false
false
false
dataich/TypetalkSwift
TypetalkSwift/Requests/PostInviteTopicMembers.swift
1
1093
// // PostInviteTopicMembers.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire // sourcery: AutoInit public struct PostInviteTopicMembers: Request { public let topicId: Int public let inviteMembers:[String]? public let inviteMessage:String? public typealias Response = PostInviteTopicMembersResponse public var method: HTTPMethod { return .post } public var path: String { return "/topics/\(topicId)/members/invite" } public var parameters: Parameters? { var parameters: Parameters = [:] parameters["inviteMembers"] = self.inviteMembers parameters["inviteMessage"] = self.inviteMessage return parameters } // sourcery:inline:auto:PostInviteTopicMembers.AutoInit public init(topicId: Int, inviteMembers: [String]?, inviteMessage: String?) { self.topicId = topicId self.inviteMembers = inviteMembers self.inviteMessage = inviteMessage } // sourcery:end } public typealias PostInviteTopicMembersResponse = TopicWithInfo
mit
13cb20b8b61813c691e5a367741aff42
25
79
0.731685
4.350598
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
MemorizeItForever/MemorizeItForever/ViewControllers/Depot/TemporaryPhraseListViewController.swift
1
4674
// // TemporaryPhraseListViewController.swift // MemorizeItForever // // Created by Hadi Zamani on 11/1/19. // Copyright © 2019 SomeSimpleSolutions. All rights reserved. // import UIKit import MemorizeItForeverCore class TemporaryPhraseListViewController: UIViewController { // MARK: Fields private let segueIdentifier = "ShowEditTemporaryPhrase" var recognizedTexts = [String]() var dataSource: DepotTableDataSourceProtocol! var service: DepotPhraseServiceProtocol! // MARK: ViewController override func viewDidLoad() { super.viewDidLoad() initializeViewController() NotificationCenter.default.addObserver(self, selector: #selector(Self.reloadData), notificationNameEnum: NotificationEnum.temporaryPhraseList, object: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueIdentifier{ if let nc = segue.destination as? UINavigationController, nc.childViewControllers.count > 0, let vc = nc.childViewControllers[0] as? EditTemporaryPhraseViewController{ vc.phrase = sender as? String } } } // MARK: Private Methods private func initializeViewController(){ tableView.dataSource = dataSource tableView.delegate = dataSource setDataSourceProperties() addAll.title = NSLocalizedString("AddAll", comment: "Add all phrases") cancel.title = NSLocalizedString("Cancel", comment: "Dismiss view controller") addAll.tintColor = ColorPicker.backgroundView cancel.tintColor = ColorPicker.backgroundView } private func setDataSourceProperties(){ setDataSourceModel() dataSource.rowActionHandler = rowActionHandler } private func setDataSourceModel(){ var temporaryPhraseModelList = [TemporaryPhraseModel]() for item in recognizedTexts { temporaryPhraseModelList.append(TemporaryPhraseModel(phrase: item)) } dataSource.setModels(temporaryPhraseModelList) } private func rowActionHandler(model: MemorizeItModelProtocol, action: TableRowAction) { switch action { case .add: addModel(model) break case .edit: presentEditTemporaryPhraseViewController(model: model) break case .delete: deleteModel(model) break } } private func deleteModel(_ model: MemorizeItModelProtocol) { guard let tmpPhrase = model as? TemporaryPhraseModel else { return } if let index = recognizedTexts.index(of: tmpPhrase.phrase) { recognizedTexts.remove(at: index) } } private func presentEditTemporaryPhraseViewController(model: MemorizeItModelProtocol){ guard let tmpPhrase = model as? TemporaryPhraseModel else { return } performSegue(withIdentifier: "ShowEditTemporaryPhrase", sender: tmpPhrase.phrase) } private func addModel(_ model: MemorizeItModelProtocol) { guard let tmpPhrase = model as? TemporaryPhraseModel else { return } service.save(tmpPhrase.phrase) if let index = recognizedTexts.index(of: tmpPhrase.phrase) { recognizedTexts.remove(at: index) } } private func addAllPhrases() { service.save(recognizedTexts) dismissViewController() } private func dismissViewController() { self.dismiss(animated: true, completion: nil) NotificationCenter.default.post(.depotList, object: nil) } @objc private func reloadData(notification: NSNotification) { guard let wrapper = notification.object as? Wrapper<Any>, let dict = wrapper.getValue() as? Dictionary<TempPhrase, String?> else { return } if let original = dict[TempPhrase.original] as? String, let index = recognizedTexts.index(of: original) { recognizedTexts[index] = dict[TempPhrase.edited] as? String ?? "!!!!" setDataSourceModel() tableView.reloadData() } } // MARK: Controls @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addAll: UIBarButtonItem! @IBAction func addAllTexts(_ sender: Any) { addAllPhrases() } @IBOutlet weak var cancel: UIBarButtonItem! @IBAction func cancelAction(_ sender: Any) { dismissViewController() } } public struct TemporaryPhraseModel: MemorizeItModelProtocol{ var phrase: String }
mit
a7737ef04f915bcff4420d9d582f9973
32.378571
180
0.653114
5.446387
false
false
false
false
NGeenLibraries/NGeen
Example/App/Model/Hero/Hero.swift
1
1696
// // Hero.swift // Copyright (c) 2014 NGeen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class Hero: Model { var id: Int = 0 var name: String = "" var bio: String = "" override var description: String { set { self.bio = newValue } get { return self.bio } } var modified: NSDate = NSDate() var resourceURI: String = "" var urls: [AnyObject] = Array() var thumbnail: [String: AnyObject] = Dictionary() var comics: Comic? var stories: Story? var events: Event? var series: Serie? //MARK: Constructor required init () {} }
mit
8b7b938862ad4dbade23f3d8c49218fe
32.254902
80
0.683962
4.428198
false
false
false
false
DDSSwiftTech/SwiftGtk
Sources/Common.swift
2
1014
// // Copyright © 2016 Tomas Linhart. All rights reserved. // import CGtk extension gboolean { func toBool() -> Bool { return self >= 1 } } extension Bool { func toGBoolean() -> gboolean { return self ? 1 : 0 } } extension Int { func toBool() -> Bool { return self >= 1 } } extension UnsafeMutablePointer { func cast<T>() -> UnsafeMutablePointer<T> { let pointer = UnsafeRawPointer(self).bindMemory(to: T.self, capacity: 1) return UnsafeMutablePointer<T>(mutating: pointer) } } extension UnsafeRawPointer { func cast<T>() -> UnsafeMutablePointer<T> { let pointer = UnsafeRawPointer(self).bindMemory(to: T.self, capacity: 1) return UnsafeMutablePointer<T>(mutating: pointer) } } extension UnsafeMutableRawPointer { func cast<T>() -> UnsafeMutablePointer<T> { let pointer = UnsafeRawPointer(self).bindMemory(to: T.self, capacity: 1) return UnsafeMutablePointer<T>(mutating: pointer) } }
mit
301ff85924df1c9c8b938afac63694a3
22.022727
80
0.639684
4.134694
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/TimeSignature.swift
1
3268
// // TimeSignature.swift // denm_view // // Created by James Bean on 10/6/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class TimeSignature: ViewNode, BuildPattern { public var measure: MeasureView? public var numeratorLayer: TextLayerConstrainedByHeight? public var denominatorLayer: TextLayerConstrainedByHeight? public var numerator: String = "" public var denominator: String = "" // perhaps make string to include: ?/16 or Δ/32 public var x: CGFloat = 0 public var height: CGFloat = 0 private var pad_between: CGFloat { get { return 0.0618 * height } } private var numberHeight: CGFloat { get { return (height - pad_between) / 2 } } public var hasBeenBuilt: Bool = false public init(numerator: Int, denominator: Int, x: CGFloat, top: CGFloat, height: CGFloat) { self.numerator = "\(numerator)" self.denominator = "\(denominator)" self.x = x self.height = height super.init() self.top = top build() } override init() { super.init() layoutFlow_horizontal = .Center setsWidthWithContents = true // override } public override init(layer: AnyObject) { super.init(layer: layer) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func build() { addNumeratorLayer() addDenominatorLayer() setFrame() flowHorizontally() hasBeenBuilt = true } private func addNumeratorLayer() { numeratorLayer = TextLayerConstrainedByHeight( text: numerator, x: 0, top: 0, height: numberHeight, alignment: .Center, fontName: "Baskerville-SemiBold" ) numeratorLayer?.foregroundColor = UIColor.brownColor().CGColor addSublayer(numeratorLayer!) } private func addDenominatorLayer() { denominatorLayer = TextLayerConstrainedByHeight( text: denominator, x: 0, top: numberHeight + pad_between, height: numberHeight, alignment: .Center, fontName: "Baskerville-SemiBold" ) denominatorLayer?.foregroundColor = UIColor.brownColor().CGColor addSublayer(denominatorLayer!) } private func setFrame() { setWidthWithContents() frame = CGRectMake(x - 0.5 * frame.width, top, frame.width, height) } override func setWidthWithContents() { let maxWidth: CGFloat = numeratorLayer!.frame.width > denominatorLayer!.frame.width ? numeratorLayer!.frame.width : denominatorLayer!.frame.width frame = CGRectMake(frame.minX, frame.minY, maxWidth, frame.height) } override func flowHorizontally() { numeratorLayer!.position.x = 0.5 * frame.width denominatorLayer!.position.x = 0.5 * frame.width } public override func hitTest(p: CGPoint) -> CALayer? { if containsPoint(p) { return self } else { return nil } } public override func containsPoint(p: CGPoint) -> Bool { return CGRectContainsPoint(frame, p) } }
gpl-2.0
178a7f7f2036e434770c7016f0ad506c
29.820755
94
0.612676
4.774854
false
false
false
false
DrabWeb/Azusa
Azusa.Previous/Azusa/Views/Music Player/AZQueueTableView.swift
1
4085
// // AZQueueTableView.swift // Azusa // // Created by Ushio on 12/12/16. // import Cocoa /// The `NSTableView` subclass for queue views class AZQueueTableView: NSTableView { // MARK: - Variables /// The closure to call when the user either double clicks or presses enter on this table view, normally plays the clicked track /// /// Passed this table view, the selected songs and the event var primaryHandler : ((AZQueueTableView, [AZSong], NSEvent) -> ())? = nil; /// The closure to call when the user either right clicks on this table view, normally shows a context menu /// /// Passed this table view, the selected songs and the event var secondaryHandler : ((AZQueueTableView, [AZSong], NSEvent) -> ())? = nil; /// The closure to call when the user selects songs and presses backspace/delete, should remove the selected songs from the queue /// /// Passed this table view, the selected songs and the event var removeHandler : ((AZQueueTableView, [AZSong], NSEvent) -> ())? = nil; // MARK: - Functions override func rightMouseDown(with event: NSEvent) { /// The index of the row that was clicked let row : Int = self.row(at: self.convert(event.locationInWindow, from: nil)); // If there was any row under the mouse... if(row != -1) { // If the row that was under the mouse isn't selected... if(!self.selectedRowIndexes.contains(row)) { // Deselect all the other rows and only select the one under the mouse self.deselectAll(self); self.selectRowIndexes(IndexSet([row]), byExtendingSelection: false); } } // Call `secondaryHandler` self.secondaryHandler?(self, self.getSelectedSongs(), event); } override func mouseDown(with event: NSEvent) { super.mouseDown(with: event); /// The index of the row that was clicked let row : Int = self.row(at: self.convert(event.locationInWindow, from: nil)); // If the user double clicked... if(event.clickCount >= 2) { // If `row` is valid... if(row != -1) { // Only select the clicked row self.selectRowIndexes(IndexSet([row]), byExtendingSelection: false); } // Call `primaryHandler` self.primaryHandler?(self, self.getSelectedSongs(), event); } } override func keyDown(with event: NSEvent) { // Switch on the keycode and act accordingly switch(event.keyCode) { // Enter case 36, 76: // Make sure if there are multiple selection to only select the first one self.selectRowIndexes(IndexSet([self.selectedRowIndexes.first ?? -1]), byExtendingSelection: false); self.primaryHandler?(self, self.getSelectedSongs(), event); break; // Backspace/delete case 51, 117: self.removeHandler?(self, self.getSelectedSongs(), event); break; default: super.keyDown(with: event); break; } } /// Gets all the selected `AZSong`s in this table view and returns them /// /// - Returns: All the `AZSong`s selected in this table view func getSelectedSongs() -> [AZSong] { /// The songs to return var songs : [AZSong] = []; // For every selected row index... for(_, currentRowIndex) in self.selectedRowIndexes.enumerated() { // Add `representedSong` of the `AZQueueTableCellView` of this row to `songs` if let rowView = self.rowView(atRow: currentRowIndex, makeIfNecessary: false) { songs.append((rowView.view(atColumn: 0) as! AZQueueTableCellView).representedSong!); } } // Return `songs` return songs; } }
gpl-3.0
cb742478a59d3719dc8f0af4cc353727
36.136364
133
0.576744
4.915764
false
false
false
false
nasust/LeafViewer
LeafViewer/classes/ViewMode/AutomaticZoomCalculationViewSize.swift
1
2392
// // Created by hideki on 2017/06/22. // Copyright (c) 2017 hideki. All rights reserved. // import Foundation import Cocoa class AutomaticZoomCalculationViewSize : CalculationViewSize { static func calculateTargetImageSize(window: NSWindow, image: NSImage) -> NSSize{ let margin: CGFloat = window.styleMask.contains(NSWindow.StyleMask.fullScreen) ? 0 : 30 var targetSize = NSMakeSize(0, 0) let windowVisibleFrame = NSScreen.main!.visibleFrame; //todo current screen let headerHeight = window.frame.size.height - window.contentView!.frame.size.height NSLog("header height: %f", headerHeight) var targetImageViewWidth: CGFloat = image.size.width var targetImageViewHeight: CGFloat = image.size.height if image.size.width > (image.size.height + headerHeight) { let coefficient = windowVisibleFrame.size.width / image.size.width targetImageViewWidth = image.size.width * coefficient targetImageViewHeight = image.size.height * coefficient if targetImageViewHeight + headerHeight + margin > windowVisibleFrame.size.height { let contentHeight = (windowVisibleFrame.size.height - headerHeight - margin) let coefficient = contentHeight / targetImageViewHeight targetImageViewWidth = targetImageViewWidth * coefficient targetImageViewHeight = targetImageViewHeight * coefficient } } else { let contentHeight = (windowVisibleFrame.size.height - headerHeight - margin) let coefficient = contentHeight / image.size.height NSLog("contentHeight: %f" , contentHeight ) targetImageViewWidth = image.size.width * coefficient targetImageViewHeight = image.size.height * coefficient if targetImageViewWidth > windowVisibleFrame.size.width { let coefficient = windowVisibleFrame.size.width / targetImageViewWidth targetImageViewWidth = targetImageViewWidth * coefficient targetImageViewHeight = targetImageViewHeight * coefficient } } targetSize.width = targetImageViewWidth targetSize.height = targetImageViewHeight NSLog("targetSize: %f , %f" , targetSize.width , targetSize.height) return targetSize } }
gpl-3.0
bf11e2e64bfc94f55f49e62b06bff1d2
36.375
95
0.673077
5.834146
false
false
false
false
yanif/circator
MetabolicCompass/NutritionManager/ViewController/MealBuilderViewController.swift
1
3454
// // MealBuilderViewController.swift // MetabolicCompassNutritionManager // // Created by Edwin L. Whitman on 8/2/16. // Copyright © 2016 Edwin L. Whitman. All rights reserved. // import UIKit class MealBuilderViewController : UIViewController, ConfigurableStatusBar { let addFoodItemViewController = AddFoodItemViewController() let mealBuilderView = MealBuilderView() var meal : Meal = Meal() override func viewDidLoad() { super.viewDidLoad() self.configureView() } private func configureView() { self.view.backgroundColor = UIColor.blackColor() self.mealBuilderView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.mealBuilderView) let mealBuilderViewConstraints : [NSLayoutConstraint] = [ self.mealBuilderView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor), self.mealBuilderView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor), self.mealBuilderView.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor), self.mealBuilderView.heightAnchor.constraintEqualToConstant(UIScreen.mainScreen().bounds.height * (1/7)) ] self.view.addConstraints(mealBuilderViewConstraints) //lays out builder view such that its exact height can be referenced in next layout self.view.layoutIfNeeded() self.addChildViewController(self.addFoodItemViewController) let addFoodItemView = self.addFoodItemViewController.view addFoodItemView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(addFoodItemView) let addFoodItemViewConstraints : [NSLayoutConstraint] = [ addFoodItemView.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor), addFoodItemView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor), addFoodItemView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor), addFoodItemView.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -self.mealBuilderView.bounds.height) ] self.view.addConstraints(addFoodItemViewConstraints) let statusBarBacking = UIView(frame: UIApplication.sharedApplication().statusBarFrame) statusBarBacking.backgroundColor = UIColor.whiteColor() self.view.addSubview(statusBarBacking) self.view.bringSubviewToFront(self.mealBuilderView) self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MealBuilderViewController.untoggleBuilderView(_:)))) } func untoggleBuilderView(sender: AnyObject) { if self.mealBuilderView.isToggled { self.mealBuilderView.didToggleView() } } //status bar animation add-on var showStatusBar = true override func prefersStatusBarHidden() -> Bool { return !self.showStatusBar } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Slide } func showStatusBar(enabled: Bool) { self.showStatusBar = enabled UIView.animateWithDuration(0.5, animations: { self.setNeedsStatusBarAppearanceUpdate() }) } }
apache-2.0
9f36e29aaee85058085170ec4dfc8d56
34.96875
146
0.686649
6.079225
false
false
false
false
a497500306/yijia_kuanjia
医家/医家/主项目/MLTableViewController/MLTableViewController.swift
1
3010
// // MLTableViewController.swift // 医家 // // Created by 洛耳 on 15/12/15. // Copyright © 2015年 workorz. All rights reserved. // import UIKit class MLTableViewController: UITableViewController { var sideslipView = MLSideslipView() override func viewDidLoad() { super.viewDidLoad() //覆盖全屏的View,用来做侧滑栏 let p:MLSideslipView = MLSideslipView() self.sideslipView = p self.view.window?.addSubview(p) //添加View作为手势响应,放在Controller最下面,所以不影响其他手势执行 let s:UIView = UIView(frame: self.view.bounds) self.tableView.addSubview(s) s.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "dragCenterView:")) } //MARK: - 侧滑 // 用x来判断,用transform来控制 func dragCenterView(pan:UIPanGestureRecognizer){ let point = pan.translationInView(pan.view) if pan.state == UIGestureRecognizerState.Cancelled || pan.state == UIGestureRecognizerState.Ended{ if self.sideslipView.frame.origin.x > 0 - UIScreen.mainScreen().bounds.width / 3 { UIView.animateWithDuration(0.2, animations: { () -> Void in self.sideslipView.frame = CGRectMake( 0, 0, UIScreen.mainScreen().bounds.width + (UIScreen.mainScreen().bounds.width * 2 / 3), UIScreen.mainScreen().bounds.height) self.sideslipView.toolbar.alpha = 0.5 self.sideslipView.userInteractionEnabled = true self.sideslipView.toolbar.userInteractionEnabled = true }) }else{ UIView.animateWithDuration(0.2, animations: { () -> Void in self.sideslipView.frame = CGRectMake( 0 - (UIScreen.mainScreen().bounds.width * 2 / 3), 0, UIScreen.mainScreen().bounds.width + (UIScreen.mainScreen().bounds.width * 2 / 3), UIScreen.mainScreen().bounds.height) self.sideslipView.toolbar.alpha = 0 self.sideslipView.userInteractionEnabled = false self.sideslipView.toolbar.userInteractionEnabled = false }) } }else{ self.sideslipView.userInteractionEnabled = false self.sideslipView.toolbar.userInteractionEnabled = false self.sideslipView.frame.origin = CGPointMake(self.sideslipView.frame.origin.x + point.x, 0) let f = (((0 - (UIScreen.mainScreen().bounds.width * 2 / 3)) - self.sideslipView.frame.origin.x) / (0 - (UIScreen.mainScreen().bounds.width * 2 / 3)) * 0.5) self.sideslipView.toolbar.alpha = f pan.setTranslation(CGPoint.zero, inView: self.sideslipView) if (self.sideslipView.frame.origin.x >= 0) { self.sideslipView.frame = CGRectMake( 0, 0, UIScreen.mainScreen().bounds.width + (UIScreen.mainScreen().bounds.width * 2 / 3), UIScreen.mainScreen().bounds.height) } } } //MARK: - }
apache-2.0
694961fba00792fd9f22deca57e7269d
50
230
0.628827
4.424658
false
false
false
false
jwalsh/mal
swift3/Sources/step4_if_fn_do/main.swift
3
4001
import Foundation // read func READ(str: String) throws -> MalVal { return try read_str(str) } // eval func eval_ast(ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalSymbol: return try env.get(ast) case MalVal.MalList(let lst, _): return list(try lst.map { try EVAL($0, env) }) case MalVal.MalVector(let lst, _): return vector(try lst.map { try EVAL($0, env) }) case MalVal.MalHashMap(let dict, _): var new_dict = Dictionary<String,MalVal>() for (k,v) in dict { new_dict[k] = try EVAL(v, env) } return hash_map(new_dict) default: return ast } } func EVAL(ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalList(let lst, _): if lst.count == 0 { return ast } default: return try eval_ast(ast, env) } switch ast { case MalVal.MalList(let lst, _): switch lst[0] { case MalVal.MalSymbol("def!"): return try env.set(lst[1], try EVAL(lst[2], env)) case MalVal.MalSymbol("let*"): let let_env = try Env(env) var binds = Array<MalVal>() switch lst[1] { case MalVal.MalList(let l, _): binds = l case MalVal.MalVector(let l, _): binds = l default: throw MalError.General(msg: "Invalid let* bindings") } var idx = binds.startIndex while idx < binds.endIndex { let v = try EVAL(binds[idx.successor()], let_env) try let_env.set(binds[idx], v) idx = idx.successor().successor() } return try EVAL(lst[2], let_env) case MalVal.MalSymbol("do"): let slc = lst[lst.startIndex.successor()..<lst.endIndex] switch try eval_ast(list(Array(slc)), env) { case MalVal.MalList(let elst, _): return elst[elst.endIndex.predecessor()] default: throw MalError.General(msg: "Invalid do form") } case MalVal.MalSymbol("if"): switch try EVAL(lst[1], env) { case MalVal.MalFalse, MalVal.MalNil: if lst.count > 3 { return try EVAL(lst[3], env) } else { return MalVal.MalNil } default: return try EVAL(lst[2], env) } case MalVal.MalSymbol("fn*"): return malfunc( { return try EVAL(lst[2], Env(env, binds: lst[1], exprs: list($0))) }) default: switch try eval_ast(ast, env) { case MalVal.MalList(let elst, _): switch elst[0] { case MalVal.MalFunc(let fn,_,_,_,_,_): let args = Array(elst[1..<elst.count]) return try fn(args) default: throw MalError.General(msg: "Cannot apply on '\(elst[0])'") } default: throw MalError.General(msg: "Invalid apply") } } default: throw MalError.General(msg: "Invalid apply") } } // print func PRINT(exp: MalVal) -> String { return pr_str(exp, true) } // repl func rep(str:String) throws -> String { return PRINT(try EVAL(try READ(str), repl_env)) } var repl_env: Env = try Env() // core.swift: defined using Swift for (k, fn) in core_ns { try repl_env.set(MalVal.MalSymbol(k), malfunc(fn)) } // core.mal: defined using the language itself try rep("(def! not (fn* (a) (if a false true)))") while true { print("user> ", terminator: "") let line = readLine(stripNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } catch (MalError.General(let msg)) { print("Error: \(msg)") } }
mpl-2.0
cf0ecfc5ff7763b2ba94f344e8af5564
29.776923
79
0.513872
3.957468
false
false
false
false
ytfhqqu/iCC98
iCC98/iCC98/SettingsTableViewController.swift
1
3692
// // SettingsTableViewController.swift // iCC98 // // Created by Duo Xu on 5/7/17. // Copyright © 2017 Duo Xu. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class SettingsTableViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var showTailSwitch: UISwitch! @IBOutlet weak var tailCodeTextField: UITextField! // MARK: - UI // 更新 UI private func updateUI() { // 从 UserDefaults.standard 读取设置,并呈现到 UI showTailSwitch.isOn = Settings.showTail tailCodeTextField.text = Settings.tailCode } // MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() // 把控制器设置为文本框的委托 tailCodeTextField.delegate = self // 更新 UI updateUI() } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 按下特定的单元格会触发操作 if indexPath.section == 1 { // 第二节是“恢复默认”单元格 // 创建并展示一个上拉菜单(iPhone)或弹框(iPad) let alertControllerStyle: UIAlertControllerStyle switch UIDevice.current.userInterfaceIdiom { case .phone: alertControllerStyle = .actionSheet default: alertControllerStyle = .alert } let alertController = UIAlertController(title: nil, message: "确定恢复到默认设置吗?", preferredStyle: alertControllerStyle) let cancelAction = UIAlertAction(title: "取消", style: .cancel) let destroyAction = UIAlertAction(title: "恢复默认", style: .destructive) { [weak self] action in // 选择“恢复默认”后的操作 Settings.restoreDefaults() // 更新 UI self?.updateUI() } alertController.addAction(cancelAction) alertController.addAction(destroyAction) self.present(alertController, animated: true) // 单元格恢复为未选中的状态 tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Action @IBAction func toggleShowTailSwitch(_ sender: UISwitch) { Settings.showTail = showTailSwitch.isOn } // MARK: - Text field delegate func textFieldDidEndEditing(_ textField: UITextField) { Settings.tailCode = tailCodeTextField.text } }
mit
24bcccc6604827ff71c7683415bf9ea2
36.236559
125
0.650014
4.809722
false
false
false
false
stevewight/DuoKit
DuoKit/DuoSkill.swift
1
1598
// // DuoSkill.swift // Linguist // // Created by Steve on 10/30/16. // Copyright © 2016 31Labs. All rights reserved. // import UIKit public class DuoSkill: NSObject { public var languageString = "" public var iconColor = "" public var title = "" public var learned = false public var index = 0 public var isBonus = false public var short = "" public var progressPercent = 0 public var isMastered = false public init?(rawJson:[String:AnyObject]) { super.init() if let newLanguageSkill = rawJson["language_string"] as? String { languageString = newLanguageSkill } if let newIconColor = rawJson["icon_color"] as? String { iconColor = newIconColor } if let newTitle = rawJson["title"] as? String { title = newTitle } if let newLearned = rawJson["learned"] as? Bool { learned = newLearned } if let newIndex = rawJson["index"] as? String { index = Int(newIndex)! } if let newBonus = rawJson["bonus"] as? Bool { isBonus = newBonus } if let newShort = rawJson["short"] as? String { short = newShort } if let newProgressPercent = rawJson["progress_percent"] as? Int { progressPercent = newProgressPercent } if let newIsMastered = rawJson["mastered"] as? Bool { isMastered = newIsMastered } } }
mit
f9630a7938556b7f013219f154c3a67b
23.953125
73
0.537884
4.58908
false
false
false
false
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/Extensions/NSArrayExtension.swift
1
4384
// // NSArrayExtension.swift // Pods // // Created by MacMini-2 on 01/09/17. // // import Foundation /// This extension add some useful functions to NSArray public extension NSArray { // MARK: - Instance functions - /** Get the object at a given index in safe mode (nil if self is empty or out of range) - parameter index: The index - returns: Returns the object at a given index in safe mode (nil if self is empty or out of range) */ func safeObjectAtIndex(index: Int) -> AnyObject? { if self.count > 0 && self.count > index { return self[index] as AnyObject? } else { return nil } } /** Create a reversed array from self - returns: Returns the reversed array */ func reversedArray() -> NSArray { return NSArray.reversedArray(array: self) } /** Convert self to JSON as String - returns: Returns the JSON as String or nil if error while parsing */ func arrayToJSON() throws -> NSString { return try NSArray.arrayToJSON(array: self) } /** Simulates the array as a circle. When it is out of range, begins again - parameter index: The index - returns: Returns the object at a given index */ func objectAtCircleIndex(index: Int) -> AnyObject { return self[self.superCircle(index: index, size: self.count)] as AnyObject } /** Private, to get the index as a circle - parameter index: The index - parameter maxSize: Max size of the array - returns: Returns the right index */ private func superCircle(index: Int, size maxSize: Int) -> Int{ var _index = index if _index < 0 { _index = _index % maxSize _index += maxSize } if _index >= maxSize { _index = _index % maxSize } return _index } // MARK: - Class functions - /** Create a reversed array from the given array - parameter array: The array to be reverse - returns: Returns the reversed array */ static func reversedArray(array: NSArray) -> NSArray { let arrayTemp: NSMutableArray = NSMutableArray.init(capacity: array.count) let enumerator: NSEnumerator = array.reverseObjectEnumerator() for element in enumerator { arrayTemp.add(element) } return arrayTemp } /** Create a reversed array from the given array - parameter array: The array to be converted - returns: Returns the JSON as String or nil if error while parsing */ static func arrayToJSON(array: AnyObject) throws -> NSString { let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions()) return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! } //Json String func JSONString() -> NSString{ var jsonString : NSString = "" do { let jsonData : Data = try JSONSerialization .data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue : 0)) jsonString = NSString(data: jsonData ,encoding: String.Encoding.utf8.rawValue)! } catch let error as NSError { print(error.localizedDescription) } return jsonString } // Make Comma separated String from array var toCommaString: String! { return self.componentsJoined(by: ",") } // Chack Array contain specific object func containsObject<T:AnyObject>(_ item:T) -> Bool { for element in self { if item === element as? T { return true } } return false } // Get Index of specific object func indexOfObject<T : Equatable>(_ x:T) -> Int? { for i in 0...self.count { if self[i] as! T == x { return i } } return nil } // Gets the object at the specified index, if it exists. func get(_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil } }
mit
8f9cefc556efbe8c412e64e1e789fdcc
25.409639
140
0.565237
4.801752
false
false
false
false
vzool/ios-nanodegree-earth-diary
Forecast.swift
1
2649
// // Forecast.swift // Map Forecast Diary // // Created by Abdelaziz Elrashed on 8/18/15. // Copyright (c) 2015 Abdelaziz Elrashed. All rights reserved. // import CoreData @objc(Forecast) class Forecast : NSManagedObject{ struct Keys{ static let ID = "id" static let Temp = "temp" static let Pressure = "pressure" static let Humidity = "humidity" static let TempMin = "temp_min" static let TempMax = "temp_max" static let WindSpeed = "wind_speed" static let WindDirection = "wind_direction" static let CreatedDate = "created_date" } @NSManaged var id:String @NSManaged var temp:NSNumber @NSManaged var pressure:NSNumber @NSManaged var humidity:NSNumber @NSManaged var temp_max:NSNumber @NSManaged var temp_min:NSNumber @NSManaged var wind_speed:NSNumber @NSManaged var wind_direction:NSNumber @NSManaged var created_date:NSDate @NSManaged var pin:Pin override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(data: NSDictionary ,context: NSManagedObjectContext?) { let entity = NSEntityDescription.entityForName("Forecast", inManagedObjectContext: context!) super.init(entity: entity!, insertIntoManagedObjectContext: context) if let main = data.valueForKey("main") as? NSDictionary{ if let temp = main.valueForKey("temp") as? Double{ self.temp = temp } if let temp_max = main.valueForKey("temp_max") as? Double{ self.temp_max = temp_max } if let temp_min = main.valueForKey("temp_min") as? Double{ self.temp_min = temp_min } if let humidity = main.valueForKey("humidity") as? Int{ self.humidity = humidity } if let pressure = main.valueForKey("pressure") as? Int{ self.pressure = pressure } } if let wind = data.valueForKey("wind") as? NSDictionary{ if let direction = wind.valueForKey("deg") as? Double{ self.wind_direction = direction } if let speed = wind.valueForKey("speed") as? Double{ self.wind_speed = speed } } id = NSUUID().UUIDString created_date = NSDate() } }
mit
4f554bcec4756e54d70f3c1695c58ae8
30.164706
113
0.576066
4.923792
false
false
false
false
stripe/stripe-ios
Tests/Tests/AddressViewControllerSnapshotTests.swift
1
4755
// // AddressViewControllerSnapshotTests.swift // StripeiOS Tests // // Created by Yuki Tokuhiro on 6/15/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import FBSnapshotTestCase @_spi(STP)@testable import Stripe @_spi(STP)@testable import StripeCore @_spi(STP)@testable import StripeUICore class AddressViewControllerSnapshotTests: FBSnapshotTestCase { private let addressSpecProvider: AddressSpecProvider = { let specProvider = AddressSpecProvider() specProvider.addressSpecs = [ "US": AddressSpec( format: "NOACSZ", require: "ACSZ", cityNameType: .city, stateNameType: .state, zip: "", zipNameType: .zip ) ] return specProvider }() var configuration: AddressViewController.Configuration { var config = AddressViewController.Configuration() config.apiClient = .init(publishableKey: "pk_test_1234") return config } override func setUp() { super.setUp() // self.recordMode = true } func testShippingAddressViewController() { let testWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 428, height: 500)) testWindow.isHidden = false let vc = AddressViewController( addressSpecProvider: addressSpecProvider, configuration: configuration, delegate: self ) let navVC = UINavigationController(rootViewController: vc) testWindow.rootViewController = navVC verify(navVC.view) } @available(iOS 13.0, *) func testShippingAddressViewController_darkMode() { let testWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 428, height: 500)) testWindow.isHidden = false testWindow.overrideUserInterfaceStyle = .dark let vc = AddressViewController( addressSpecProvider: addressSpecProvider, configuration: configuration, delegate: self ) let navVC = UINavigationController(rootViewController: vc) testWindow.rootViewController = navVC verify(navVC.view) } func testShippingAddressViewController_appearance() { let testWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 428, height: 500)) testWindow.isHidden = false var configuration = configuration configuration.appearance = PaymentSheetTestUtils.snapshotTestTheme let vc = AddressViewController( addressSpecProvider: addressSpecProvider, configuration: configuration, delegate: self ) let navVC = UINavigationController(rootViewController: vc) testWindow.rootViewController = navVC verify(navVC.view) } func testShippingAddressViewController_customText() { let testWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 428, height: 500)) testWindow.isHidden = false var configuration = configuration configuration.title = "Custom title" configuration.buttonTitle = "Custom button title" let vc = AddressViewController( addressSpecProvider: addressSpecProvider, configuration: configuration, delegate: self ) let navVC = UINavigationController(rootViewController: vc) testWindow.rootViewController = navVC verify(navVC.view) } func testShippingAddressViewController_checkbox() { let testWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 428, height: 500)) testWindow.isHidden = false var configuration = configuration configuration.additionalFields.checkboxLabel = "Test checkbox text" configuration.defaultValues = .init( address: .init(), name: nil, phone: nil, isCheckboxSelected: true ) let vc = AddressViewController( addressSpecProvider: addressSpecProvider, configuration: configuration, delegate: self ) let navVC = UINavigationController(rootViewController: vc) testWindow.rootViewController = navVC verify(navVC.view) } func verify( _ view: UIView, identifier: String? = nil, file: StaticString = #filePath, line: UInt = #line ) { STPSnapshotVerifyView(view, identifier: identifier, file: file, line: line) } } extension AddressViewControllerSnapshotTests: AddressViewControllerDelegate { func addressViewControllerDidFinish( _ addressViewController: AddressViewController, with address: AddressViewController.AddressDetails? ) { // no-op } }
mit
39d0e307f83c5e85ab497493894670b8
33.70073
85
0.63883
5.540793
false
true
false
false
yorkepb/nytm-ios10-notifications
NYTimes/InteractiveNotifications.swift
1
1445
// // InteractiveNotifications.swift // NYTimes // // Created by iYrke on 7/14/16. // Copyright © 2016 iYorke. All rights reserved. // import Foundation import UserNotifications /** An enum provided to contain information relative to the notification actions. This is provided as a means of easily identifying action strings in other locations of the app (for handling notification action responses from users) */ enum InteractiveNotifications: String { case Follow = "follow" case Read = "read" case Save = "save" private func title() -> String { switch self { case .Follow: return "Follow for Updates" case .Read: return "Read Story" case .Save: return "Save for Later" } } /** Three notification actions used for interactive notifications here just as examples. This is functionality introduced in iOS 8, not new to iOS 10 however the object types have changed from `UIUserNotificationAction` to the new `UNNotificationAction`. Everything else about how this functions is the same. */ func action() -> UNNotificationAction { var options: UNNotificationActionOptions = [] switch self { case .Read: options = [.foreground] default: break } return UNNotificationAction(identifier: self.rawValue, title: self.title(), options: options) } }
apache-2.0
d79852af0c52de2a8fbec07a6ccb3c71
30.347826
309
0.660888
4.838926
false
false
false
false
wjk/AdBlockPlus-macOS
SafariExtension/ContentBlockerRequestHandler.swift
1
1962
// // This file is part of Adblock Plus <https://adblockplus.org/>, // Copyright (C) 2006-2016 Eyeo GmbH // // Adblock Plus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as // published by the Free Software Foundation. // // Adblock Plus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. // import Foundation import AdBlockKit @objc(ABPContentBlockerRequestHandler) class ContentBlockerRequestHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { NSLog("AdBlockPlus Safari Extension: Entry") do { guard let libraryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AdBlockPlus.applicationGroup) else { throw NSError() } let dirURL = libraryURL.appendingPathComponents([ "Library", "AdBlockPlus Filter Lists" ]) try FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true, attributes: nil) } catch { fatalError("Could not create AdBlockPlus Filter Lists directory") } let abp = AdBlockPlus() abp.activated = true let downloadedVersion = abp.downloadedVersion let url = abp.activeFilterListURLWithWhitelistedWebsites guard let attachment = NSItemProvider(contentsOf: url) else { fatalError("Could not create NSItemProvider for URL '\(url)'") } let extensionItem = NSExtensionItem() extensionItem.attachments = [attachment] context.completeRequest(returningItems: [extensionItem]) { (expired) in if !expired { abp.installedVersion = max(abp.installedVersion, downloadedVersion) } } } }
gpl-3.0
c32a6b538d9be331d041b972f82d9689
35.333333
134
0.756881
4.293217
false
false
false
false
CatchChat/Yep
Yep/Views/Cells/ChatLeftSocialWork/ChatLeftSocialWorkCell.swift
1
4357
// // ChatLeftSocialWorkCell.swift // Yep // // Created by nixzhu on 15/11/17. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit import Kingfisher final class ChatLeftSocialWorkCell: UICollectionViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var socialWorkImageView: UIImageView! @IBOutlet weak var githubRepoContainerView: UIView! @IBOutlet weak var githubRepoImageView: UIImageView! @IBOutlet weak var githubRepoNameLabel: UILabel! @IBOutlet weak var githubRepoDescriptionLabel: UILabel! @IBOutlet weak var logoImageView: UIImageView! @IBOutlet weak var syncButton: BorderButton! @IBOutlet weak var centerLineImageView: UIImageView! lazy var maskImageView: UIImageView = { let imageView = UIImageView(image: UIImage.yep_socialMediaImageMask) return imageView }() var socialWork: MessageSocialWork? var createFeedAction: ((socialWork: MessageSocialWork) -> Void)? override func awakeFromNib() { super.awakeFromNib() socialWorkImageView.maskView = maskImageView githubRepoImageView.tintColor = UIColor.yepIconImageViewTintColor() syncButton.setTitle(NSLocalizedString("Sync to Feeds", comment: ""), forState: .Normal) syncButton.setTitle(NSLocalizedString("Synced to Feeds", comment: ""), forState: .Disabled) syncButton.setTitleColor(UIColor.yepTintColor(), forState: .Normal) syncButton.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled) } override func layoutSubviews() { super.layoutSubviews() maskImageView.frame = socialWorkImageView.bounds } override func prepareForReuse() { super.prepareForReuse() socialWorkImageView.image = nil socialWork = nil } func configureWithMessage(message: Message) { if let sender = message.fromFriend { let userAvatar = UserAvatar(userID: sender.userID, avatarURLString: sender.avatarURLString, avatarStyle: nanoAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) } if let socialWork = message.socialWork { self.socialWork = socialWork var socialWorkImageURL: NSURL? guard let socialWorkType = MessageSocialWorkType(rawValue: socialWork.type), socialAccount = SocialAccount(rawValue: socialWorkType.accountName) else { return } logoImageView.image = UIImage(named: socialAccount.iconName) logoImageView.tintColor = socialAccount.tintColor switch socialWorkType { case .GithubRepo: socialWorkImageView.hidden = true githubRepoContainerView.hidden = false centerLineImageView.hidden = false if let githubRepo = socialWork.githubRepo { githubRepoNameLabel.text = githubRepo.name githubRepoDescriptionLabel.text = githubRepo.repoDescription syncButton.enabled = !githubRepo.synced } case .DribbbleShot: socialWorkImageView.hidden = false githubRepoContainerView.hidden = true centerLineImageView.hidden = true if let dribbbleShot = socialWork.dribbbleShot { socialWorkImageURL = NSURL(string: dribbbleShot.imageURLString) syncButton.enabled = !dribbbleShot.synced } case .InstagramMedia: socialWorkImageView.hidden = false githubRepoContainerView.hidden = true centerLineImageView.hidden = true if let string = socialWork.instagramMedia?.imageURLString { socialWorkImageURL = NSURL(string: string) } } if let URL = socialWorkImageURL { socialWorkImageView.kf_setImageWithURL(URL, placeholderImage: nil) } } } @IBAction func sync(sender: BorderButton) { guard let socialWork = socialWork else { return } createFeedAction?(socialWork: socialWork) } }
mit
e910845afe516356ca86884696b9f16f
30.1
133
0.644006
5.972565
false
false
false
false
prey/prey-ios-client
Prey/Classes/HomeWebVC.swift
1
29651
// // HomeWebVC.swift // Prey // // Created by Javier Cala Uribe on 13/2/18. // Copyright © 2018 Prey, Inc. All rights reserved. // import Foundation import UIKit import WebKit import LocalAuthentication import Firebase import FirebaseCrashlytics class HomeWebVC: UIViewController, WKUIDelegate, WKNavigationDelegate { // MARK: Properties var webView = WKWebView() var showPanel = false var checkAuth = true var actInd = UIActivityIndicatorView() let rectView = UIScreen.main.bounds var request : URLRequest { let mode = PreyConfig.sharedInstance.getDarkModeState(self) // Set language for webView let language:String = Locale.preferredLanguages[0] as String var languageES = (language as NSString).substring(to: 2) if (languageES != "es") {languageES = "en"} let indexPage = "index" let baseURL = URL(fileURLWithPath: Bundle.main.path(forResource:indexPage, ofType:"html", inDirectory:"ReactViews")!) let startState = (PreyConfig.sharedInstance.validationUserEmail == PreyUserEmailValidation.pending.rawValue) ? "emailsent" : "start" let pathURL = (PreyConfig.sharedInstance.isRegistered) ? "#/\(languageES)/index\(mode)" : "#/\(languageES)/\(startState)\(mode)" return URLRequest(url:URL(string: pathURL, relativeTo: baseURL)!) } // MARK: Init required init?(coder: NSCoder) { super.init(coder: coder) if #available(iOS 13.0, *) { if PreyConfig.sharedInstance.isSystemDarkMode { return } self.overrideUserInterfaceStyle = PreyConfig.sharedInstance.isDarkMode ? .dark : .light } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black // Config webView let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame:rectView, configuration:webConfiguration) webView.backgroundColor = UIColor.black webView.uiDelegate = self webView.navigationDelegate = self webView.isMultipleTouchEnabled = true webView.allowsBackForwardNavigationGestures = false // Load request webView.load(request) // Add webView to View self.view.addSubview(webView) self.actInd = UIActivityIndicatorView(initInView:self.view, withText:"Please wait".localized) webView.addSubview(actInd) if (PreyConfig.sharedInstance.isRegistered) { // Check for Rate us PreyRateUs.sharedInstance.askForReview() // Check new version on App Store PreyConfig.sharedInstance.checkLastVersionOnStore() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool){ // Hide navigationBar when appear this ViewController self.navigationController?.isNavigationBarHidden = true super.viewWillAppear(animated) } // Check TouchID/FaceID func checkTouchID(_ openPanelWeb: String?) { guard PreyConfig.sharedInstance.isTouchIDEnabled == true, PreyConfig.sharedInstance.tokenPanel != nil else { return } // Check Panel token expired time < 1h guard (PreyConfig.sharedInstance.tokenWebTimestamp + 60*60) > CFAbsoluteTimeGetCurrent() else { return } let myContext = LAContext() let myLocalizedReasonString = "Would you like to use \(biometricAuth) to access the Prey settings?".localized var authError: NSError? guard myContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) else { PreyLogger("error with biometric policy") return } myContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: myLocalizedReasonString) { success, evaluateError in DispatchQueue.main.async { guard success else { PreyLogger("error with auth on touchID") self.showPanel = false return } // Show webView if openPanelWeb == "panel" { self.goToControlPanel() } else { if openPanelWeb == "setting" { self.goToLocalSettings() } else { self.goToRename() } } // Hide credentials webView self.evaluateJS(self.webView, code: "var btn = document.getElementById('cancelBtn'); btn.click();") } } } // Check device auth func checkDeviceAuth(webView: WKWebView) { guard checkAuth == true else { return } DeviceAuth.sharedInstance.checkAllDeviceAuthorization { granted in DispatchQueue.main.async { let titleTxt = granted ? "protected".localized : "unprotected".localized self.evaluateJS(webView, code:"document.getElementById('txtStatusDevice').innerHTML = '\(titleTxt)';") self.checkAuth = false } } } // Open URL from Safari func openBrowserWith(_ url:URL?) { if let urlRequest = url { UIApplication.shared.openURL(urlRequest) } } // Check password func checkPassword(_ pwd: String?, view: UIView, back: String) { // Check password length guard let pwdInput = pwd else { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } if pwdInput.count < 6 { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } // Hide keyboard self.view.endEditing(true) // Show ActivityIndicator let actInd = UIActivityIndicatorView(initInView: self.view, withText:"Please wait".localized) self.view.addSubview(actInd) actInd.startAnimating() // Check userApiKey length guard let userApiKey = PreyConfig.sharedInstance.userApiKey else { displayErrorAlert("Wrong password. Try again.".localized, titleMessage:"We have a situation!".localized) return } // Get Token for Control Panel PreyUser.getTokenFromPanel(userApiKey, userPassword:pwdInput, onCompletion:{(isSuccess: Bool) in // Hide ActivityIndicator DispatchQueue.main.async { actInd.stopAnimating() // Check sucess request guard isSuccess else { return } // Show Settings View self.sendEventGAnalytics() // Show webView if back == "panel" { self.goToControlPanel() } else { if back == "setting" { self.goToLocalSettings() } else { self.goToRename() } } // Hide credentials webView self.evaluateJS(self.webView, code: "var btn = document.getElementById('cancelBtn'); btn.click();") } }) } // Send GAnalytics event func sendEventGAnalytics() { // if let tracker = GAI.sharedInstance().defaultTracker { // // let dimensionValue = PreyConfig.sharedInstance.isPro ? "Pro" : "Free" // tracker.set(GAIFields.customDimension(for: 1), value:dimensionValue) // // let params:NSObject = GAIDictionaryBuilder.createEvent(withCategory: "UserActivity", action:"Log In", label:"Log In", value:nil).build() // tracker.send(params as! [NSObject : AnyObject]) // } } // Add device with QRCode func addDeviceWithQRCode() { let controller:QRCodeScannerVC = QRCodeScannerVC() if #available(iOS 13, *) {controller.modalPresentationStyle = .fullScreen} self.navigationController?.present(controller, animated:true, completion:nil) } // Add device func addDeviceWithLogin(_ email: String?, password: String?) { // Check valid email if isInvalidEmail(email!, withPattern:emailRegExp) { displayErrorAlert("Enter a valid e-mail address".localized, titleMessage:"We have a situation!".localized) return } // Check password length if password!.count < 6 { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } // Hide keyboard self.view.endEditing(true) // Show ActivityIndicator let actInd = UIActivityIndicatorView(initInView: self.view, withText: "Attaching device...".localized) self.view.addSubview(actInd) actInd.startAnimating() // LogIn to Panel Prey PreyUser.logInToPrey(email!, userPassword: password!, onCompletion: {(isSuccess: Bool) in // LogIn isn't Success guard isSuccess else { // Hide ActivityIndicator DispatchQueue.main.async { actInd.stopAnimating() } return } // Get Token for Control Panel //PreyUser.getTokenFromPanel(email!, userPassword:password!, onCompletion: {_ in }) // Add Device to Panel Prey PreyDevice.addDeviceWith({(isSuccess: Bool) in DispatchQueue.main.async { // Hide ActivityIndicator actInd.stopAnimating() // AddDevice isn't success guard isSuccess else { return } self.loadViewOnWebView("permissions") } }) }) } func renameDevice(_ newName: String?){ PreyDevice.renameDevice(newName! ,onCompletion: {(isSuccess: Bool) in if(isSuccess){ PreyConfig.sharedInstance.nameDevice = newName PreyConfig.sharedInstance.saveValues() } self.loadViewOnWebView("index") self.webView.reload() }) } // Check signUp fields func checkSignUpFields(_ name: String?, email: String?, password1: String?, password2: String?, term: Bool, age: Bool) { // Check terms and conditions if (!age || !term) { displayErrorAlert("You must accept the Terms & Conditions".localized, titleMessage:"We have a situation!".localized) return } guard let nm = name else { displayErrorAlert("Name can't be blank".localized, titleMessage:"We have a situation!".localized) return } guard let pwd1 = password1 else { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } guard let pwd2 = password2 else { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } if pwd1 != pwd2 { displayErrorAlert("Passwords do not match".localized, titleMessage:"We have a situation!".localized) return } // Check name length if nm.count < 1 { displayErrorAlert("Name can't be blank".localized, titleMessage:"We have a situation!".localized) return } // Check valid email if isInvalidEmail(email!, withPattern:emailRegExp) { displayErrorAlert("Enter a valid e-mail address".localized, titleMessage:"We have a situation!".localized) return } // Check password length if pwd1.count < 6 { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } // Hide keyboard self.view.endEditing(true) // Show popUp to emailValidation self.evaluateJS(self.webView, code: "var btn = document.getElementById('btnEmailValidation'); btn.click();") } // Add device action func addDeviceWithSignUp(_ name: String?, email: String?, password1: String?, password2: String?, term: Bool, age: Bool, offers: Bool?) { guard let nm = name else { displayErrorAlert("Name can't be blank".localized, titleMessage:"We have a situation!".localized) return } guard let pwd1 = password1 else { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } // Show ActivityIndicator let actInd = UIActivityIndicatorView(initInView: self.view, withText: "Creating account...".localized) self.view.addSubview(actInd) actInd.startAnimating() // SignUp to Panel Prey PreyUser.signUpToPrey(nm, userEmail:email!, userPassword:pwd1, offers:offers!, onCompletion: {(isSuccess: Bool) in // LogIn isn't Success guard isSuccess else { // Hide ActivityIndicator DispatchQueue.main.async { actInd.stopAnimating() } return } // Get Token for Control Panel //PreyUser.getTokenFromPanel(email!, userPassword:pwd1, onCompletion: {_ in }) // Add Device to Panel Prey PreyDevice.addDeviceWith({(isSuccess: Bool) in DispatchQueue.main.async { // Hide ActivityIndicator actInd.stopAnimating() // Add Device Success guard isSuccess else { return } //self.loadViewOnWebView("permissions") DeviceAuth.sharedInstance.requestAuthNotification(false) PreyConfig.sharedInstance.userEmail = email PreyConfig.sharedInstance.validationUserEmail = PreyUserEmailValidation.pending.rawValue PreyConfig.sharedInstance.isRegistered = false PreyConfig.sharedInstance.saveValues() self.loadViewOnWebView("emailsent") self.webView.reload() } }) }) } // Show webView on modal func showWebViewModal(_ urlString: String, pageTitle: String) { let controller : UIViewController if #available(iOS 10.0, *) { controller = WebKitVC(withURL:URL(string:urlString)!, withParameters:nil, withTitle:pageTitle) } else { controller = WebVC(withURL:URL(string:urlString)!, withParameters:nil, withTitle:pageTitle) } if #available(iOS 13, *) {controller.modalPresentationStyle = .fullScreen} self.present(controller, animated:true, completion:nil) } // Load view on webView func loadViewOnWebView(_ view:String) { let mode = PreyConfig.sharedInstance.getDarkModeState(self) var request : URLRequest let language:String = Locale.preferredLanguages[0] as String var languageES = (language as NSString).substring(to: 2) if (languageES != "es") {languageES = "en"} let indexPage = "index" let baseURL = URL(fileURLWithPath: Bundle.main.path(forResource:indexPage, ofType:"html", inDirectory:"ReactViews")!) let pathURL = "#/\(languageES)/\(view)\(mode)" request = URLRequest(url:URL(string: pathURL, relativeTo: baseURL)!) webView.load(request) } // Go to Control Panel func goToControlPanel() { if let token = PreyConfig.sharedInstance.tokenPanel { let params = String(format:"token=%@", token) let controller : UIViewController if #available(iOS 10.0, *) { controller = WebKitVC(withURL:URL(string:URLSessionPanel)!, withParameters:params, withTitle:"Control Panel Web") } else { controller = WebVC(withURL:URL(string:URLSessionPanel)!, withParameters:params, withTitle:"Control Panel Web") } if #available(iOS 13, *) {controller.modalPresentationStyle = .fullScreen} self.present(controller, animated:true, completion:nil) } else { displayErrorAlert("Error, retry later.".localized, titleMessage:"We have a situation!".localized) } } // Go to Local Settings func goToLocalSettings() { guard let appWindow = UIApplication.shared.delegate?.window else { PreyLogger("error with sharedApplication") return } guard let rootVC = appWindow?.rootViewController else { PreyLogger("error with rootVC") return } let mainStoryboard: UIStoryboard = UIStoryboard(name:StoryboardIdVC.PreyStoryBoard.rawValue, bundle: nil) let resultController = mainStoryboard.instantiateViewController(withIdentifier: StoryboardIdVC.settings.rawValue) (rootVC as! UINavigationController).pushViewController(resultController, animated: true) } func goToRename(){ self.loadViewOnWebView("rename") self.webView.reload() } // MARK: WKUIDelegate func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { PreyLogger("Start load WKWebView") // Show ActivityIndicator DispatchQueue.main.async { self.actInd.startAnimating() } } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { PreyLogger("Should load request: WKWebView") guard let requestUrl = navigationAction.request.url else { return decisionHandler(.allow) } if let host = requestUrl.host { switch host { // Worldpay case BlockHost.WORLDPAY.rawValue: displayErrorAlert("This service is not available from here. Please go to 'Manage Prey Settings' from the main menu in the app.".localized, titleMessage:"Information".localized) return decisionHandler(.cancel) // Help Prey case BlockHost.HELPPREY.rawValue: openBrowserWith(URL(string:URLHelpPrey)) return decisionHandler(.cancel) // Panel Prey case BlockHost.PANELPREY.rawValue: evaluateJS(webView, code:"var printBtn = document.getElementById('print'); printBtn.style.display='none';") return decisionHandler(.allow) // Google Maps and image reports case BlockHost.S3AMAZON.rawValue: openBrowserWith(requestUrl) return decisionHandler(.cancel) // Default true default: PreyLogger("Ok") //decisionHandler(.allow) } } // Evaluate scheme if let urlScheme = requestUrl.scheme { DispatchQueue.main.async { self.evaluateURLScheme(webView, scheme: urlScheme, reqUrl: requestUrl) } } return decisionHandler(.allow) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { PreyLogger("Finish load WKWebView") // Hide ActivityIndicator DispatchQueue.main.async { self.actInd.stopAnimating() } // Hide ViewMap class evaluateJS(webView, code:"var viewMapBtn = document.getElementsByClassName('btn btn-block btn-border')[1]; viewMapBtn.style.display='none';") // Hide addDeviceBtn evaluateJS(webView, code:"var addDeviceBtn = document.getElementsByClassName('btn btn-success pull-right')[0]; addDeviceBtn.style.display='none';") // Hide accountPlans evaluateJS(webView, code:"var accountPlans = document.getElementById('account-plans'); accountPlans.style.display='none';") // Hide print option evaluateJS(webView, code:"var printBtn = document.getElementById('print'); printBtn.style.display='none';") // Check device auth if (PreyConfig.sharedInstance.isRegistered) { checkDeviceAuth(webView: webView) } // Email validation reactView if let email = PreyConfig.sharedInstance.userEmail { evaluateJS(webView, code:"document.getElementById('userEmail').value='\(email)';") } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { PreyLogger("Error loading WKWebView") // Hide ActivityIndicator DispatchQueue.main.async { self.actInd.stopAnimating() } displayErrorAlert("Error loading web, please try again.".localized, titleMessage:"We have a situation!".localized) } func evaluateJS(_ view: WKWebView, code: String) { DispatchQueue.main.async { view.evaluateJavaScript(code, completionHandler:nil) } } func evaluateURLScheme(_ webView: WKWebView, scheme: String, reqUrl: URL) { switch scheme { case ReactViews.CHECKID.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let openPanelWeb = queryItems?.filter({$0.name == "openPanelWeb"}).first self.checkTouchID(openPanelWeb?.value) case ReactViews.QRCODE.rawValue: self.addDeviceWithQRCode() case ReactViews.LOGIN.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let email = queryItems?.filter({$0.name == "preyEmailLogin"}).first let pwd = queryItems?.filter({$0.name == "preyPassLogin"}).first self.addDeviceWithLogin(email?.value, password: pwd?.value) case ReactViews.RENAME.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let newName = queryItems?.filter({$0.name == "newName"}).first self.renameDevice(newName?.value) case ReactViews.CHECKSIGNUP.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let name = queryItems?.filter({$0.name == "nameSignup"}).first let email = queryItems?.filter({$0.name == "emailSignup"}).first let pwd1 = queryItems?.filter({$0.name == "pwd1Signup"}).first let pwd2 = queryItems?.filter({$0.name == "pwd2Signup"}).first guard let term = queryItems?.filter({$0.name == "termsSignup"}).first else {return} guard let age = queryItems?.filter({$0.name == "ageSignup"}).first else {return} let offers = queryItems?.filter({$0.name == "offers"}).first self.checkSignUpFields(name?.value, email: email?.value, password1: pwd1?.value, password2: pwd2?.value, term: term.value!.boolValue(), age: age.value!.boolValue()) case ReactViews.SIGNUP.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let name = queryItems?.filter({$0.name == "nameSignup"}).first let email = queryItems?.filter({$0.name == "emailSignup"}).first let pwd1 = queryItems?.filter({$0.name == "pwd1Signup"}).first let pwd2 = queryItems?.filter({$0.name == "pwd2Signup"}).first guard let term = queryItems?.filter({$0.name == "termsSignup"}).first else {return} guard let age = queryItems?.filter({$0.name == "ageSignup"}).first else {return} let offers = queryItems?.filter({$0.name == "offers"}).first self.addDeviceWithSignUp(name?.value, email: email?.value, password1: pwd1?.value, password2: pwd2?.value, term: term.value!.boolValue(), age: age.value!.boolValue(), offers: offers?.value?.boolValue() ) case ReactViews.EMAILRESEND.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let email = queryItems?.filter({$0.name == "emailSignup"}).first if isInvalidEmail((email?.value)!, withPattern:emailRegExp) { displayErrorAlert("Enter a valid e-mail address".localized, titleMessage:"We have a situation!".localized) } else { PreyUser.resendEmailValidation((email?.value)!, onCompletion: {(isSuccess: Bool) in DispatchQueue.main.async { // Resend email success guard isSuccess else { return } self.evaluateJS(self.webView, code: "var btn = document.getElementById('btnIDEmailValidation'); btn.click();") } }) } PreyLogger("Resend email validation") case ReactViews.TERMS.rawValue: self.showWebViewModal(URLTermsPrey, pageTitle: "Terms of Service".localized) case ReactViews.PRIVACY.rawValue: self.showWebViewModal(URLPrivacyPrey, pageTitle: "Privacy Policy".localized) case ReactViews.FORGOT.rawValue: self.showWebViewModal(URLForgotPanel, pageTitle: "Forgot Password Web") case ReactViews.AUTHLOC.rawValue: DeviceAuth.sharedInstance.requestAuthLocation() case ReactViews.AUTHPHOTO.rawValue: DeviceAuth.sharedInstance.requestAuthPhotos() case ReactViews.AUTHCONTACT.rawValue: DeviceAuth.sharedInstance.requestAuthContacts() case ReactViews.AUTHCAMERA.rawValue: DeviceAuth.sharedInstance.requestAuthCamera() case ReactViews.AUTHNOTIF.rawValue: DeviceAuth.sharedInstance.requestAuthNotification(true) case ReactViews.REPORTEXAMP.rawValue: self.actInd.startAnimating() ReportExample.sharedInstance.runReportExample(webView) case ReactViews.GOTOSETTING.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let pwd = queryItems?.filter({$0.name == "pwdLogin"}).first self.checkPassword(pwd?.value, view: self.view, back: "setting") case ReactViews.GOTOPANEL.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let pwd = queryItems?.filter({$0.name == "pwdLogin"}).first self.checkPassword(pwd?.value, view: self.view, back: "panel") case ReactViews.GOTORENAME.rawValue: let queryItems = URLComponents(string: reqUrl.absoluteString)?.queryItems let pwd = queryItems?.filter({$0.name == "pwdLogin"}).first self.checkPassword(pwd?.value, view: self.view, back: "rename") case ReactViews.NAMEDEVICE.rawValue: var nameDevice=PreyConfig.sharedInstance.nameDevice if nameDevice == nil { nameDevice="iPhone"; } self.evaluateJS(self.webView, code: "document.getElementById('nametext').value = '\(nameDevice!)';") self.evaluateJS(self.webView, code: "var btn = document.getElementById('btnChangeName'); btn.click();") case ReactViews.INDEX.rawValue: self.loadViewOnWebView("index") self.webView.reload() default: PreyLogger("Ok") } } }
gpl-3.0
2a9ca1e5333b7a5c4b61395d51ec36f2
39.896552
215
0.574435
5.570167
false
false
false
false
InLefter/Wea
Wea/PopAnimation.swift
1
1004
// // PopAnimation.swift // Wea // // Created by Howie on 16/4/9. // Copyright © 2016年 Howie. All rights reserved. // import UIKit class PopAnimator: NSObject,UIViewControllerAnimatedTransitioning { let duration = 0.3 //动画持续时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return duration } //动画执行的方法 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() let toView = transitionContext.viewForKey(UITransitionContextToViewKey) containerView.addSubview(toView!) toView!.alpha = 0.0 UIView.animateWithDuration(duration, animations: { toView!.alpha = 1.0 }, completion: { _ in transitionContext.completeTransition(true) }) } }
mit
d3bc4483f35b784550064fd138c5c111
27.676471
105
0.625641
5.668605
false
false
false
false
DragonCherry/AssetsPickerViewController
AssetsPickerViewController/Classes/Library/Extensions/UIView+KVO.swift
1
1055
// // UIView+KVO.swift // Pods // // Created by DragonCherry on 1/9/17. // // import UIKit private let kUIViewKVODictionaryKey = "kUIViewKVODictionaryKey" public extension UIView { /** Set nil on first parameter to remove existing object for key. */ func set(_ object: Any?, forKey key: AnyHashable) { var dictionary: [AnyHashable: Any]! if let savedDictionary = self.layer.value(forKey: kUIViewKVODictionaryKey) as? [AnyHashable: Any] { dictionary = savedDictionary } else { dictionary = [AnyHashable: Any]() } if let object = object { dictionary[key] = object } else { dictionary.removeValue(forKey: key) } self.layer.setValue(dictionary, forKey: kUIViewKVODictionaryKey) } func get(_ key: AnyHashable) -> Any? { if let dictionary = self.layer.value(forKey: kUIViewKVODictionaryKey) as? [AnyHashable: Any] { return dictionary[key] } else { return nil } } }
mit
5d821dbea2a304f367fb434e96a7122f
26.051282
107
0.600948
4.359504
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project7/iExpense/AddView.swift
1
1238
// // AddView.swift // iExpense // // Created by Paul Hudson on 01/11/2021. // import SwiftUI struct AddView: View { @ObservedObject var expenses: Expenses @Environment(\.dismiss) var dismiss @State private var name = "" @State private var type = "Personal" @State private var amount = 0.0 let types = ["Business", "Personal"] var body: some View { NavigationView { Form { TextField("Name", text: $name) Picker("Type", selection: $type) { ForEach(types, id: \.self) { Text($0) } } TextField("Amount", value: $amount, format: .currency(code: "USD")) .keyboardType(.decimalPad) } .navigationTitle("Add new expense") .toolbar { Button("Save") { let item = ExpenseItem(name: name, type: type, amount: amount) expenses.items.append(item) dismiss() } } } } } struct AddView_Previews: PreviewProvider { static var previews: some View { AddView(expenses: Expenses()) } }
unlicense
d173e81aee3acbfc29dff3916e392a36
23.76
83
0.490307
4.619403
false
false
false
false
limsangjin12/Hero
Sources/Extensions/UIView+Hero.swift
2
4103
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public extension UIView { private struct AssociatedKeys { static var heroID = "heroID" static var heroModifiers = "heroModifers" static var heroStoredAlpha = "heroStoredAlpha" } /** **heroID** is the identifier for the view. When doing a transition between two view controllers, Hero will search through all the subviews for both view controllers and matches views with the same **heroID**. Whenever a pair is discovered, Hero will automatically transit the views from source state to the destination state. */ @IBInspectable public var heroID: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.heroID) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.heroID, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Use **heroModifiers** to specify animations alongside the main transition. Checkout `HeroModifier.swift` for available modifiers. */ public var heroModifiers: [HeroModifier]? { get { return objc_getAssociatedObject(self, &AssociatedKeys.heroModifiers) as? [HeroModifier] } set { objc_setAssociatedObject(self, &AssociatedKeys.heroModifiers, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** **heroModifierString** provides another way to set **heroModifiers**. It can be assigned through storyboard. */ @IBInspectable public var heroModifierString: String? { get { fatalError("Reverse lookup is not supported") } set { heroModifiers = newValue?.parse() } } internal func slowSnapshotView() -> UIView { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0) layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = bounds let snapshotView = UIView(frame:bounds) snapshotView.addSubview(imageView) return snapshotView } internal var flattenedViewHierarchy: [UIView] { if #available(iOS 9.0, *) { return isHidden && (superview is UICollectionView || superview is UIStackView) ? [] : ([self] + subviews.flatMap { $0.flattenedViewHierarchy }) } return isHidden && (superview is UICollectionView) ? [] : ([self] + subviews.flatMap { $0.flattenedViewHierarchy }) } /// Used for .overFullScreen presentation internal var heroStoredAlpha: CGFloat? { get { if let doubleValue = (objc_getAssociatedObject(self, &AssociatedKeys.heroStoredAlpha) as? NSNumber)?.doubleValue { return CGFloat(doubleValue) } return nil } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, NSNumber(value:newValue.native), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &AssociatedKeys.heroStoredAlpha, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
mit
f15425403708e4870b7406a819bb7303
41.298969
149
0.730441
4.810082
false
false
false
false
svanimpe/around-the-table
Sources/AroundTheTable/ViewModels/SponsorsViewModel.swift
1
729
/** View model for **sponsors.stencil**. */ struct SponsorsViewModel: Codable { let base: BaseViewModel struct SponsorViewModel: Codable { let name: String let description: String let picture: String let link: String init(_ sponsor: Sponsor) { self.name = sponsor.name self.description = sponsor.description self.picture = sponsor.picture.absoluteString self.link = sponsor.link.absoluteString } } let sponsors: [SponsorViewModel] init(base: BaseViewModel, sponsors: [Sponsor]) { self.base = base self.sponsors = sponsors.map(SponsorViewModel.init) } }
bsd-2-clause
c30df0a606002174cfc1a00f7da7f6d8
24.137931
59
0.587106
4.827815
false
true
false
false
antonio081014/LeetCode-CodeBase
Swift/find-the-duplicate-number.swift
1
1544
/** * Problem Link: https://leetcode.com/problems/find-the-duplicate-number/ * * Binary Search. */ class Solution { func findDuplicate(_ nums: [Int]) -> Int { var left = 1 var right = nums.count while left < right { let mid = left + (right - left) / 2 var count = 0 // Count number of numbers equal or smaller than mid. for n in nums { if n <= mid { count += 1 } } /// Key: /// For mid, we would have mid numbers smaller or equal to mid. /// If there is x numbers qualifed, and x is larger than mid, we know the duplicate number is equal or smaller than mid. /// Otherwise, left = mid + 1. /// if count <= mid { left = mid + 1 } else { right = mid } } // print("\(left) - \(right)") return left } } /** * https://leetcode.com/problems/find-the-duplicate-number/ * * */ // Date: Mon Mar 28 22:20:21 PDT 2022 class Solution { func findDuplicate(_ nums: [Int]) -> Int { guard nums.count > 1 else { return -1 } var slow = nums[0] var fast = nums[nums[0]] while fast != slow { slow = nums[slow] fast = nums[nums[fast]] } fast = 0 while fast != slow { slow = nums[slow] fast = nums[fast] } return fast } }
mit
99dd3445d1f4b2b14f534fecbf408645
25.637931
132
0.459197
4.230137
false
false
false
false
gaurav1981/HackingWithSwift
project9/Project7/MasterViewController.swift
20
3003
// // MasterViewController.swift // Project7 // // Created by Hudzilla on 20/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [[String: String]]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() var urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { [unowned self] in if let url = NSURL(string: urlString) { if let data = NSData(contentsOfURL: url, options: .allZeros, error: nil) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { self.parseJSON(json) } else { self.showError() } } else { self.showError() } } else { self.showError() } } } func parseJSON(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let obj = ["title": title, "body": body, "sigs": sigs] objects.append(obj) } dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.tableView.reloadData() } } func showError() { dispatch_async(dispatch_get_main_queue()) { [unowned self] in let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] (segue.destinationViewController as! DetailViewController).detailItem = object } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let object = objects[indexPath.row] cell.textLabel!.text = object["title"] cell.detailTextLabel!.text = object["body"] return cell } }
unlicense
533490a0fbdfa1f78e9804c084699f51
27.330189
171
0.699967
3.840153
false
false
false
false
cdmx/MiniMancera
miniMancera/View/OptionWhistlesVsZombies/Board/VOptionWhistlesVsZombiesBoardBar.swift
1
4226
import UIKit class VOptionWhistlesVsZombiesBoardBar:UIView { private weak var controller:COptionWhistlesVsZombiesBoard! private let kCancelWidth:CGFloat = 80 private let kCoinWidth:CGFloat = 50 private let kCoinLabelTop:CGFloat = -6 private let kCoinLabelWidth:CGFloat = 200 init(controller:COptionWhistlesVsZombiesBoard) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.textAlignment = NSTextAlignment.center labelTitle.textColor = UIColor.white labelTitle.font = UIFont.bold(size:16) labelTitle.text = String.localizedWhistlesVsZombies( key:"VOptionWhistlesVsZombiesBoardBar_labelTitle") let buttonCancel:UIButton = UIButton() buttonCancel.clipsToBounds = true buttonCancel.translatesAutoresizingMaskIntoConstraints = false buttonCancel.setImage( #imageLiteral(resourceName: "assetWhistlesVsZombiesWhistleBoardCancel"), for:UIControlState.normal) buttonCancel.imageView!.clipsToBounds = true buttonCancel.imageView!.contentMode = UIViewContentMode.center buttonCancel.addTarget( self, action:#selector(actionCancel(sender:)), for:UIControlEvents.touchUpInside) let imageCoin:UIImageView = UIImageView() imageCoin.isUserInteractionEnabled = false imageCoin.translatesAutoresizingMaskIntoConstraints = false imageCoin.clipsToBounds = true imageCoin.contentMode = UIViewContentMode.center imageCoin.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardPrice") let labelCoins:UILabel = UILabel() labelCoins.isUserInteractionEnabled = false labelCoins.translatesAutoresizingMaskIntoConstraints = false labelCoins.backgroundColor = UIColor.clear labelCoins.textAlignment = NSTextAlignment.right labelCoins.font = UIFont.game(size:17) labelCoins.textColor = UIColor( red:0.972549019607843, green:0.905882352941176, blue:0.109803921568627, alpha:1) addSubview(labelTitle) addSubview(labelCoins) addSubview(buttonCancel) addSubview(imageCoin) NSLayoutConstraint.equals( view:labelTitle, toView:self) NSLayoutConstraint.equalsVertical( view:buttonCancel, toView:self) NSLayoutConstraint.leftToLeft( view:buttonCancel, toView:self) NSLayoutConstraint.width( view:buttonCancel, constant:kCancelWidth) NSLayoutConstraint.equalsVertical( view:imageCoin, toView:self) NSLayoutConstraint.rightToRight( view:imageCoin, toView:self) NSLayoutConstraint.width( view:imageCoin, constant:kCoinWidth) NSLayoutConstraint.topToTop( view:labelCoins, toView:self, constant:kCoinLabelTop) NSLayoutConstraint.bottomToBottom( view:labelCoins, toView:self) NSLayoutConstraint.rightToLeft( view:labelCoins, toView:imageCoin) NSLayoutConstraint.width( view:labelCoins, constant:kCoinLabelWidth) guard let coins:Int = controller.controllerGame?.model.coins else { return } let coinsString:String = "\(coins)" labelCoins.text = coinsString } required init?(coder:NSCoder) { return nil } //MARK: actions func actionCancel(sender button:UIButton) { controller.back() } }
mit
74a330da562b8354fa6ea6fb3b3e19b1
32.015625
89
0.633223
6.071839
false
false
false
false
verticon/MecklenburgTrailOfHistory
Trail of History/Common/CustomColors.swift
1
2404
// // UIColor+CustomColors.swift // Trail of History // // Created by Robert Vaessen on 8/16/16. // Copyright © 2018 Robert Vaessen. All rights reserved. // import UIKit // MARK: - Custom Colors for the Trail of History extension UIColor { static let tohGreyishBrownColor: UIColor = { return UIColor(red: 62.0 / 255.0, green: 59.0 / 255.0, blue: 52.0 / 255.0, alpha: 1.0) }() static let tohDullYellowColor: UIColor = { return UIColor(red: 233.0 / 255.0, green: 190.0 / 255.0, blue: 88.0 / 255.0, alpha: 1.0) }() static let tohAdobeColor: UIColor = { return UIColor(red: 195.0 / 255.0, green: 115.0 / 255.0, blue: 76.0 / 255.0, alpha: 1.0) }() static let tohWhiteColor: UIColor = { return UIColor(white: 255.0 / 255.0, alpha: 1.0) }() static let tohGreyishBrown58Color: UIColor = { return UIColor(white: 78.0 / 255.0, alpha: 0.58) }() static let tohTerracotaColor: UIColor = { return UIColor(red: 209.0 / 255.0, green: 110.0 / 255.0, blue: 59.0 / 255.0, alpha: 1.0) }() static let tohGreyishBrownTwoColor: UIColor = { return UIColor(red: 62.0 / 255.0, green: 59.0 / 255.0, blue: 52.0 / 255.0, alpha: 1.0) }() static let tohDullYellowTwoColor: UIColor = { return UIColor(red: 233.0 / 255.0, green: 190.0 / 255.0, blue: 88.0 / 255.0, alpha: 1.0) }() static let tohWhite62Color: UIColor = { return UIColor(white: 255.0 / 255.0, alpha: 0.62) }() static let tohWarmGreyColor: UIColor = { return UIColor(white: 151.0 / 255.0, alpha: 1.0) }() static let tohWhiteTwoColor: UIColor = { return UIColor(white: 231.0 / 255.0, alpha: 1.0) }() static let tohGreyishBrownThreeColor: UIColor = { return UIColor(red: 122.0 / 255.0, green: 112.0 / 255.0, blue: 78.0 / 255.0, alpha: 1.0) }() static let tohWhiteThreeColor: UIColor = { return UIColor(white: 216.0 / 255.0, alpha: 1.0) }() static let tohGreyishBrownFourColor: UIColor = { return UIColor(white: 60.0 / 255.0, alpha: 1.0) }() static let tohGreyishColor: UIColor = { return UIColor(white: 167.0 / 255.0, alpha: 1.0) }() static let tohWarmGreyTwoColor: UIColor = { return UIColor(white: 136.0 / 255.0, alpha: 1.0) }() }
mit
c5d2b12b3853f2836c55c8c3f747e822
30.207792
96
0.583437
3.269388
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Classes/Controller/CSKeyboardObserverController.swift
1
3163
// // CSKeyboardManager.swift // Renetik // // Created by Rene Dohan on 7/9/19. // import UIKit public class CSKeyboardObserverController: CSViewController { public var keyboardHeight: CGFloat = 0 public var onKeyboardChange: ((CGFloat) -> Void)? public var onKeyboardShow: CSEvent<CGFloat> = event() public var onKeyboardHide = event() public var isKeyboardVisible: Bool { keyboardHeight > 0 } @discardableResult public func construct( _ parent: UIViewController, _ onKeyboardChange: ((_ keyboardHeight: CGFloat) -> Void)? = nil) -> Self { super.construct(parent).asViewLess() self.onKeyboardChange = onKeyboardChange observe(notification: UIResponder.keyboardDidShowNotification, callback: keyboardDidShow) observe(notification: UIResponder.keyboardDidHideNotification, callback: keyboardDidHide) return self } private func keyboardDidShow(_ note: Notification) { let rect = note.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect keyboardHeight = rect.size.height onKeyboardShow.fire(keyboardHeight) onKeyboardChange?(keyboardHeight) } private func keyboardDidHide(_ note: Notification) { keyboardHeight = 0 onKeyboardHide.fire() onKeyboardChange?(0) } } public class CSKeyboardObserver { public var keyboardHeight: CGFloat = 0 public var onKeyboardChange: ((CGFloat) -> Void)? public var onKeyboardShow: CSEvent<CGFloat> = event() public var onKeyboardHide = event() public var isKeyboardVisible: Bool { keyboardHeight > 0 } public var isKeyboardHidden: Bool { !isKeyboardVisible } @discardableResult public init(_ parent: CSViewController, _ onKeyboardChange: ((_ keyboardHeight: CGFloat) -> Void)? = nil) { self.onKeyboardChange = onKeyboardChange; registerEvents(parent) } @discardableResult public init(_ onKeyboardChange: ((_ keyboardHeight: CGFloat) -> Void)? = nil) { self.onKeyboardChange = onKeyboardChange; registerEvents(navigation.topViewController as? CSViewController) } private func registerEvents(_ parent: CSViewController? = nil) { parent.notNil { controller in controller.observe(notification: UIResponder.keyboardDidShowNotification, callback: keyboardDidShow) controller.observe(notification: UIResponder.keyboardDidHideNotification, callback: keyboardDidHide) }.elseDo { NotificationCenter.add(observer: UIResponder.keyboardDidShowNotification, using: keyboardDidShow) NotificationCenter.add(observer: UIResponder.keyboardDidHideNotification, using: keyboardDidHide) } } private func keyboardDidShow(_ note: Notification) { let rect = note.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect keyboardHeight = rect.size.height onKeyboardShow.fire(keyboardHeight) onKeyboardChange?(keyboardHeight) } private func keyboardDidHide(_ note: Notification) { keyboardHeight = 0 onKeyboardHide.fire() onKeyboardChange?(0) } }
mit
33304bbb262ff45591a2c1349e88f353
37.108434
115
0.704078
5.510453
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Data/CharSet.swift
1
7067
// // CharSet.swift // LispKit // // Created by Matthias Zenger on 02/01/2019. // Copyright © 2019 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// /// Simple character set implementation assuming characters are UTF16 code units. /// Immutability of character sets is implemented at the Scheme library level. /// public final class CharSet: NativeObject { /// Type representing character sets public static let type = Type.objectType(Symbol(uninterned: "char-set")) /// Native character set public private(set) var chars: Set<UniChar> /// Is this character set immutable? Immutability is not enforced via this class. public let immutable: Bool /// Return native object type. public override var type: Type { return Self.type } public override init() { self.chars = [] self.immutable = false } public init(immutable: Bool) { self.chars = [] self.immutable = immutable } public init(copy cs: CharSet, immutable: Bool = false) { self.chars = cs.chars self.immutable = immutable } public convenience init(charsIn str: NSString, immutable: Bool = false) { self.init(immutable: immutable) self.chars.reserveCapacity(str.length) for i in 0..<str.length { self.chars.insert(str.character(at: i)) } } public convenience init(charsIn str: String, immutable: Bool = false) { self.init(immutable: immutable) for ch in str.utf16 { self.chars.insert(ch) } } public func contains(_ ch: UniChar) -> Bool { return self.chars.contains(ch) } public func insert(_ ch: UniChar) { self.chars.insert(ch) } public func insert(charsIn str: NSString) { for i in 0..<str.length { self.chars.insert(str.character(at: i)) } } public func insert(charsIn str: String) { for ch in str.utf16 { self.chars.insert(ch) } } public func remove(_ ch: UniChar) { self.chars.remove(ch) } public func remove(charsIn str: NSString) { for i in 0..<str.length { self.chars.remove(str.character(at: i)) } } public func remove(charsIn str: String) { for ch in str.utf16 { self.chars.remove(ch) } } public func formUnion(_ cs: CharSet) { self.chars.formUnion(cs.chars) } public func formIntersection(_ cs: CharSet) { self.chars.formIntersection(cs.chars) } public func formSymmetricDifference(_ cs: CharSet) { self.chars.formSymmetricDifference(cs.chars) } public func subtract(_ cs: CharSet) { self.chars.subtract(cs.chars) } public var inverted: CharSet { let res = CharSet() for ch in 0...UInt16.max { if !self.chars.contains(ch) { res.chars.insert(ch) } } return res } public func invert() { for ch in 0...UInt16.max { if self.chars.contains(ch) { self.chars.remove(ch) } else { self.chars.insert(ch) } } } public var isEmpty: Bool { return self.chars.isEmpty } public var count: Int { return self.chars.count } public func forEach(f: (UniChar) -> Void) { for ch in self.chars { f(ch) } } public var array: [UniChar] { var res: [UniChar] = [] res.reserveCapacity(self.chars.count) for ch in self.chars { res.append(ch) } return res } public var first: UniChar? { for i in 0...UInt16.max { if self.chars.contains(i) { return i } } return nil } public func next(_ ch: UniChar) -> UniChar? { if ch == UInt16.max { return nil } for i in (ch + 1)...UInt16.max { if self.chars.contains(i) { return i } } return nil } public var charSetHashValue: Int { return self.chars.hashValue } public func isEqual(to cs: CharSet) -> Bool { return self.chars == cs.chars } public func isSubset(of cs: CharSet) -> Bool { return self.chars.isSubset(of: cs.chars) } public func isDisjoint(with cs: CharSet) -> Bool { return self.chars.isDisjoint(with: cs.chars) } // Definiton of default character sets public class func lowercaseLetters() -> CharSet { return CharSet.convert(cs: .lowercaseLetters) } public class func uppercaseLetters() -> CharSet { return CharSet.convert(cs: .uppercaseLetters) } public class func titlecaseLetters() -> CharSet { return CharSet.convert(cs: .capitalizedLetters) } public class func letters() -> CharSet { return CharSet.convert(cs: .letters) } public class func digits() -> CharSet { return CharSet.convert(cs: .decimalDigits) } public class func lettersAndDigits() -> CharSet { return CharSet.convert(cs: .alphanumerics) } public class func graphics() -> CharSet { return CharSet.convert(cs: .symbols, target: CharSet.convert(cs: .punctuationCharacters, target: CharSet.convert(cs: .alphanumerics))) } public class func printing() -> CharSet { return CharSet.convert(cs: .whitespacesAndNewlines, target: CharSet.graphics()) } public class func whitespaces() -> CharSet { return CharSet.convert(cs: .whitespacesAndNewlines) } public class func newlines() -> CharSet { return CharSet.convert(cs: .newlines) } public class func blanks() -> CharSet { return CharSet.convert(cs: .whitespaces) } public class func controls() -> CharSet { return CharSet.convert(cs: .controlCharacters) } public class func punctuations() -> CharSet { return CharSet.convert(cs: .punctuationCharacters) } public class func symbols() -> CharSet { return CharSet.convert(cs: .symbols) } public class func hexdigits() -> CharSet { return CharSet(charsIn: "0123456789ABCDEFabcdef", immutable: true) } public class func ascii() -> CharSet { let cs = CharSet(immutable: true) for ch: UInt16 in 0..<128 { cs.insert(ch) } return cs } public class func full() -> CharSet { let cs = CharSet(immutable: true) cs.invert() return cs } class func convert(cs: CharacterSet, target: CharSet? = nil) -> CharSet { return Self.convert(nscs: cs as NSCharacterSet, target: target) } class func convert(nscs: NSCharacterSet, target: CharSet? = nil) -> CharSet { let res = target == nil ? CharSet(immutable: true) : target! for ch in 0...UInt16.max { if nscs.characterIsMember(ch) { res.insert(ch) } } return res } }
apache-2.0
18776ce7e5bbf1f41a5b288effaad059
22.871622
96
0.642796
3.912514
false
false
false
false
invoy/CoreDataQueryInterface
CoreDataQueryInterface/Query.swift
1
11463
// // Query.swift // CoreDataQueryInterface // // Created by Gregory Higley on 9/25/16. // Copyright © 2016 Prosumma LLC. All rights reserved. // import CoreData import Foundation public struct Query<M: NSManagedObject, R: NSFetchRequestResult> where M: Entity { public let builder: QueryBuilder<M> public init(builder: QueryBuilder<M> = QueryBuilder<M>()) { self.builder = builder } public func context(managedObjectContext: NSManagedObjectContext) -> Query<M, R> { var builder = self.builder builder.managedObjectContext = managedObjectContext return Query<M, R>(builder: builder) } public func filter(_ predicate: NSPredicate) -> Query<M, R> { var builder = self.builder builder.predicates.append(predicate) return Query<M, R>(builder: builder) } public func filter(_ format: String, _ args: CVarArg...) -> Query<M, R> { return withVaList(args) { filter(NSPredicate(format: format, arguments: $0)) } } public func filter(_ block: (M.CDQIAttribute) -> NSPredicate) -> Query<M, R> { let predicate = block(M.CDQIAttribute()) return filter(predicate) } public func refilter() -> Query<M, R> { var builder = self.builder builder.predicates = [] return Query<M, R>(builder: builder) } public func select<P: Sequence>(_ properties: P) -> Query<M, NSDictionary> where P.Iterator.Element: PropertyConvertible { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToFetch ??= [] builder.propertiesToFetch!.append(contentsOf: properties.map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func select(_ properties: PropertyConvertible...) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToFetch ??= [] builder.propertiesToFetch!.append(contentsOf: properties.map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func select(_ blocks: ((M.CDQIAttribute) -> PropertyConvertible)...) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToFetch ??= [] let attribute = M.CDQIAttribute() builder.propertiesToFetch!.append(contentsOf: blocks.map{ $0(attribute).cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func select(_ block: (M.CDQIAttribute) -> [PropertyConvertible]) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToFetch ??= [] builder.propertiesToFetch!.append(contentsOf: block(M.CDQIAttribute()).map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func reselect() -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToFetch = nil return Query<M, NSDictionary>(builder: builder) } public func groupBy<P: Sequence>(_ properties: P) -> Query<M, NSDictionary> where P.Iterator.Element: PropertyConvertible { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToGroupBy ??= [] builder.propertiesToGroupBy!.append(contentsOf: properties.map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func groupBy(_ properties: PropertyConvertible...) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToGroupBy ??= [] builder.propertiesToGroupBy!.append(contentsOf: properties.map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func groupBy(_ blocks: ((M.CDQIAttribute) -> PropertyConvertible)...) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToGroupBy ??= [] let attribute = M.CDQIAttribute() builder.propertiesToGroupBy!.append(contentsOf: blocks.map { $0(attribute).cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func groupBy(_ block: (M.CDQIAttribute) -> [PropertyConvertible]) -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToGroupBy ??= [] builder.propertiesToGroupBy!.append(contentsOf: block(M.CDQIAttribute()).map{ $0.cdqiProperty }) return Query<M, NSDictionary>(builder: builder) } public func regroup() -> Query<M, NSDictionary> { var builder = self.builder builder.resultType = .dictionaryResultType builder.propertiesToGroupBy = nil return Query<M, NSDictionary>(builder: builder) } public func order<O: Sequence>(ascending: Bool, _ sortDescriptors: O) -> Query<M, R> where O.Iterator.Element: SortDescriptorConvertible { var builder = self.builder builder.sortDescriptors.append(contentsOf: sortDescriptors.map{ $0.cdqiSortDescriptor(ascending: ascending) }) return Query<M, R>(builder: builder) } public func order<O: Sequence>(_ sortDescriptors: O) -> Query<M, R> where O.Iterator.Element: SortDescriptorConvertible { return order(ascending: true, sortDescriptors) } public func order(ascending: Bool, _ sortDescriptors: SortDescriptorConvertible...) -> Query<M, R> { var builder = self.builder builder.sortDescriptors.append(contentsOf: sortDescriptors.map{ $0.cdqiSortDescriptor(ascending: ascending) }) return Query<M, R>(builder: builder) } public func order(_ sortDescriptors: SortDescriptorConvertible...) -> Query<M, R> { var builder = self.builder builder.sortDescriptors.append(contentsOf: sortDescriptors.map{ $0.cdqiSortDescriptor(ascending: true) }) return Query<M, R>(builder: builder) } public func order(ascending: Bool = true, _ blocks: ((M.CDQIAttribute) -> SortDescriptorConvertible)...) -> Query<M, R> { var builder = self.builder let attribute = M.CDQIAttribute() builder.sortDescriptors.append(contentsOf: blocks.map { $0(attribute).cdqiSortDescriptor(ascending: ascending) }) return Query<M, R>(builder: builder) } public func order(ascending: Bool = true, _ block: (M.CDQIAttribute) -> [SortDescriptorConvertible]) -> Query<M, R> { var builder = self.builder builder.sortDescriptors.append(contentsOf: block(M.CDQIAttribute()).map{ $0.cdqiSortDescriptor(ascending: ascending) }) return Query<M, R>(builder: builder) } public func reorder() -> Query<M, R> { var builder = self.builder builder.sortDescriptors = [] return Query<M, R>(builder: builder) } public func objects() -> Query<M, M> { var builder = self.builder builder.propertiesToFetch = nil builder.propertiesToGroupBy = nil builder.resultType = .managedObjectResultType return Query<M, M>(builder: builder) } public func ids() -> Query<M, NSManagedObjectID> { var builder = self.builder builder.propertiesToFetch = nil builder.propertiesToGroupBy = nil builder.resultType = .managedObjectIDResultType return Query<M, NSManagedObjectID>(builder: builder) } public func limit(_ fetchLimit: Int) -> Query<M, R> { var builder = self.builder builder.fetchLimit = fetchLimit return Query<M, R>(builder: builder) } public func offset(_ fetchOffset: Int) -> Query<M, R> { var builder = self.builder builder.fetchOffset = fetchOffset return Query<M, R>(builder: builder) } public func distinct(_ distinct: Bool = true) -> Query<M, NSDictionary> { var builder = self.builder builder.returnsDistinctResults = distinct builder.resultType = .dictionaryResultType return Query<M, NSDictionary>(builder: builder) } public func request(managedObjectContext: NSManagedObjectContext) -> NSFetchRequest<R> { if #available(iOS 10, macOS 10.12, tvOS 10, watchOS 3, *) { return builder.request() } else { let managedObjectModel = managedObjectContext.persistentStoreCoordinator!.managedObjectModel return builder.request(managedObjectModel: managedObjectModel) } } @available(iOS 10, macOS 10.12, tvOS 10, watchOS 3, *) public func request() -> NSFetchRequest<R> { return builder.request() } @available(*, deprecated: 5.0) public func request(managedObjectModel: NSManagedObjectModel) -> NSFetchRequest<R> { return builder.request(managedObjectModel: managedObjectModel) } public func count(managedObjectContext: NSManagedObjectContext? = nil) throws -> Int { var builder = self.builder builder.resultType = .countResultType let managedObjectContext = managedObjectContext ?? builder.managedObjectContext! return try managedObjectContext.count(for: request(managedObjectContext: managedObjectContext)) } public func first(managedObjectContext: NSManagedObjectContext? = nil) throws -> R? { let results = try limit(1).all(managedObjectContext: managedObjectContext) assert(results.count < 2) return results.count == 0 ? nil : results[0] } public func all(managedObjectContext: NSManagedObjectContext? = nil) throws -> [R] { let managedObjectContext = managedObjectContext ?? builder.managedObjectContext! return try managedObjectContext.fetch(request(managedObjectContext: managedObjectContext)) } public func array<T>(_ property: PropertyConvertible, managedObjectContext: NSManagedObjectContext? = nil) throws -> [T] { let results: [NSDictionary] = try reselect().select(property).all(managedObjectContext: managedObjectContext) if results.count == 0 { return [] } let key = results[0].allKeys[0] return results.map { $0[key]! as! T } } public func array<T>(managedObjectContext: NSManagedObjectContext? = nil, _ block: (M.CDQIAttribute) -> PropertyConvertible) throws -> [T] { return try array(block(M.CDQIAttribute()), managedObjectContext: managedObjectContext) } public func value<T>(_ property: PropertyConvertible, managedObjectContext: NSManagedObjectContext? = nil) throws -> T? { let results: [T] = try limit(1).array(property) return results.count == 0 ? nil : results[0] } public func value<T>(managedObjectContext: NSManagedObjectContext? = nil, _ block: (M.CDQIAttribute) -> PropertyConvertible) throws -> T? { return try value(block(M.CDQIAttribute()), managedObjectContext: managedObjectContext) } public func exists(managedObjectContext: NSManagedObjectContext? = nil) throws -> Bool { return try limit(1).count(managedObjectContext: managedObjectContext) > 0 } }
mit
b8e4041e955c73e9a720ad8a553b4af1
42.748092
144
0.663671
4.904579
false
false
false
false
cfilipov/MuscleBook
MuscleBook/MuscleMovementCoder.swift
1
5326
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation private func objectToMovement(obj: AnyObject, _ classification: MuscleMovement.Classification, _ exerciseID: Int64) -> MuscleMovement { var muscle: Muscle? = nil if let muscleID = obj as? NSInteger { muscle = Muscle(rawValue: Int64(muscleID)) } var muscleName: String? = nil if let name = obj as? NSString { muscleName = String(name) } return MuscleMovement( muscleMovementID: nil, exerciseID: exerciseID, classification: classification, muscleName: muscle?.name ?? muscleName!, muscle: muscle ) } @objc class MuscleMovementCoder: NSObject, NSCoding { let target: NSArray let agonists: NSArray? let antagonists: NSArray? let synergists: NSArray? let stabilizers: NSArray? let dynamicStabilizers: NSArray? let antagonistStabilizers: NSArray? let other: NSArray? required init?(coder aDecoder: NSCoder) { self.target = (aDecoder.decodeObjectForKey("Target") as? NSArray) ?? [] self.agonists = aDecoder.decodeObjectForKey("Agonists") as? NSArray self.antagonists = aDecoder.decodeObjectForKey("Antagonists") as? NSArray self.synergists = aDecoder.decodeObjectForKey("Synergists") as? NSArray self.stabilizers = aDecoder.decodeObjectForKey("Stabilizers") as? NSArray self.dynamicStabilizers = aDecoder.decodeObjectForKey("Dynamic Stabilizers") as? NSArray self.antagonistStabilizers = aDecoder.decodeObjectForKey("Antagonist Stabilizer") as? NSArray self.other = aDecoder.decodeObjectForKey("Other") as? NSArray } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.target, forKey: "Target") if let agonists = self.agonists { aCoder.encodeObject(agonists, forKey: "Agonists") } if let antagonists = self.antagonists { aCoder.encodeObject(antagonists, forKey: "Antagonists") } if let synergists = self.synergists { aCoder.encodeObject(synergists, forKey: "Synergists") } if let stabilizers = self.stabilizers { aCoder.encodeObject(stabilizers, forKey: "Stabilizers") } if let dynamicStabilizers = self.dynamicStabilizers { aCoder.encodeObject(dynamicStabilizers, forKey: "Dynamic Stabilizers") } if let antagonistStabilizer = self.antagonistStabilizers { aCoder.encodeObject(antagonistStabilizer, forKey: "Antagonist Stabilizers") } if let other = self.other { aCoder.encodeObject(other, forKey: "Other") } } init(movements: [MuscleMovement]) { var dict: [MuscleMovement.Classification: NSMutableArray] = [:] for movement in movements { let items = (dict[movement.classification] ?? NSMutableArray()) if let muscle = movement.muscle { items.addObject(Int(muscle.rawValue)) } else { items.addObject(movement.muscleName) } dict[movement.classification] = items } self.target = dict[MuscleMovement.Classification.Target] ?? [] self.agonists = dict[MuscleMovement.Classification.Agonist] self.antagonists = dict[MuscleMovement.Classification.Antagonist] self.synergists = dict[MuscleMovement.Classification.Synergist] self.stabilizers = dict[MuscleMovement.Classification.Stabilizer] self.dynamicStabilizers = dict[MuscleMovement.Classification.DynamicStabilizer] self.antagonistStabilizers = dict[MuscleMovement.Classification.AntagonistStabilizer] self.other = dict[MuscleMovement.Classification.Other] } func muscleMovements(exerciseID: Int64) -> [MuscleMovement] { var movement: [MuscleMovement] = [] target.forEach { movement.append(objectToMovement($0, .Target, exerciseID)) } agonists?.forEach { movement.append(objectToMovement($0, .Agonist, exerciseID)) } antagonists?.forEach { movement.append(objectToMovement($0, .Antagonist, exerciseID)) } synergists?.forEach { movement.append(objectToMovement($0, .Synergist, exerciseID)) } stabilizers?.forEach { movement.append(objectToMovement($0, .Stabilizer, exerciseID)) } dynamicStabilizers?.forEach { movement.append(objectToMovement($0, .DynamicStabilizer, exerciseID)) } antagonistStabilizers?.forEach { movement.append(objectToMovement($0, .AntagonistStabilizer, exerciseID)) } other?.forEach { movement.append(objectToMovement($0, .Other, exerciseID)) } return movement } }
gpl-3.0
f33064429975059db4f93acb4a213e73
43.383333
135
0.689448
4.755357
false
false
false
false
briandw/SwiftPack
SwiftPack/Packer.swift
2
7788
// // Packer.swift // SwiftPack // // Created by brian on 7/1/14. // Copyright (c) 2014 RantLab. All rights reserved. // import Foundation import SwiftPack public class Packer { //@todo research the most effiecant array type for this class func pack(thing:Any) -> [UInt8] { return pack(thing, bytes: Array<UInt8>()) } class func pack(thing:Any, bytes:[UInt8]) -> [UInt8] { var localBytes = bytes switch thing { case let string as String: localBytes = packString(string, bytes: bytes) case let dictionary as Dictionary<String, Any>: localBytes = packDictionary(dictionary, bytes: bytes) case let array as Array<Any>: localBytes = packArray(array, bytes: bytes) case let uint as UInt: localBytes = packUInt(UInt64(uint), bytes: bytes) case let int as Int: localBytes = packInt(int, bytes: bytes) case let float as Float: localBytes = packFloat(float, bytes: bytes) case let double as Double: localBytes = packDouble(double, bytes: bytes) case let binary as [UInt8]: localBytes = packBin(binary, bytes: bytes) case let bool as Bool: let value: UInt8 = bool ? 0xc3 : 0xc2 localBytes = [value] default: println("Error: Can't pack type") } return localBytes } class func packUInt(var uint:UInt64, bytes:[UInt8]) -> [UInt8] { var size:Int! var formatByte: UInt8! switch uint { case 0...127: return [UInt8(uint)] case UInt64(UInt8.min)...UInt64(UInt8.max): size = sizeof(UInt8.self) formatByte = 0xcc case UInt64(UInt16.min)...UInt64(UInt16.max): size = sizeof(UInt16.self) formatByte = 0xcd case UInt64(UInt32.min)...UInt64(UInt32.max): size = sizeof(Int32.self) formatByte = 0xce default: size = sizeof(UInt64.self) formatByte = 0xcf } var data = [UInt8](count: size, repeatedValue: 0) memcpy(&data, &uint, size) return [formatByte] + data.reverse() } class func packInt(var int:Int, bytes:[UInt8]) -> [UInt8] { var size:Int! var formatByte: UInt8! switch int { case -32..<0, 0...127: return unsafeBitCast([int], [UInt8].self) case Int(Int8.min)...Int(Int8.max): size = sizeof(Int8.self) formatByte = 0xd0 case Int(Int16.min)...Int(Int16.max): size = sizeof(Int16.self) formatByte = 0xd1 case Int(Int32.min)...Int(Int32.max): size = sizeof(Int32.self) formatByte = 0xd2 default: size = sizeof(Int64.self) formatByte = 0xd3 } var data = [Int8](count: size, repeatedValue: 0) memcpy(&data, &int, size) return [formatByte] + unsafeBitCast(reverse(data), [UInt8].self) } class func packFloat(float:Float, bytes:[UInt8]) -> [UInt8] { var localFloat = float var localBytes:Array<UInt8> = bytes localBytes.append(0xCA) return copyBytes(localFloat, length: 4, bytes: localBytes) } class func packDouble(double:Double, bytes:[UInt8]) -> [UInt8] { let localBytes:Array<UInt8> = copyBytes(double, length: sizeof(Double), bytes: bytes) return [0xCB] + localBytes.reverse() } class func packBin(bin:[UInt8], bytes:[UInt8]) -> [UInt8] { var localBytes:Array<UInt8> = bytes let length = Int32(count(bin)) if (length < 0x10) { localBytes.append(UInt8(0xC4)) } else if (length < 0x100) { localBytes.append(UInt8(0xC5)) } else { localBytes.append(UInt8(0xC6)) } localBytes += lengthBytes(length) localBytes += bin return localBytes } class func packString(string:String, bytes:[UInt8]) -> [UInt8] { var localBytes:Array<UInt8> = bytes var stringBuff = [UInt8]() stringBuff += string.utf8 var length = stringBuff.count if (length < 0x20) { localBytes.append(UInt8(0xA0 | UInt8(length))) } else { if (length < 0x10) { localBytes.append(UInt8(0xD9)) } else if (length < 0x100) { localBytes.append(UInt8(0xDA)) } else { localBytes.append(UInt8(0xDB)) } localBytes += lengthBytes(Int32(length)) } localBytes += stringBuff return localBytes } class func packArray(array:Array<Any>, bytes:[UInt8]) -> [UInt8] { var localBytes = bytes var items = Int32(count(array)) if (items < 0x10) { localBytes.append(UInt8(0x90 | UInt8(items))) } else { if (items < 0x100) { localBytes.append(UInt8(0xDC)) } else { localBytes.append(UInt8(0xDD)) } localBytes += lengthBytes(items) } for item in array { localBytes += pack(item, bytes: localBytes) } return localBytes } class func packDictionary(dict:Dictionary<String, Any>, bytes:[UInt8]) -> [UInt8] { var localBytes = bytes var elements = Int32(count(dict)) if (elements < 0x10) { localBytes.append(UInt8(0x80 | UInt8(elements))) } else { if (elements < 0x100) { localBytes.append(UInt8(0xDE)) } else { localBytes.append(UInt8(0xDF)) } localBytes += lengthBytes(elements) } for (key, value) in dict { localBytes = pack(key, bytes: localBytes) localBytes = pack(value, bytes: localBytes) } return localBytes } class func lengthBytes(lengthIn:Int32) -> Array<UInt8> { var length:CLong = CLong(lengthIn) var lengthBytes:Array<UInt8> = Array<UInt8>() switch (length) { case 0..<0x10: lengthBytes.append(UInt8(length)) case 0x10..<0x100: lengthBytes = Array<UInt8>(count:2, repeatedValue:0) memcpy(&lengthBytes, &length, 2) lengthBytes = lengthBytes.reverse() case 0x100..<0x10000: lengthBytes = Array<UInt8>(count:4, repeatedValue:0) memcpy(&lengthBytes, &length, 4) lengthBytes = lengthBytes.reverse() default: error("Unknown length") } return lengthBytes } class func copyBytes<T>(value:T, length:Int, bytes:[UInt8]) -> [UInt8] { var localValue = value var localBytes:Array<UInt8> = bytes var intBytes:Array<UInt8> = Array<UInt8>(count:length, repeatedValue:0) memcpy(&intBytes, &localValue, Int(length)) localBytes += intBytes return localBytes } }
mit
8b39fda9b50c40795fc68dc4e70fbea7
25.674658
93
0.501284
4.321865
false
false
false
false
xwu/swift
test/Concurrency/actor_call_implicitly_async.swift
1
21853
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency // REQUIRES: concurrency // some utilities func thrower() throws {} func asyncer() async {} func rethrower(_ f : @autoclosure () throws -> Any) rethrows -> Any { return try f() } func asAutoclosure(_ f : @autoclosure () -> Any) -> Any { return f() } // not a concurrency-safe type class Box { // expected-note 4{{class 'Box' does not conform to the 'Sendable' protocol}} var counter : Int = 0 } actor BankAccount { private var curBalance : Int private var accountHolder : String = "unknown" // expected-note@+1 {{mutation of this property is only permitted within the actor}} var owner : String { get { accountHolder } set { accountHolder = newValue } } init(initialDeposit : Int) { curBalance = initialDeposit } func balance() -> Int { return curBalance } // expected-note@+1 {{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} func deposit(_ amount : Int) -> Int { guard amount >= 0 else { return 0 } curBalance = curBalance + amount return curBalance } func canWithdraw(_ amount : Int) -> Bool { // call 'balance' from sync through self return self.balance() >= amount } func testSelfBalance() async { _ = await balance() // expected-warning {{no 'async' operations occur within 'await' expression}} } // returns the amount actually withdrawn func withdraw(_ amount : Int) -> Int { guard canWithdraw(amount) else { return 0 } curBalance = curBalance - amount return amount } // returns the balance of this account following the transfer func transferAll(from : BankAccount) async -> Int { // call sync methods on another actor let amountTaken = await from.withdraw(from.balance()) return deposit(amountTaken) } func greaterThan(other : BankAccount) async -> Bool { return await balance() > other.balance() } func testTransactions() { _ = deposit(withdraw(deposit(withdraw(balance())))) } func testThrowing() throws {} var effPropA : Box { get async { await asyncer() return Box() } } var effPropT : Box { get throws { try thrower() return Box() } } var effPropAT : Int { get async throws { await asyncer() try thrower() return 0 } } // expected-note@+1 2 {{add 'async' to function 'effPropertiesFromInsideActorInstance()' to make it asynchronous}} func effPropertiesFromInsideActorInstance() throws { // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropA // expected-note@+4{{did you mean to handle error as optional value?}} // expected-note@+3{{did you mean to use 'try'?}} // expected-note@+2{{did you mean to disable error propagation?}} // expected-error@+1{{property access can throw but is not marked with 'try'}} _ = effPropT _ = try effPropT // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{property access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(effPropT) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try effPropT) _ = try rethrower(effPropT) _ = try rethrower(thrower()) _ = try rethrower(try effPropT) _ = try rethrower(try thrower()) _ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}} _ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropAT } } // end actor func someAsyncFunc() async { let deposit1 = 120, deposit2 = 45 let a = BankAccount(initialDeposit: 0) let b = BankAccount(initialDeposit: deposit2) let _ = await a.deposit(deposit1) let afterXfer = await a.transferAll(from: b) let reportedBal = await a.balance() // check on account A guard afterXfer == (deposit1 + deposit2) && afterXfer == reportedBal else { print("BUG 1!") return } // check on account B guard await b.balance() == 0 else { print("BUG 2!") return } _ = await a.deposit(b.withdraw(a.deposit(b.withdraw(b.balance())))) // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}} a.testSelfBalance() await a.testThrowing() // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}} //////////// // effectful properties from outside the actor instance // expected-warning@+2 {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropA // expected-warning@+3 {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}} // expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropT // expected-error@+2{{property access can throw, but it is not marked with 'try' and the error is not handled}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = a.effPropAT // (mostly) corrected ones _ = await a.effPropA // expected-warning {{cannot use property 'effPropA' with a non-sendable type 'Box' across actors}} _ = try! await a.effPropT // expected-warning {{cannot use property 'effPropT' with a non-sendable type 'Box' across actors}} _ = try? await a.effPropAT print("ok!") } ////////////////// // check for appropriate error messages ////////////////// extension BankAccount { func totalBalance(including other: BankAccount) async -> Int { //expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{12-12=await }} return balance() + other.balance() // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} } func breakAccounts(other: BankAccount) async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} _ = other.deposit( // expected-note{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}} self.deposit( other.withdraw( // expected-note{{calls to instance method 'withdraw' from outside of its actor context are implicitly asynchronous}} other.balance())))) // expected-note{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} } } func anotherAsyncFunc() async { let a = BankAccount(initialDeposit: 34) let b = BankAccount(initialDeposit: 35) // expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} // expected-note@+1{{calls to instance method 'deposit' from outside of its actor context are implicitly asynchronous}} _ = a.deposit(1) // expected-error@+2{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} // expected-note@+1{{calls to instance method 'balance()' from outside of its actor context are implicitly asynchronous}} _ = b.balance() _ = b.balance // expected-error {{actor-isolated instance method 'balance()' can not be partially applied}} a.owner = "cat" // expected-error{{actor-isolated property 'owner' can not be mutated from a non-isolated context}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{7-7=await }} expected-note@+1{{property access is 'async'}} _ = b.owner _ = await b.owner == "cat" } func regularFunc() { let a = BankAccount(initialDeposit: 34) _ = a.deposit //expected-error{{actor-isolated instance method 'deposit' can not be partially applied}} _ = a.deposit(1) // expected-error{{actor-isolated instance method 'deposit' can not be referenced from a non-isolated context}} } actor TestActor {} @globalActor struct BananaActor { static var shared: TestActor { TestActor() } } @globalActor struct OrangeActor { static var shared: TestActor { TestActor() } } func blender(_ peeler : () -> Void) { peeler() } // expected-note@+2 {{var declared here}} // expected-note@+1 2 {{mutation of this var is only permitted within the actor}} @BananaActor var dollarsInBananaStand : Int = 250000 @BananaActor func wisk(_ something : Any) { } @BananaActor func peelBanana() { } @BananaActor func takeInout(_ x : inout Int) {} @OrangeActor func makeSmoothie() async { var money = await dollarsInBananaStand money -= 1200 dollarsInBananaStand = money // expected-error{{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be mutated from different global actor 'OrangeActor'}} // FIXME: these two errors seem a bit redundant. // expected-error@+2 {{actor-isolated var 'dollarsInBananaStand' cannot be passed 'inout' to implicitly 'async' function call}} // expected-error@+1 {{var 'dollarsInBananaStand' isolated to global actor 'BananaActor' can not be used 'inout' from different global actor 'OrangeActor'}} await takeInout(&dollarsInBananaStand) _ = wisk await wisk({}) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await wisk(1) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await (peelBanana)() await (((((peelBanana)))))() await (((wisk)))((wisk)((wisk)(1))) // expected-warning@-1 3{{cannot pass argument of non-sendable type 'Any' across actors}} blender((peelBanana)) // expected-error@-1{{converting function value of type '@BananaActor () -> ()' to '() -> Void' loses global actor 'BananaActor'}} await wisk(peelBanana) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await wisk(wisk) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} await (((wisk)))(((wisk))) // expected-warning@-1{{cannot pass argument of non-sendable type 'Any' across actors}} // expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}} await {wisk}()(1) // expected-warning@+1 {{cannot pass argument of non-sendable type 'Any' across actors}} await (true ? wisk : {n in return})(1) } actor Chain { var next : Chain? } func walkChain(chain : Chain) async { // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 4 {{property access is 'async'}} _ = chain.next?.next?.next?.next // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 3 {{property access is 'async'}} _ = (await chain.next)?.next?.next?.next // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 2 {{property access is 'async'}} _ = (await chain.next?.next)?.next?.next } // want to make sure there is no note about implicitly async on this func. @BananaActor func rice() async {} @OrangeActor func quinoa() async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }} expected-note@+1 {{call is 'async'}} rice() } /////////// // check various curried applications to ensure we mark the right expression. actor Calculator { func addCurried(_ x : Int) -> ((Int) -> Int) { return { (_ y : Int) in x + y } } func add(_ x : Int, _ y : Int) -> Int { return x + y } } @BananaActor func bananaAdd(_ x : Int) -> ((Int) -> Int) { return { (_ y : Int) in x + y } } @OrangeActor func doSomething() async { let _ = (await bananaAdd(1))(2) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = await (await bananaAdd(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}} // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let calc = Calculator() let _ = (await calc.addCurried(1))(2) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = await (await calc.addCurried(1))(2) // expected-warning{{no 'async' operations occur within 'await' expression}} // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let plusOne = await calc.addCurried(await calc.add(0, 1)) // expected-warning@-1{{cannot call function returning non-sendable type}} // expected-note@-2{{a function type must be marked '@Sendable' to conform to 'Sendable'}} let _ = plusOne(2) } /////// // Effectful properties isolated to a global actor @BananaActor var effPropA : Int { get async { await asyncer() try thrower() // expected-error{{errors thrown from here are not handled}} return 0 } } @BananaActor var effPropT : Int { // expected-note{{var declared here}} get throws { await asyncer() // expected-error{{'async' call in a function that does not support concurrency}} try thrower() return 0 } } @BananaActor var effPropAT : Int { get async throws { await asyncer() try thrower() return 0 } } // expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromBanana()' to make it asynchronous}} @BananaActor func tryEffPropsFromBanana() throws { // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropA // expected-note@+4{{did you mean to handle error as optional value?}} // expected-note@+3{{did you mean to use 'try'?}} // expected-note@+2{{did you mean to disable error propagation?}} // expected-error@+1{{property access can throw but is not marked with 'try'}} _ = effPropT _ = try effPropT // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{property access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(effPropT) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try effPropT) _ = try rethrower(effPropT) _ = try rethrower(thrower()) _ = try rethrower(try effPropT) _ = try rethrower(try thrower()) _ = rethrower(effPropA) // expected-error{{'async' property access in an autoclosure that does not support concurrency}} _ = asAutoclosure(effPropT) // expected-error{{property access can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{'async' property access in a function that does not support concurrency}} _ = effPropAT } // expected-note@+2 {{add '@BananaActor' to make global function 'tryEffPropsFromSync()' part of global actor 'BananaActor'}} // expected-note@+1 2 {{add 'async' to function 'tryEffPropsFromSync()' to make it asynchronous}} func tryEffPropsFromSync() { _ = effPropA // expected-error{{'async' property access in a function that does not support concurrency}} // expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}} _ = effPropT // expected-error{{var 'effPropT' isolated to global actor 'BananaActor' can not be referenced from this synchronous context}} // NOTE: that we don't complain about async access on `effPropT` because it's not declared async, and we're not in an async context! // expected-error@+1 {{property access can throw, but it is not marked with 'try' and the error is not handled}} _ = effPropAT // expected-error{{'async' property access in a function that does not support concurrency}} } @OrangeActor func tryEffPropertiesFromGlobalActor() async throws { // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropA // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropT // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{property access can throw but is not marked with 'try'}} // expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{property access is 'async'}} _ = effPropAT _ = await effPropA _ = try? await effPropT _ = try! await effPropAT } ///////////// // check subscripts in actors actor SubscriptA { subscript(_ i : Int) -> Int { get async { try thrower() // expected-error{{errors thrown from here are not handled}} await asyncer() return 0 } } func f() async { // expected-error@+1{{expression is 'async' but is not marked with 'await'}} {{9-9=await }} expected-note@+1{{subscript access is 'async'}} _ = self[0] } } actor SubscriptT { subscript(_ i : Int) -> Int { get throws { try thrower() await asyncer() // expected-error{{'async' call in a function that does not support concurrency}} return 0 } } func f() throws { _ = try self[0] // expected-note@+6 {{did you mean to handle error as optional value?}} // expected-note@+5 {{did you mean to use 'try'?}} // expected-note@+4 {{did you mean to disable error propagation?}} // expected-error@+3 {{subscript access can throw but is not marked with 'try'}} // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(self[1]) // expected-note@+2 {{call is to 'rethrows' function, but argument function can throw}} // expected-error@+1 {{call can throw but is not marked with 'try'}} _ = rethrower(try self[1]) _ = try rethrower(self[1]) _ = try rethrower(try self[1]) } } actor SubscriptAT { subscript(_ i : Int) -> Int { get async throws { try thrower() await asyncer() return 0 } } func f() async throws { _ = try await self[0] } } func tryTheActorSubscripts(a : SubscriptA, t : SubscriptT, at : SubscriptAT) async throws { // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = a[0] _ = await a[0] // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{subscript access can throw but is not marked with 'try'}} // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = t[0] _ = try await t[0] _ = try! await t[0] _ = try? await t[0] // expected-note@+5{{did you mean to handle error as optional value?}} // expected-note@+4{{did you mean to use 'try'?}} // expected-note@+3{{did you mean to disable error propagation?}} // expected-error@+2{{subscript access can throw but is not marked with 'try'}} // expected-error@+1 {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} expected-note@+1 {{subscript access is 'async'}} _ = at[0] _ = try await at[0] }
apache-2.0
ddb33fe3fee33b5a9ccea338c80573cd
36.74266
178
0.671029
3.956726
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Weather List Scene/WeatherListViewController.swift
1
7729
// // WeatherListViewController.swift // NearbyWeather // // Created by Erik Maximilian Martens on 04.05.20. // Copyright © 2020 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension WeatherListViewController { struct Definitions {} } // MARK: - Class Definition final class WeatherListViewController: UIViewController, BaseViewController { typealias ViewModel = WeatherListViewModel // MARK: - UIComponents fileprivate lazy var listTypeBarButton = Factory.BarButtonItem.make(fromType: .systemImageWithCircle(imageName: "checklist")) fileprivate lazy var sortingOrientationBarButton = Factory.BarButtonItem.make(fromType: .systemImageWithCircle(imageName: "arrow.up.arrow.down")) fileprivate lazy var amountOfResultsBarButton10 = Factory.BarButtonItem.make(fromType: .systemImageWithCircle( imageName: "10.circle.fill", paletteColors: [Constants.Theme.Color.MarqueColors.standardMarque, .clear] )) fileprivate lazy var amountOfResultsBarButton20 = Factory.BarButtonItem.make(fromType: .systemImageWithCircle( imageName: "20.circle.fill", paletteColors: [Constants.Theme.Color.MarqueColors.standardMarque, .clear] )) fileprivate lazy var amountOfResultsBarButton30 = Factory.BarButtonItem.make(fromType: .systemImageWithCircle( imageName: "30.circle.fill", paletteColors: [Constants.Theme.Color.MarqueColors.standardMarque, .clear] )) fileprivate lazy var amountOfResultsBarButton40 = Factory.BarButtonItem.make(fromType: .systemImageWithCircle( imageName: "40.circle.fill", paletteColors: [Constants.Theme.Color.MarqueColors.standardMarque, .clear] )) fileprivate lazy var amountOfResultsBarButton50 = Factory.BarButtonItem.make(fromType: .systemImageWithCircle( imageName: "50.circle.fill", paletteColors: [Constants.Theme.Color.MarqueColors.standardMarque, .clear] )) fileprivate lazy var tableView = Factory.TableView.make(fromType: .standard(frame: view.frame)) // MARK: - Assets private let disposeBag = DisposeBag() // MARK: - Properties let viewModel: ViewModel // MARK: - Initialization required init(dependencies: ViewModel.Dependencies) { viewModel = WeatherListViewModel(dependencies: dependencies) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } // MARK: - ViewController LifeCycle override func viewDidLoad() { super.viewDidLoad() viewModel.viewDidLoad() setupUiComponents() setupBindings() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel.viewWillAppear() setupUiAppearance() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewModel.viewWillDisappear() tableView.refreshControl?.endRefreshing() } } // MARK: - ViewModel Bindings extension WeatherListViewController { func setupBindings() { viewModel.observeEvents() bindContentFromViewModel(viewModel) bindUserInputToViewModel(viewModel) } func bindContentFromViewModel(_ viewModel: ViewModel) { viewModel .tableDataSource .sectionDataSources .map { _ in () } .asDriver(onErrorJustReturn: ()) .drive(onNext: { [weak tableView] in tableView?.reloadData() }) .disposed(by: disposeBag) Observable .combineLatest( viewModel.preferredListTypeDriver.asObservable(), viewModel.preferredAmountOfResultsDriver.asObservable(), resultSelector: { ($0, $1) } ) .asDriver(onErrorJustReturn: (ListTypeOptionValue.bookmarked, AmountOfResultsOptionValue.ten)) .drive(onNext: { [unowned self] result in guard result.0 != .bookmarked else { self.navigationItem.rightBarButtonItems = [] return } switch result.1 { case .ten: self.navigationItem.rightBarButtonItems = [self.amountOfResultsBarButton10, self.sortingOrientationBarButton] case .twenty: self.navigationItem.rightBarButtonItems = [self.amountOfResultsBarButton20, self.sortingOrientationBarButton] case .thirty: self.navigationItem.rightBarButtonItems = [self.amountOfResultsBarButton30, self.sortingOrientationBarButton] case .forty: self.navigationItem.rightBarButtonItems = [self.amountOfResultsBarButton40, self.sortingOrientationBarButton] case .fifty: self.navigationItem.rightBarButtonItems = [self.amountOfResultsBarButton50, self.sortingOrientationBarButton] } }) .disposed(by: disposeBag) viewModel .isRefreshingDriver .drive(onNext: { [weak tableView] isRefreshing in isRefreshing ? tableView?.refreshControl?.beginRefreshing() : tableView?.refreshControl?.endRefreshing() }) .disposed(by: disposeBag) } func bindUserInputToViewModel(_ viewModel: ViewModel) { listTypeBarButton.rx .tap .bind(to: viewModel.onDidTapListTypeBarButtonSubject) .disposed(by: disposeBag) Observable .merge( amountOfResultsBarButton10.rx.tap.asObservable(), amountOfResultsBarButton20.rx.tap.asObservable(), amountOfResultsBarButton30.rx.tap.asObservable(), amountOfResultsBarButton40.rx.tap.asObservable(), amountOfResultsBarButton50.rx.tap.asObservable() ) .bind(to: viewModel.onDidTapAmountOfResultsBarButtonSubject) .disposed(by: disposeBag) sortingOrientationBarButton.rx .tap .bind(to: viewModel.onDidTapSortingOrientationBarButtonSubject) .disposed(by: disposeBag) tableView.refreshControl?.rx .controlEvent(.valueChanged) .bind(to: viewModel.onDidPullToRefreshSubject) .disposed(by: disposeBag) } } // MARK: - Setup private extension WeatherListViewController { func setupUiComponents() { navigationItem.leftBarButtonItems = [listTypeBarButton] tableView.dataSource = viewModel.tableDataSource tableView.delegate = viewModel.tableDelegate tableView.refreshControl = UIRefreshControl() tableView.registerCells([ WeatherListInformationTableViewCell.self, WeatherListAlertTableViewCell.self ]) tableView.contentInset = UIEdgeInsets( top: .zero, left: .zero, bottom: Constants.Dimensions.TableCellContentInsets.bottom, right: .zero ) view.addSubview(tableView, constraints: [ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } func setupUiAppearance() { navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .automatic DispatchQueue.main.async { self.navigationController?.navigationBar.sizeToFit() } title = R.string.localizable.tab_weatherList() tabBarController?.tabBar.isTranslucent = true navigationController?.navigationBar.isTranslucent = true navigationController?.view.backgroundColor = Constants.Theme.Color.ViewElement.secondaryBackground view.backgroundColor = Constants.Theme.Color.ViewElement.secondaryBackground tableView.separatorStyle = .none tableView.backgroundColor = .clear } }
mit
b0b77e83c780ffb2608a811f45d942c3
32.025641
147
0.721403
5.193548
false
false
false
false
practicalswift/swift
validation-test/compiler_crashers_fixed/02110-swift-modulefile-gettype.swift
65
661
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var b[(with: B>) -> { protocol b = b<c where Optional<d = b(")() -> <r : (bytes: String { class B<T where f{ x in 0) var d { class a { var b { } func a<1 { func r.init(self.i : Any, e<o : Range<d { class m>? = { class a(b[c, " } func a<T : c == { } func c(t: a {
apache-2.0
2b498df292c0a76979aa20b7723bc06f
30.47619
79
0.662632
3.03211
false
false
false
false
argent-os/argent-ios
app-ios/AddCustomerViewController.swift
1
12875
// // AddCustomerViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 3/15/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import UIKit import MessageUI import DKCircleButton import Crashlytics final class AddCustomerViewController: UIViewController, UINavigationBarDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate { // MARK: Public override func viewDidLoad() { super.viewDidLoad() configure() setupNav() } override func prefersStatusBarHidden() -> Bool { return true } // MARK: Private private func setupNav() { let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50)) // Offset by 20 pixels vertically to take the status bar into account navigationBar.backgroundColor = UIColor.clearColor() navigationBar.tintColor = UIColor.whiteColor() navigationBar.delegate = self // Create a navigation item with a title let navigationItem = UINavigationItem() navigationItem.title = "" // Create left and right button for navigation item let leftButton = UIBarButtonItem(image: UIImage(named: "IconClose"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(AddCustomerViewController.returnToMenu(_:))) let font = UIFont.systemFontOfSize(14) leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()], forState: UIControlState.Normal) // Create two buttons for the navigation item navigationItem.leftBarButtonItem = leftButton // Assign the navigation item to the navigation bar navigationBar.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.darkGrayColor()] navigationBar.items = [navigationItem] // Make the navigation bar a subview of the current view controller self.view.addSubview(navigationBar) } override func viewDidAppear(animated: Bool) { // screen width and height: // let screen = UIScreen.mainScreen().bounds //let screenWidth = screen.size.width //let screenHeight = screen.size.height } private func configure() { // screen width and height: let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height // self.view.backgroundColor = UIColor.offWhite() let backgroundImageView = UIImageView(image: UIImage(named: "BackgroundGradientBlueDark"), highlightedImage: nil) backgroundImageView.frame = CGRectMake(0, 0, screenWidth, screenHeight) backgroundImageView.contentMode = .ScaleAspectFill backgroundImageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] backgroundImageView.layer.masksToBounds = true backgroundImageView.clipsToBounds = true // backgroundImageView.addSubview(visualEffectView) self.view.sendSubviewToBack(backgroundImageView) self.view.addSubview(backgroundImageView) let imageView = UIImageView() let imageName = "LogoOutlineGradient" let image = UIImage(named: imageName) imageView.image = image imageView.layer.masksToBounds = true imageView.tag = 7577 imageView.frame = CGRect(x: 0, y: 0, width: 75, height: 75) imageView.frame.origin.y = screenHeight*0.15 imageView.frame.origin.x = (self.view.bounds.size.width - imageView.frame.size.width) / 2.0 // centered left to right. addSubviewWithFade(imageView, parentView: self, duration: 0.3) let lbl = UILabel() // Set range of string length to exactly 8, the number of characters lbl.frame = CGRect(x: 0, y: screenHeight*0.33, width: screenWidth, height: 40) lbl.font = UIFont(name: "SFUIText-Regular", size: 23) lbl.tag = 7578 lbl.textAlignment = NSTextAlignment.Center lbl.textColor = UIColor.whiteColor() lbl.adjustAttributedString("ARGENT", spacing: 4, fontName: "SFUIText-Regular", fontSize: 23, fontColor: UIColor.whiteColor()) addSubviewWithFade(lbl, parentView: self, duration: 0.3) let dividerView = UIImageView() dividerView.image = UIImage(named: "DividerWhite")?.alpha(0.5) dividerView.frame = CGRect(x: 100, y: screenHeight*0.39, width: screenWidth-200, height: 1) addSubviewWithFade(dividerView, parentView: self, duration: 0.3) let lblDetail = UILabel() // Set range of string length to exactly 8, the number of characters lblDetail.frame = CGRect(x: 0, y: screenHeight*0.39, width: screenWidth, height: 40) lblDetail.tag = 7579 lblDetail.textAlignment = NSTextAlignment.Center lblDetail.textColor = UIColor.whiteColor() lblDetail.adjustAttributedString("INVITATION", spacing: 4, fontName: "SFUIText-Regular", fontSize: 13, fontColor: UIColor.whiteColor()) addSubviewWithFade(lblDetail, parentView: self, duration: 0.3) let lblBody = UILabel() // Set range of string length to exactly 8, the number of characters lblBody.frame = CGRect(x: 50, y: screenHeight*0.40, width: screenWidth-100, height: 200) lblBody.numberOfLines = 0 lblBody.alpha = 0.9 lblBody.adjustAttributedString("Spread the joy. Invite new users, subscribers, or friends to " + APP_NAME + " today.", spacing: 2, fontName: "HelveticaNeue-Light", fontSize: 14, fontColor: UIColor.whiteColor()) lblBody.tag = 7579 lblBody.textAlignment = NSTextAlignment.Center lblBody.textColor = UIColor.whiteColor() addSubviewWithFade(lblBody, parentView: self, duration: 0.3) let emailButton: DKCircleButton = DKCircleButton(frame: CGRectMake(45, screenHeight-180, 90, 90)) emailButton.center = CGPointMake(self.view.layer.frame.width*0.3, screenHeight-130) emailButton.titleLabel!.font = UIFont.systemFontOfSize(22) emailButton.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.5) emailButton.borderSize = 1 emailButton.tintColor = UIColor.whiteColor() emailButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) let str0 = NSAttributedString(string: "Mail", attributes: [ NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 12)!, NSForegroundColorAttributeName:UIColor.whiteColor() ]) emailButton.setAttributedTitle(str0, forState: .Normal) emailButton.addTarget(self, action: #selector(AddCustomerViewController.sendEmailButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside) let _ = Timeout(0.4) { addSubviewWithFade(emailButton, parentView: self, duration: 0.3) } let smsButton: DKCircleButton = DKCircleButton(frame: CGRectMake(screenWidth/2+45, screenHeight-180, 90, 90)) smsButton.center = CGPointMake(self.view.layer.frame.width*0.7, screenHeight-130) smsButton.titleLabel!.font = UIFont.systemFontOfSize(22) smsButton.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.5) smsButton.borderSize = 1 smsButton.tintColor = UIColor.whiteColor() smsButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) let str1 = NSAttributedString(string: "SMS", attributes: [ NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 12)!, NSForegroundColorAttributeName:UIColor.whiteColor() ]) smsButton.setAttributedTitle(str1, forState: .Normal) smsButton.addTarget(self, action: #selector(AddCustomerViewController.sendSMSButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside) let _ = Timeout(0.4) { addSubviewWithFade(smsButton, parentView: self, duration: 0.3) } self.navigationItem.title = "" self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] } func returnToMenu(sender: AnyObject) { self.view.window!.rootViewController!.dismissViewControllerAnimated(true, completion: { _ in }) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } override func viewWillDisappear(animated: Bool) { dismissKeyboard() super.viewWillDisappear(animated) } } extension AddCustomerViewController { // MARK: Email Composition @IBAction func sendEmailButtonTapped(sender: AnyObject) { Answers.logInviteWithMethod("Email", customAttributes: nil) let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property mailComposerVC.setToRecipients([]) User.getProfile { (user, err) in // if let first_name = user?.first_name where first_name != "" { mailComposerVC.setSubject("Re: Message from " + first_name) mailComposerVC.setMessageBody("Hey it's " + first_name + ". Have you tried " + APP_NAME + "? It's a great app I've been using lately! Sending you the link " + APP_URL, isHTML: false) } else { mailComposerVC.setSubject("Re: Message from " + APP_NAME) mailComposerVC.setMessageBody("Hello from Argent! Check out our app: " + APP_URL, isHTML: false) } } return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert) sendMailErrorAlert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(sendMailErrorAlert, animated: true, completion: nil) } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } } extension AddCustomerViewController { // MARK: SMS Composition @IBAction func sendSMSButtonTapped(sender: AnyObject) { Answers.logInviteWithMethod("SMS", customAttributes: nil) let smsComposeViewController = configuredSMSViewController() if !MFMessageComposeViewController.canSendText() { print("SMS services are not available") } else { self.presentViewController(smsComposeViewController, animated: true, completion: nil) } } func configuredSMSViewController() -> MFMessageComposeViewController { let composeSMSVC = MFMessageComposeViewController() composeSMSVC.messageComposeDelegate = self // Configure the fields of the interface. composeSMSVC.recipients = ([]) User.getProfile { (user, err) in // if let first_name = user?.first_name where first_name != "" { composeSMSVC.body = "Hey it's " + first_name + ". Have you tried " + APP_NAME + "? It's a great app I've been using lately! Sending you the link " + APP_URL } else { composeSMSVC.body = "Hello from " + APP_NAME + "!" + " Check out our app: " + APP_URL } } return composeSMSVC } func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) { // Check the result or perform other tasks. // Dismiss the mail compose view controller. controller.dismissViewControllerAnimated(true, completion: nil) } }
mit
a6057466dc194b8e305ca314b754babc
45.648551
218
0.668324
5.29141
false
false
false
false
huonw/swift
validation-test/Sema/type_checker_perf/fast/rdar19029974.swift
14
552
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts infix operator <*> : AdditionPrecedence func <*><A, B>(lhs: ((A) -> B)?, rhs: A?) -> B? { if let lhs1 = lhs, let rhs1 = rhs { return lhs1(rhs1) } return nil } func cons<T, U>(lhs: T) -> (U) -> (T, U) { return { rhs in (lhs, rhs) } } var str: String? = "x" if let f = cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> str)))))) { print("\(f)") }
apache-2.0
9a0de8917b6a61e68ca3e552f5973bbd
28.052632
147
0.527174
2.920635
false
false
false
false
casid/SKBitmapFont
SKBitmapFont/src/BitmapFontLoader.swift
1
2678
import SpriteKit public class BitmapFontLoader : NSObject, NSXMLParserDelegate { let fontName:String let textureName:String let font:BitmapFont public init(fontName:String, textureName:String, font:BitmapFont) { self.fontName = fontName self.textureName = textureName self.font = font super.init() } public func load() { loadTexture() } private func loadTexture() { let texture = SKTexture(imageNamed: textureName) font.texture = texture texture.preloadWithCompletionHandler { () -> Void in self.loadFont() } } private func loadFont() { if let path = NSBundle.mainBundle().pathForResource(fontName, ofType: nil) { if let data = NSData(contentsOfFile: path) { let parser = NSXMLParser(data: data) parser.delegate = self parser.parse() } } font.isLoaded = true } public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if elementName == "char" { let char = parseChar(attributeDict) font.addChar(char) } else if elementName == "common" { font.lineHeight = parseInt(attributeDict["lineHeight"]) } } private func parseChar(attributes: [String : String]) -> BitmapChar { let char = BitmapChar() char.id = parseInt(attributes["id"]) char.x = parseInt(attributes["x"]) char.y = parseInt(attributes["y"]) char.width = parseInt(attributes["width"]) char.height = parseInt(attributes["height"]) char.xOffset = parseInt(attributes["xoffset"]) char.yOffset = parseInt(attributes["yoffset"]) char.xAdvance = parseInt(attributes["xadvance"]) let size = font.texture!.size() let rect = CGRect(x: CGFloat(char.x) / size.width, y: 1 - CGFloat(char.y + char.height) / size.height, width: CGFloat(char.width) / size.width, height: CGFloat(char.height) / size.height) char.texture = SKTexture(rect: rect, inTexture: font.texture!) return char } private func parseInt(value:String?) -> Int { if value != nil { let integerValue = Int(value!) if integerValue != nil { return integerValue! } } return 0 } }
mit
2f144551f8d061f796143cc6542bb942
30.880952
180
0.558999
4.913761
false
false
false
false
huonw/swift
test/SILGen/keypath_property_descriptors.swift
1
2572
// RUN: %target-swift-emit-silgen -enable-key-path-resilience %s | %FileCheck %s // TODO: globals should get descriptors public var a: Int = 0 @inlinable public var b: Int { return 0 } @usableFromInline internal var c: Int = 0 // no descriptor // CHECK-NOT: sil_property #d internal var d: Int = 0 // CHECK-NOT: sil_property #e private var e: Int = 0 public struct A { // CHECK-LABEL: sil_property #A.a public var a: Int = 0 // CHECK-LABEL: sil_property #A.b @inlinable public var b: Int { return 0 } // CHECK-LABEL: sil_property #A.c @usableFromInline internal var c: Int = 0 // no descriptor // CHECK-NOT: sil_property #A.d internal var d: Int = 0 // CHECK-NOT: sil_property #A.e fileprivate var e: Int = 0 // CHECK-NOT: sil_property #A.f private var f: Int = 0 // TODO: static vars should get descriptors public static var a: Int = 0 @inlinable public static var b: Int { return 0 } @usableFromInline internal static var c: Int = 0 // no descriptor // CHECK-NOT: sil_property #A.d internal static var d: Int = 0 // CHECK-NOT: sil_property #A.e fileprivate static var e: Int = 0 // CHECK-NOT: sil_property #A.f private static var f: Int = 0 // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1a public subscript(a x: Int) -> Int { return x } // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1b @inlinable public subscript(b x: Int) -> Int { return x } // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1c @usableFromInline internal subscript(c x: Int) -> Int { return x } // no descriptor // CHECK-NOT: sil_property #A.subscript internal subscript(d x: Int) -> Int { return x } fileprivate subscript(e x: Int) -> Int { return x } private subscript(f x: Int) -> Int { return x } // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1a public subscript<T>(a x: T) -> T { return x } // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1b @inlinable public subscript<T>(b x: T) -> T { return x } // CHECK-LABEL: sil_property #A.subscript{{.*}} id @{{.*}}1c @usableFromInline internal subscript<T>(c x: T) -> T { return x } // no descriptor // CHECK-NOT: sil_property #A.subscript internal subscript<T>(d x: T) -> T { return x } fileprivate subscript<T>(e x: T) -> T { return x } private subscript<T>(f x: T) -> T { return x } // no descriptor public var count: Int { mutating get { _count += 1 return _count } set { _count = newValue } } private var _count: Int = 0 }
apache-2.0
602dbacb23ec355fb62771aa1f4424a9
25.791667
80
0.62014
3.357702
false
false
false
false