repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Wolox/wolmo-core-ios
refs/heads/master
WolmoCoreTests/Extensions/Foundation/RawRepresentableSpec.swift
mit
1
// // RawRepresentable.swift // WolmoCore // // Created by Francisco Depascuali on 7/18/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation import Quick import Nimble import WolmoCore private enum IntRepresentable: Int { case zero case one case two case three } public class RawRepresentableSpec: QuickSpec { override public func spec() { describe("#allValues") { context("When specifying an existent initial value") { it("should return all values starting at the initial value") { let values = Array(IntRepresentable.allValues(startingAt: .one)) expect(values).to(equal([.one, .two, .three])) } context("When the value is the first one") { it("should return all values") { let values = Array(IntRepresentable.allValues(startingAt: .zero)) expect(values).to(equal([.zero, .one, .two, .three])) } } context("When the value is the last one") { it("should return the last value") { let values = Array(IntRepresentable.allValues(startingAt: .three)) expect(values).to(equal([.three])) } } } } describe("#count") { context("When specifying an initial value") { it("should return the count of all the values starting at the initial value") { expect(IntRepresentable.count(startingAt: .one)).to(equal(3)) } context("When the value is the first one") { it("should return the count of all the values") { expect(IntRepresentable.count(startingAt: .zero)).to(equal(4)) } } context("When the value is the last one") { it("should return one") { expect(IntRepresentable.count(startingAt: .three)).to(equal(1)) } } } } } } public class RawRepresentableGeneratorSpec: QuickSpec { override public func spec() { var generator: RawRepresentableGenerator<Int, IntRepresentable>! beforeEach { generator = RawRepresentableGenerator(startingAt: .zero) { $0 } } describe("#next") { context("When using the identity function as generator") { it("should return always the same element") { expect(generator.next()).to(equal(IntRepresentable.zero)) expect(generator.next()).to(equal(IntRepresentable.zero)) } } context("When adding one in the generator") { beforeEach { generator = RawRepresentableGenerator(startingAt: .zero) { IntRepresentable(rawValue: $0.rawValue + 1) } } it("should return the following element until there is no following") { expect(generator.next()).to(equal(IntRepresentable.zero)) expect(generator.next()).to(equal(IntRepresentable.one)) expect(generator.next()).to(equal(IntRepresentable.two)) expect(generator.next()).to(equal(IntRepresentable.three)) expect(generator.next()).to(beNil()) expect(generator.next()).to(beNil()) } } } } }
41e5033f6882ff03b0f0c56e0c948335
37.229167
124
0.518529
false
false
false
false
spothero/SHEmailValidator
refs/heads/master
Sources/SpotHeroEmailValidator/SpotHeroEmailValidator.swift
apache-2.0
1
// Copyright © 2021 SpotHero, Inc. All rights reserved. import Foundation // TODO: Remove NSObject when entirely converted into Swift public class SpotHeroEmailValidator: NSObject { private typealias EmailParts = (username: String, hostname: String, tld: String) public static let shared = SpotHeroEmailValidator() private let commonTLDs: [String] private let commonDomains: [String] private let ianaRegisteredTLDs: [String] override private init() { var dataDictionary: NSDictionary? // All TLDs registered with IANA as of October 8th, 2019 at 11:28 AM CST (latest list at: http://data.iana.org/TLD/tlds-alpha-by-domain.txt) if let plistPath = Bundle.module.path(forResource: "DomainData", ofType: "plist") { dataDictionary = NSDictionary(contentsOfFile: plistPath) } self.commonDomains = dataDictionary?["CommonDomains"] as? [String] ?? [] self.commonTLDs = dataDictionary?["CommonTLDs"] as? [String] ?? [] self.ianaRegisteredTLDs = dataDictionary?["IANARegisteredTLDs"] as? [String] ?? [] } public func validateAndAutocorrect(emailAddress: String) throws -> SHValidationResult { do { // Attempt to get an autocorrect suggestion // As long as no error is thrown, we can consider the email address to have passed validation let autocorrectSuggestion = try self.autocorrectSuggestion(for: emailAddress) return SHValidationResult(passedValidation: true, autocorrectSuggestion: autocorrectSuggestion) } catch { return SHValidationResult(passedValidation: false, autocorrectSuggestion: nil) } } public func autocorrectSuggestion(for emailAddress: String) throws -> String? { // Attempt to validate the syntax of the email address // If the email address has incorrect format or syntax, an error will be thrown try self.validateSyntax(of: emailAddress) // Split the email address into its component parts let emailParts = try self.splitEmailAddress(emailAddress) var suggestedTLD = emailParts.tld if !self.ianaRegisteredTLDs.contains(emailParts.tld), let closestTLD = self.closestString(for: emailParts.tld, fromArray: self.commonTLDs, withTolerance: 0.5) { suggestedTLD = closestTLD } var suggestedDomain = "\(emailParts.hostname).\(suggestedTLD)" if !self.commonDomains.contains(suggestedDomain), let closestDomain = self.closestString(for: suggestedDomain, fromArray: self.commonDomains, withTolerance: 0.25) { suggestedDomain = closestDomain } let suggestedEmailAddress = "\(emailParts.username)@\(suggestedDomain)" guard suggestedEmailAddress != emailAddress else { return nil } return suggestedEmailAddress } @discardableResult public func validateSyntax(of emailAddress: String) throws -> Bool { // Split the email address into parts let emailParts = try self.splitEmailAddress(emailAddress) // Ensure the username is valid by itself guard emailParts.username.isValidEmailUsername() else { throw Error.invalidUsername } // Combine the hostname and TLD into the domain" let domain = "\(emailParts.hostname).\(emailParts.tld)" // Ensure the domain is valid guard domain.isValidEmailDomain() else { throw Error.invalidDomain } // Ensure that the entire email forms a syntactically valid email guard emailAddress.isValidEmail() else { throw Error.invalidSyntax } return true } // TODO: Use better name for array parameter private func closestString(for string: String, fromArray array: [String], withTolerance tolerance: Float) -> String? { guard !array.contains(string) else { return nil } var closestString: String? var closestDistance = Int.max // TODO: Use better name for arrayString parameter for arrayString in array { let distance = Int(string.levenshteinDistance(from: arrayString)) if distance < closestDistance, Float(distance) / Float(string.count) < tolerance { closestDistance = distance closestString = arrayString } } return closestString } private func splitEmailAddress(_ emailAddress: String) throws -> EmailParts { let emailAddressParts = emailAddress.split(separator: "@") guard emailAddressParts.count == 2 else { // There are either no @ symbols or more than one @ symbol, throw an error throw Error.invalidSyntax } // Extract the username from the email address parts let username = String(emailAddressParts.first ?? "") // Extract the full domain (including TLD) from the email address parts let fullDomain = String(emailAddressParts.last ?? "") // Split the domain parts for evaluation let domainParts = fullDomain.split(separator: ".") guard domainParts.count >= 2 else { // There are no periods found in the domain, throw an error throw Error.invalidDomain } // TODO: This logic is wrong and doesn't take subdomains into account. We should compare TLDs against the commonTLDs list." // Extract the domain from the domain parts let domain = domainParts.first?.lowercased() ?? "" // Extract the TLD from the domain parts, which are all the remaining parts joined with a period again let tld = domainParts.dropFirst().joined(separator: ".") return (username, domain, tld) } } // MARK: - Extensions public extension SpotHeroEmailValidator { enum Error: Int, LocalizedError { case blankAddress = 1000 case invalidSyntax = 1001 case invalidUsername = 1002 case invalidDomain = 1003 public var errorDescription: String? { switch self { case .blankAddress: return "The entered email address is blank." case .invalidDomain: return "The domain name section of the entered email address is invalid." case .invalidSyntax: return "The syntax of the entered email address is invalid." case .invalidUsername: return "The username section of the entered email address is invalid." } } } } private extension String { /// RFC 5322 Official Standard Email Regex Pattern /// /// Sources: /// - [How to validate an email address using a regular expression? (Stack Overflow)](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) /// - [What characters are allowed in an email address? (Stack Overflow](https://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-an-email-address) private static let emailRegexPattern = "\(Self.emailUsernameRegexPattern)@\(Self.emailDomainRegexPattern)" // swiftlint:disable:next line_length private static let emailUsernameRegexPattern = #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")"# // swiftlint:disable:next line_length private static let emailDomainRegexPattern = #"(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"# func isValidEmail() -> Bool { return self.range(of: Self.emailRegexPattern, options: .regularExpression) != nil } func isValidEmailUsername() -> Bool { return !self.hasPrefix(".") && !self.hasSuffix(".") && (self as NSString).range(of: "..").location == NSNotFound && self.range(of: Self.emailUsernameRegexPattern, options: .regularExpression) != nil } func isValidEmailDomain() -> Bool { return self.range(of: Self.emailDomainRegexPattern, options: .regularExpression) != nil } }
d7ed6f1e0621236945bcfce55a0a7403
41.627451
342
0.62247
false
false
false
false
mattjgalloway/emoncms-ios
refs/heads/master
EmonCMSiOS/UI/View Controllers/FeedListViewController.swift
mit
1
// // ViewController.swift // EmonCMSiOS // // Created by Matt Galloway on 11/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources final class FeedListViewController: UITableViewController { var viewModel: FeedListViewModel! fileprivate let dataSource = RxTableViewSectionedReloadDataSource<FeedListViewModel.Section>() fileprivate let disposeBag = DisposeBag() fileprivate enum Segues: String { case showFeed } override func viewDidLoad() { super.viewDidLoad() self.title = "Feeds" self.setupDataSource() self.setupBindings() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.viewModel.active.value = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.viewModel.active.value = false } private func setupDataSource() { self.dataSource.configureCell = { (ds, tableView, indexPath, item) in let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) cell.textLabel?.text = item.name cell.detailTextLabel?.text = item.value return cell } self.dataSource.titleForHeaderInSection = { (ds, index) in return ds.sectionModels[index].model } self.tableView.delegate = nil self.tableView.dataSource = nil self.viewModel.feeds .drive(self.tableView.rx.items(dataSource: self.dataSource)) .addDisposableTo(self.disposeBag) } private func setupBindings() { let refreshControl = self.tableView.refreshControl! refreshControl.rx.controlEvent(.valueChanged) .bindTo(self.viewModel.refresh) .addDisposableTo(self.disposeBag) self.viewModel.isRefreshing .drive(refreshControl.rx.refreshing) .addDisposableTo(self.disposeBag) } } extension FeedListViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.showFeed.rawValue { let feedViewController = segue.destination as! FeedChartViewController let selectedIndexPath = self.tableView.indexPathForSelectedRow! let item = self.dataSource[selectedIndexPath] let viewModel = self.viewModel.feedChartViewModel(forItem: item) feedViewController.viewModel = viewModel } } }
e94c420ff33d72f362e123e84c9907ce
25.197802
96
0.72651
false
false
false
false
HighBay/PageMenu
refs/heads/master
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/PageMenuTwoViewController.swift
bsd-3-clause
4
// // PageMenuTwoViewController.swift // PageMenuDemoTabbar // // Created by Niklas Fahl on 1/9/15. // Copyright (c) 2015 Niklas Fahl. All rights reserved. // import UIKit import PageMenu class PageMenuTwoViewController: UIViewController { var pageMenu : CAPSPageMenu? override func viewDidLoad() { super.viewDidLoad() // MARK: - Scroll menu setup // Initialize view controllers to display and place in array var controllerArray : [UIViewController] = [] let controller1 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil) controller1.title = "friends" controllerArray.append(controller1) let controller2 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil) controller2.title = "mood" controllerArray.append(controller2) let controller3 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil) controller3.title = "favorites" controllerArray.append(controller3) let controller4 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil) controller4.title = "music" controllerArray.append(controller4) // Customize menu (Optional) let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 1.0)), .viewBackgroundColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 1.0)), .selectionIndicatorColor(UIColor.orange), .addBottomMenuHairline(false), .menuItemFont(UIFont(name: "HelveticaNeue", size: 35.0)!), .menuHeight(50.0), .selectionIndicatorHeight(0.0), .menuItemWidthBasedOnTitleTextWidth(true), .selectedMenuItemLabelColor(UIColor.orange) ] // Initialize scroll menu pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 60.0, width: self.view.frame.width, height: self.view.frame.height - 60.0), pageMenuOptions: parameters) self.view.addSubview(pageMenu!.view) } }
bfb317474846dcff544e095ca8ab5d31
42.851852
195
0.673986
false
true
false
false
lanstonpeng/Focord2
refs/heads/master
Focord2/GameCountingCircleView.swift
mit
1
// // GameCountingCircleView.swift // Focord2 // // Created by Lanston Peng on 8/20/14. // Copyright (c) 2014 Vtm. All rights reserved. // import UIKit import CoreMotion protocol GameCountingCircleDelegate:NSObjectProtocol { func GameCountingCircleDidEndCount(circleKey:NSString) func GameCountingCircleDidChange(circleKey:NSString) } class GameCountingCircleView: UIView,NSCopying { var indicatorLabel:UILabel? var pieCapacity:CGFloat{ didSet{ self.setNeedsDisplay() } } var clockWise:Int32!//0=逆时针,1=顺时针 var currentCount:Int var deltaCount:Int! var destinationCount:Int var circleKey:NSString! var frontColor:UIColor! var circleColor:UIColor! var delegate:GameCountingCircleDelegate? let frontLayer:CALayer! let frontBgLayer:CALayer! let circleLayer:CAShapeLayer! var timer:NSTimer? var startX:CGFloat! var startY:CGFloat! var radius:CGFloat! var pieStart:CGFloat! // func addCount(deltaNum:Int) // func addCount(deltaNum:Int isReverse:Bool) // func initShapeLayer() internal var f:CGRect! internal var addCountCurrentNumber:CGFloat var animator:UIDynamicAnimator! var gravity:UIGravityBehavior! var collision:UICollisionBehavior! var totalCount: Int { didSet { self.indicatorLabel?.text = "\(totalCount)" } } override init(frame: CGRect) { f = frame addCountCurrentNumber = 0 pieStart = 270 pieCapacity = 360 clockWise = 0 currentCount = 0 deltaCount = 0 destinationCount = 0 circleKey = "timeCount" frontLayer = CALayer() frontBgLayer = CALayer() circleLayer = CAShapeLayer() totalCount = 0 super.init(frame: frame) let smallerFrame:CGRect = CGRectInset(self.bounds, 10, 10) radius = smallerFrame.size.width/2 + 1 startX = self.bounds.size.width/2 startY = self.bounds.size.height/2 self.backgroundColor = UIColor.clearColor() self.clipsToBounds = false self.layer.masksToBounds = false frontLayer.frame = smallerFrame frontLayer.backgroundColor = UIColor(red: 0.0/255, green: 206.0/255, blue: 97.0/255, alpha: 1.0).CGColor frontLayer.cornerRadius = smallerFrame.size.width / 2; circleLayer.fillColor = UIColor.clearColor().CGColor circleLayer.strokeStart = 0; circleLayer.strokeEnd = 1; circleLayer.lineWidth = 5; circleLayer.lineCap = "round"; self.layer.addSublayer(frontLayer) self.layer.insertSublayer(circleLayer, below:frontLayer) } required init(coder aDecoder: NSCoder) { f = CGRectZero currentCount = 0 addCountCurrentNumber = 0 destinationCount = 0 pieCapacity = 360 totalCount = 0 //super.init() super.init(coder: aDecoder) } func startCounting() { if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(1.0/30, target: self, selector: "updateSector", userInfo: nil, repeats: true) } } func stopCounting(){ timer?.invalidate() timer = nil } func initData(toCount desCount:Int,withStart startCount:Int) { indicatorLabel = UILabel(frame:self.bounds) self.currentCount = startCount; destinationCount = desCount; deltaCount = abs(destinationCount - startCount) indicatorLabel?.textAlignment = NSTextAlignment.Center //indicatorLabel?.textColor = UIColor(red: 254.0/255, green: 213.0/255, blue: 49.0/255, alpha: 1) indicatorLabel?.textColor = UIColor.whiteColor() indicatorLabel?.font = UIFont(name: "AppleSDGothicNeo-Thin", size: 40.0) indicatorLabel?.adjustsFontSizeToFitWidth = true indicatorLabel?.layer.shadowOpacity = 0.5 indicatorLabel?.layer.shadowOffset = CGSizeMake(0,2) indicatorLabel?.layer.shadowColor = UIColor.blackColor().CGColor indicatorLabel?.layer.shadowRadius = 1.5 indicatorLabel?.layer.masksToBounds = false indicatorLabel?.text = "0" self.addSubview(indicatorLabel!) } func copyWithZone(zone: NSZone) -> AnyObject! { let c:GameCountingCircleView = GameCountingCircleView(frame: self.f) c.initData(toCount: self.destinationCount, withStart: self.currentCount) c.indicatorLabel?.text = self.indicatorLabel?.text return c } func bigifyCircleByUnit() { frontLayer.frame = CGRectInset(frontLayer.frame, -1, -1) self.bounds = CGRectInset(self.bounds, -1, -1) frontLayer.cornerRadius = frontLayer.frame.size.width / 2; radius = frontLayer.frame.size.width/2 + 1 } func dropCicleView() { if animator == nil { animator = UIDynamicAnimator(referenceView: self.superview) collision = UICollisionBehavior(items: [self]) collision.translatesReferenceBoundsIntoBoundary = true gravity = UIGravityBehavior(items: [self]) animator.addBehavior(collision) MotionManager.instance.startListenDeviceMotion({ (deviceMotion:CMDeviceMotion!, error:NSError!) -> Void in let gravityVector:CMAcceleration = deviceMotion.gravity self.gravity.gravityDirection = CGVectorMake(CGFloat(gravityVector.x), CGFloat(-gravityVector.y)) }) } animator.addBehavior(gravity) } func updateSector() { //pieCapacity += 360.0 / CGFloat(destinationCount / (1.0) / 30.0 ) pieCapacity -= 18 * 1/30 addCountCurrentNumber += 1 if addCountCurrentNumber >= 30 { addCountCurrentNumber = 0 currentCount -= 1 if currentCount == destinationCount { self.delegate?.GameCountingCircleDidEndCount(self.circleKey) } else { self.delegate?.GameCountingCircleDidChange(self.circleKey) } } //self.setNeedsDisplay() } func DEG2RAD(angle:CGFloat) -> CGFloat { return ( angle ) * 3.1415926 / 180.0 } override func drawRect(rect: CGRect) { let context:CGContextRef = UIGraphicsGetCurrentContext(); //CGContextSetRGBStrokeColor(context, 0, 1, 1, 1); CGContextSetStrokeColorWithColor(context, UIColor(red: 254.0/255, green: 213.0/255, blue: 49.0/255, alpha: 1).CGColor); CGContextSetLineWidth(context, 5); CGContextSetLineCap(context, kCGLineCapRound); CGContextAddArc(context, startX, startY, radius, self.DEG2RAD(pieStart), self.DEG2RAD(pieStart + pieCapacity), clockWise); CGContextStrokePath(context); } }
5aaddd2cd1708f82924884d8d2d28774
29.679654
136
0.621561
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLax/ReLax/ReLaxResource.swift
mit
1
import Foundation struct ReLaxResource { private final class BundleClass { } static let bundle = Bundle(for: BundleClass.self) static let radiosityURL = bundle.url(forResource: "blue-radiosity", withExtension: nil)! static let tmfkPrefixData = bundle.url(forResource: "tmfkPrefixData", withExtension: nil)! static let tmfkLayerData = bundle.url(forResource: "tmfkLayerData", withExtension: nil)! static let bomTableStart = bundle.url(forResource: "bomTableStart", withExtension: nil)! }
6788ce097859c9c2ecdee36977bcf1f6
44.090909
91
0.780242
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Settings/ChangingDetails/ChangeHandleViewController.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // 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 import UIKit import WireSyncEngine fileprivate extension UIView { func wiggle() { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.duration = 0.3 animation.isAdditive = true animation.values = [0, 4, -4, 2, 0] animation.keyTimes = [0, 0.166, 0.5, 0.833, 1] layer.add(animation, forKey: "wiggle-animation") } } protocol ChangeHandleTableViewCellDelegate: AnyObject { func tableViewCell(cell: ChangeHandleTableViewCell, shouldAllowEditingText text: String) -> Bool func tableViewCellDidChangeText(cell: ChangeHandleTableViewCell, text: String) } final class ChangeHandleTableViewCell: UITableViewCell, UITextFieldDelegate { weak var delegate: ChangeHandleTableViewCellDelegate? let prefixLabel: UILabel = { let label = UILabel() label.font = .normalSemiboldFont label.textColor = SemanticColors.Label.textDefault return label }() let handleTextField: UITextField = { let textField = UITextField() textField.font = .normalFont textField.textColor = SemanticColors.Label.textDefault return textField }() let domainLabel: UILabel = { let label = UILabel() label.font = .normalSemiboldFont label.textColor = .gray label.setContentCompressionResistancePriority(.required, for: .horizontal) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() createConstraints() setupStyle() } func setupStyle() { backgroundColor = .clear } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { handleTextField.delegate = self handleTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged) handleTextField.autocapitalizationType = .none handleTextField.accessibilityLabel = "handleTextField" handleTextField.autocorrectionType = .no handleTextField.spellCheckingType = .no handleTextField.textAlignment = .right prefixLabel.text = "@" [prefixLabel, handleTextField, domainLabel].forEach(addSubview) } private func createConstraints() { [prefixLabel, handleTextField, domainLabel].prepareForLayout() NSLayoutConstraint.activate([ prefixLabel.topAnchor.constraint(equalTo: topAnchor), prefixLabel.widthAnchor.constraint(equalToConstant: 16), prefixLabel.bottomAnchor.constraint(equalTo: bottomAnchor), prefixLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), prefixLabel.trailingAnchor.constraint(equalTo: handleTextField.leadingAnchor, constant: -4), handleTextField.topAnchor.constraint(equalTo: topAnchor), handleTextField.bottomAnchor.constraint(equalTo: bottomAnchor), handleTextField.trailingAnchor.constraint(equalTo: domainLabel.leadingAnchor, constant: -4), domainLabel.topAnchor.constraint(equalTo: topAnchor), domainLabel.bottomAnchor.constraint(equalTo: bottomAnchor), domainLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -16) ]) } func performWiggleAnimation() { [handleTextField, prefixLabel].forEach { $0.wiggle() } } // MARK: - UITextField @objc func editingChanged(textField: UITextField) { let lowercase = textField.text?.lowercased() ?? "" textField.text = lowercase delegate?.tableViewCellDidChangeText(cell: self, text: lowercase) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let delegate = delegate else { return false } let current = (textField.text ?? "") as NSString let replacement = current.replacingCharacters(in: range, with: string) if delegate.tableViewCell(cell: self, shouldAllowEditingText: replacement) { return true } performWiggleAnimation() return false } } /// This struct represents the current state of a handle /// change operation and performs necessary validation steps of /// a new handle. The `ChangeHandleViewController` uses this state /// to layout its interface. struct HandleChangeState { enum ValidationError: Error { case tooShort, tooLong, invalidCharacter, sameAsPrevious } enum HandleAvailability { case unknown, available, taken } let currentHandle: String? private(set) var newHandle: String? var availability: HandleAvailability var displayHandle: String? { return newHandle ?? currentHandle } init(currentHandle: String?, newHandle: String?, availability: HandleAvailability) { self.currentHandle = currentHandle self.newHandle = newHandle self.availability = availability } private static var allowedCharacters: CharacterSet = { return CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz_-.").union(.decimalDigits) }() private static var allowedLength: CountableClosedRange<Int> { return 2...256 } /// Validates the passed in handle and updates the state if /// no error occurs, otherwise a `ValidationError` will be thrown. mutating func update(_ handle: String) throws { availability = .unknown try validate(handle) newHandle = handle } /// Validation a new handle, if passed in handle /// is invalid, an error will be thrown. /// This function does not update the `HandleChangeState` itself. func validate(_ handle: String) throws { let subset = CharacterSet(charactersIn: handle).isSubset(of: HandleChangeState.allowedCharacters) guard subset && handle.isEqualToUnicodeName else { throw ValidationError.invalidCharacter } guard handle.count >= HandleChangeState.allowedLength.lowerBound else { throw ValidationError.tooShort } guard handle.count <= HandleChangeState.allowedLength.upperBound else { throw ValidationError.tooLong } guard handle != currentHandle else { throw ValidationError.sameAsPrevious } } } final class ChangeHandleViewController: SettingsBaseTableViewController { private typealias HandleChange = L10n.Localizable.Self.Settings.AccountSection.Handle.Change var footerFont: UIFont = .smallFont var state: HandleChangeState private var footerLabel = UILabel() fileprivate weak var userProfile = ZMUserSession.shared()?.userProfile private var observerToken: Any? var popOnSuccess = true private var federationEnabled: Bool convenience init() { self.init(state: HandleChangeState(currentHandle: SelfUser.current.handle ?? nil, newHandle: nil, availability: .unknown)) } convenience init(suggestedHandle handle: String) { self.init(state: .init(currentHandle: nil, newHandle: handle, availability: .unknown)) setupViews() checkAvailability(of: handle) } /// Used to inject a specific `HandleChangeState` in tests. See `ChangeHandleViewControllerTests`. init(state: HandleChangeState, federationEnabled: Bool = BackendInfo.isFederationEnabled) { self.state = state self.federationEnabled = federationEnabled super.init(style: .grouped) setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewDidAppear(animated) updateUI() observerToken = userProfile?.add(observer: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) observerToken = nil } private func setupViews() { navigationItem.setupNavigationBarTitle(title: HandleChange.title.capitalized) view.backgroundColor = .clear ChangeHandleTableViewCell.register(in: tableView) tableView.allowsSelection = false tableView.isScrollEnabled = false tableView.separatorStyle = .singleLine tableView.separatorColor = SemanticColors.View.backgroundSeparatorCell footerLabel.numberOfLines = 0 updateUI() navigationItem.rightBarButtonItem = UIBarButtonItem( title: HandleChange.save.capitalized, style: .plain, target: self, action: #selector(saveButtonTapped) ) navigationItem.rightBarButtonItem?.tintColor = SemanticColors.Label.textDefault } @objc func saveButtonTapped(sender: UIBarButtonItem) { guard let handleToSet = state.newHandle else { return } userProfile?.requestSettingHandle(handle: handleToSet) isLoadingViewVisible = true } fileprivate var attributedFooterTitle: NSAttributedString? { let infoText = HandleChange.footer.attributedString && SemanticColors.Label.textSectionFooter let alreadyTakenText = HandleChange.Footer.unavailable && SemanticColors.LegacyColors.vividRed let prefix = state.availability == .taken ? alreadyTakenText + "\n\n" : "\n\n".attributedString return (prefix + infoText) && footerFont } private func updateFooter() { footerLabel.attributedText = attributedFooterTitle let size = footerLabel.sizeThatFits(CGSize(width: view.frame.width - 32, height: UIView.noIntrinsicMetric)) footerLabel.frame = CGRect(origin: CGPoint(x: 16, y: 0), size: size) tableView.tableFooterView = footerLabel } private func updateNavigationItem() { navigationItem.rightBarButtonItem?.isEnabled = state.availability == .available } fileprivate func updateUI() { updateNavigationItem() updateFooter() } // MARK: - UITableView override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ChangeHandleTableViewCell.zm_reuseIdentifier, for: indexPath) as! ChangeHandleTableViewCell cell.delegate = self cell.handleTextField.text = state.displayHandle cell.handleTextField.becomeFirstResponder() cell.domainLabel.isHidden = !federationEnabled cell.domainLabel.text = federationEnabled ? SelfUser.current.domainString : "" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 56 } } extension ChangeHandleViewController: ChangeHandleTableViewCellDelegate { func tableViewCell(cell: ChangeHandleTableViewCell, shouldAllowEditingText text: String) -> Bool { do { /// We validate the new handle and only allow the edit if /// the new handle neither contains invalid characters nor is too long. try state.validate(text) return true } catch HandleChangeState.ValidationError.invalidCharacter { return false } catch HandleChangeState.ValidationError.tooLong { return false } catch { return true } } func tableViewCellDidChangeText(cell: ChangeHandleTableViewCell, text: String) { do { NSObject.cancelPreviousPerformRequests(withTarget: self) try state.update(text) perform(#selector(checkAvailability), with: text, afterDelay: 0.2) } catch { // no-op } updateUI() } @objc fileprivate func checkAvailability(of handle: String) { userProfile?.requestCheckHandleAvailability(handle: handle) } } extension ChangeHandleViewController: UserProfileUpdateObserver { func didCheckAvailiabilityOfHandle(handle: String, available: Bool) { guard handle == state.newHandle else { return } state.availability = available ? .available : .taken updateUI() } func didFailToCheckAvailabilityOfHandle(handle: String) { guard handle == state.newHandle else { return } // If we fail to check we let the user check again by tapping the save button state.availability = .available updateUI() } func didSetHandle() { isLoadingViewVisible = false state.availability = .taken guard popOnSuccess else { return } _ = navigationController?.popViewController(animated: true) } func didFailToSetHandle() { presentFailureAlert() isLoadingViewVisible = false } func didFailToSetHandleBecauseExisting() { state.availability = .taken updateUI() isLoadingViewVisible = false } private func presentFailureAlert() { let alert = UIAlertController( title: HandleChange.FailureAlert.title, message: HandleChange.FailureAlert.message, preferredStyle: .alert ) alert.addAction(.init(title: L10n.Localizable.General.ok, style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } } fileprivate extension String { var isEqualToUnicodeName: Bool { return applyingTransform(.toUnicodeName, reverse: false) == self } }
16b90ee56be12973232cd9a49e157b02
34.719902
156
0.686408
false
false
false
false
J3D1-WARR10R/WikiRaces
refs/heads/master
WikiRaces/Shared/Race View Controllers/HistoryViewController/HistoryTableViewStatsCell.swift
mit
2
// // HistoryTableViewStatsCell.swift // WikiRaces // // Created by Andrew Finke on 2/28/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit final internal class HistoryTableViewStatsCell: UITableViewCell { // MARK: - Properties - static let reuseIdentifier = "statsReuseIdentifier" var stat: (key: String, value: String)? { didSet { statLabel.text = stat?.key detailLabel.text = stat?.value } } let statLabel = UILabel() let detailLabel = UILabel() // MARK: - Initialization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) statLabel.textAlignment = .left statLabel.font = UIFont.systemFont(ofSize: 17, weight: .regular) statLabel.numberOfLines = 0 statLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(statLabel) detailLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium) detailLabel.textAlignment = .right detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal) detailLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(detailLabel) setupConstraints() isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - public override func layoutSubviews() { super.layoutSubviews() let textColor = UIColor.wkrTextColor(for: traitCollection) tintColor = textColor statLabel.textColor = textColor detailLabel.textColor = textColor } // MARK: - Constraints - private func setupConstraints() { let leftMarginConstraint = NSLayoutConstraint(item: statLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .leftMargin, multiplier: 1.0, constant: 0.0) let rightMarginConstraint = NSLayoutConstraint(item: detailLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .rightMargin, multiplier: 1.0, constant: 0.0) let constraints = [ leftMarginConstraint, statLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10), statLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 15), statLabel.rightAnchor.constraint(lessThanOrEqualTo: detailLabel.leftAnchor, constant: -15), rightMarginConstraint, detailLabel.centerYAnchor.constraint(equalTo: centerYAnchor) ] NSLayoutConstraint.activate(constraints) } }
851ed0b40d3a8f5047e82fb7b291c7e0
35.086022
103
0.548272
false
false
false
false
phimage/MomXML
refs/heads/master
Sources/Model/MomElement.swift
mit
1
// Created by Eric Marchand on 07/06/2017. // Copyright © 2017 Eric Marchand. All rights reserved. // import Foundation public struct MomElement { public var name: String public var positionX: Int = 0 public var positionY: Int = 0 public var width: Int = 128 public var height: Int = 128 public init(name: String, positionX: Int = 0, positionY: Int = 0, width: Int = 0, height: Int = 0) { self.name = name self.positionX = positionX self.positionY = positionY self.width = width self.height = height } }
06f5e9af6f0714b4b99304cc674e6fbb
24.173913
104
0.632124
false
false
false
false
WSDOT/wsdot-ios-app
refs/heads/master
wsdot/AmtrakCascadesServiceStopItem.swift
gpl-3.0
2
// // AmtrakCascadesServiceItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // 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 // Stop item represents an item from the Amtrak API. It is eitehr an arriavl or desprature. class AmtrakCascadesServiceStopItem{ var stationId: String = "" var stationName: String = "" var trainNumber: Int = -1 var tripNumer: Int = -1 var sortOrder: Int = -1 var arrivalComment: String? = nil var departureComment: String? = nil var scheduledArrivalTime: Date? = nil var scheduledDepartureTime: Date? = nil var updated = Date(timeIntervalSince1970: 0) }
4fb9b8298f02c3eebedf945034163066
31.365854
92
0.706104
false
false
false
false
totomo/SSLogger
refs/heads/master
Source/Printer.swift
mit
1
// // Printer.swift // SSLogger // // Created by Kenta Tokumoto on 2015/09/19. // Copyright © 2015年 Kenta Tokumoto. All rights reserved. // public func print(value:Any...){ #if DEBUG var message = "" for element in value { var eachMessage = "\(element)" let pattern = "Optional\\((.+)\\)" eachMessage = eachMessage .stringByReplacingOccurrencesOfString(pattern, withString:"$1", options:.RegularExpressionSearch, range: nil) message += eachMessage } Swift.print(message) #endif }
d4af47f1e46144c65b59cb227db4c921
23.708333
58
0.584459
false
false
false
false
robotwholearned/GettingStarted
refs/heads/master
FoodTracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // FoodTracker // // Created by Sandquist, Cassandra - Cassandra on 3/12/16. // Copyright © 2016 robotwholearned. All rights reserved. // import UIKit enum RatingLevels: Int { case One = 1, Two, Three, Four, Five } struct MealNames { static let capreseSalad = "Caprese Salad" static let chickenAndPotatoes = "Chicken and Potatoes" static let pastaAndMeatballs = "Pasta with Meatballs" } class MealTableViewController: UITableViewController { //MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem() if let loadedMeals = loadMeals() { meals += loadedMeals } else { loadSampleMeals() } } func loadSampleMeals() { let photo1 = R.image.meal1() let meal1 = Meal(name: MealNames.capreseSalad, photo: photo1, rating: RatingLevels.Four.rawValue)! let photo2 = R.image.meal2() let meal2 = Meal(name: MealNames.chickenAndPotatoes, photo: photo2, rating: RatingLevels.Five.rawValue)! let photo3 = R.image.meal3() let meal3 = Meal(name: MealNames.pastaAndMeatballs, photo: photo3, rating: RatingLevels.Three.rawValue)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(R.reuseIdentifier.mealTableViewCell.identifier, forIndexPath: indexPath) as! MealTableViewCell // Fetches the appropriate meal for the data source layout. let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView?.image = meal.photo cell.ratingControl.rating = meal.rating return cell } @IBAction func unwindToMealList (segue: UIStoryboardSegue) { if let sourceViewController = segue.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { // Add a new meal. let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } saveMeals() } } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { meals.removeAtIndex(indexPath.row) saveMeals() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // 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?) { if segue.identifier == R.segue.mealTableViewController.showDetail.identifier { let mealDetailViewController = segue.destinationViewController as! MealViewController if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == R.segue.mealTableViewController.addItem.identifier { print("Adding new meal.") } } // MARK: NSCoding func saveMeals() { let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!) if !isSuccessfulSave { print("Failed to save meals...") } } func loadMeals() -> [Meal]? { return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal] } }
8713f956f550ceebaaf514ad99771e0d
34.381295
157
0.665718
false
false
false
false
digice/ios-dvm-boilerplate
refs/heads/master
Location/LocationData.swift
mit
1
// // Location.swift // DVM-Boilerplate // // Created by Digices LLC on 3/30/17. // Copyright © 2017 Digices LLC. All rights reserved. // import Foundation import CoreLocation class LocationData : NSObject, NSCoding { // MARK: - Optional Properties var latitude : Double? var longitude : Double? var region : CLRegion? // MARK: - NSObject Methods override init() { super.init() } // MARK: - NSCoder Methods required init?(coder aDecoder: NSCoder) { // decode latitude let x = aDecoder.decodeDouble(forKey: "latitude") if x < 200 { self.latitude = x } // decode longitude let y = aDecoder.decodeDouble(forKey: "longitude") if y < 200 { self.longitude = y } // decode region let r = aDecoder.decodeObject(forKey: "region") if r as? String == "nil" { // do nothing } else { self.region = r as? CLRegion } } func encode(with aCoder: NSCoder) { // encode latitude if let x = self.latitude { aCoder.encode(x, forKey: "latitude") } else { aCoder.encode(999.9, forKey: "latitude") } // encode longitiude if let y = self.longitude { aCoder.encode(y, forKey: "longitude") } else { aCoder.encode(999.9, forKey: "longitude") } if let r = self.region { aCoder.encode(r, forKey: "region") } else { aCoder.encode("nil", forKey: "region") } } // MARK: - Custom Methods func httpBody() -> String { // make sure we have longitude and latitude if let x = self.latitude { if let y = self.longitude { if let r = self.region { // optionally include region identifier return "x=\(x)&y=\(y)&r=\(r.identifier)" } else { // return "x=\(x)&y=\(y)&r=unknown" } } } // return default string with recognizably invalid parameters return "x=999.9&y=999.9&r=unknown" } }
af138f5e17737bb9e09bafa5ba7ddd45
18.465347
65
0.574771
false
false
false
false
mlibai/OMKit
refs/heads/master
Example/OMKit/NewsDetailMessageHandler.swift
mit
1
// // NewsDetailMessageHandler.swift // OMKit // // Created by mlibai on 2017/9/4. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import WebKit import OMKit enum NewsDetailList: String { case more = "More List" case hots = "Hot Comments List" case comments = "Comments List" case floor = "Floor Comments List" } protocol NewsDetailMessageHandlerDelegate: class { func ready(_ completion: () -> Void) func numberOfRowsInList(_ list: NewsDetailList) -> Int func list(_ list: NewsDetailList, dataForRowAt index: Int) -> [String: Any] func list(_ list: NewsDetailList, didSelectRowAt index: Int) func followButtonWasClicked(_ isSelected: Bool, completion: (Bool) -> Void) func conentLinkWasClicked() func likeButtonWasClicked(_ isSelected: Bool, completion: (_ isSelected: Bool) -> Void) func dislikeButtonWasClicked(_ isSelected: Bool, completion: (_ isSelected: Bool) -> Void) func sharePathWasClicked(_ sharePath: String) func navigationBarInfoButtonWasClicked() func toolBarShareButtonClicked() func toolBarCollectButtonClicked(_ isSelected: Bool, completion:(Bool) -> Void) // 加载评论 func loadComments() // 加载叠楼回复 func loadReplies() /// 评论点赞按钮被点击时。 /// /// - Parameters: /// - commentsList: 评论列表。 /// - index: 被点击的按钮所在列表的行索引。叠楼时,index = -1 表示楼主的评论被点击。 /// - isSelected: 按钮的当前状态。 /// - completion: 按钮被点击后的状态。 func commentsList(_ commentsList: NewsDetailList, likeButtonAt index: Int, wasClicked isSelected: Bool, completion: (Bool)->Void) } class NewsDetailMessageHandler: WebViewMessageHandler { unowned let delegate: NewsDetailMessageHandlerDelegate init(delegate: NewsDetailMessageHandlerDelegate, webView: WKWebView, viewController: UIViewController) { self.delegate = delegate super.init(webView: webView, viewController: viewController) } override func ready(_ completion: @escaping () -> Void) { delegate.ready(completion) } override func document(_ document: String, numberOfRowsInList list: String, completion: @escaping (Int) -> Void) { if let list = NewsDetailList.init(rawValue: list) { completion(delegate.numberOfRowsInList(list)); } else { super.document(document, numberOfRowsInList: list, completion: completion) } } override func document(_ document: String, list: String, dataForRowAt index: Int, completion: @escaping ([String : Any]) -> Void) { if let list = NewsDetailList.init(rawValue: list) { completion(delegate.list(list, dataForRowAt: index)) } else { super.document(document, list: list, dataForRowAt: index, completion: completion) } } override func document(_ document: String, list: String, didSelectRowAt index: Int, completion: @escaping () -> Void) { if let list = NewsDetailList.init(rawValue: list) { delegate.list(list, didSelectRowAt: index) completion() } else { super.document(document, list: list, didSelectRowAt: index, completion: completion) } } override func document(_ document: String, element: String, wasClicked data: Any, completion: @escaping (Bool) -> Void) { switch element { case "Follow Button": delegate.followButtonWasClicked(data as? Bool ?? false, completion: completion) case "Content Link": delegate.conentLinkWasClicked() case "Action Like": guard let isSelected = data as? Bool else { return } delegate.likeButtonWasClicked(isSelected, completion: completion) case "Action Dislike": guard let isSelected = data as? Bool else { return } delegate.dislikeButtonWasClicked(isSelected, completion: completion) case "Comments Load More": delegate.loadComments() case "Share Button": guard let sharePath = data as? String else { return } delegate.sharePathWasClicked(sharePath) case "Floor Load More": delegate.loadReplies() case "Hots Comments List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.hots, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Comments List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.comments, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Floor List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.floor, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Floor Host Like Action": guard let dict = data as? [String: Any] else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.floor, likeButtonAt: -1, wasClicked: isSelected, completion: { (isSelected) in completion(isSelected) }) case "Navigation Bar Info": delegate.navigationBarInfoButtonWasClicked() case "Tool Bar Share": delegate.toolBarShareButtonClicked() case "Tool Bar Collect": guard let isSelected = data as? Bool else { return } delegate.toolBarCollectButtonClicked(isSelected, completion: completion) default: super.document(document, element: element, wasClicked: data, completion: completion) } } }
33c8eb506bcae50a631c6436f117c142
34.524862
135
0.617729
false
false
false
false
weiss19ja/LocalizableUI
refs/heads/master
LocalizableUI/LocalizedItems/UITextField+LocalizableUI.swift
mit
1
// // UITextField+LocalizableUI.swift // Pods // // Created by Jan Weiß on 01.08.17. // // import Foundation import UIKit private var AssociatedObjectPointer: UInt8 = 0 extension UITextField: Localizable { // Stores the property of the localized placeholder key @IBInspectable public var localizedPlaceholderKey: String? { get { return objc_getAssociatedObject(self, &AssociatedObjectPointer) as? String } set { objc_setAssociatedObject(self, &AssociatedObjectPointer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) // Add the Element to the LocalizationManager addToManager() } } public convenience init(frame: CGRect, localizedKey: String?, localizedPlaceholderKey: String?) { self.init(frame: frame) self.localizedKey = localizedKey self.localizedPlaceholderKey = localizedPlaceholderKey } /// Updates all subviews with their given localizedKeys public func updateLocalizedStrings() { if let localizedKey = localizedKey { text = LocalizationManager.localizedStringFor(localizedKey) } if let localizedPlaceHolderKey = localizedPlaceholderKey { placeholder = LocalizationManager.localizedStringFor(localizedPlaceHolderKey) } } }
976bebbdd624b6c86c29d3669142a974
28.319149
114
0.662554
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
3-Fibonacci/3-Fibonacci/SearchArray.swift
mit
1
// // SearchArray.swift // 3-Array // // Created by keso on 2016/12/18. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class SearchArray { //数组中出现次数超过一半的数字 // 题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,5,4,2}。由于数字2在数组中出现了5词,超过数组长度的一半,因此输出2. func moreThanHalfNum(arr:[Int]) -> Int? { if arr.count == 0 { return nil } var num:Int = arr[0] var times:Int = 1 for i in 1..<arr.count { if times == 0 { num = arr[i] times = 1 } else { if arr[i] == num { times += 1 } else { times -= 1 } } } return num } }
5fd6147fc824745534ddccb15fdc25e4
21.166667
102
0.451128
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Constraints/requirement_failures_in_contextual_type.swift
apache-2.0
6
// RUN: %target-typecheck-verify-swift struct A<T> {} extension A where T == Int32 { // expected-note 2 {{where 'T' = 'Int'}} struct B : ExpressibleByIntegerLiteral { // expected-note {{where 'T' = 'Int'}} typealias E = Int typealias IntegerLiteralType = Int init(integerLiteral: IntegerLiteralType) {} } typealias C = Int } let _: A<Int>.B = 0 // expected-error@-1 {{referencing struct 'B' on 'A' requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.C = 0 // expected-error@-1 {{referencing type alias 'C' on 'A' requires the types 'Int' and 'Int32' be equivalent}} let _: A<Int>.B.E = 0 // expected-error@-1 {{referencing type alias 'E' on 'A.B' requires the types 'Int' and 'Int32' be equivalent}}
9cf5c6f53dbeadfed37122b87f2cd174
34.142857
111
0.655827
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
refs/heads/best-ui
Team UI/Browser/Browser/ConnectionCtrls.swift
mit
1
// // ConnectionCtrl.swift // Browser // // Created by Burak Erol on 10.12.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import Foundation class JSONConnectionCtrl:ConnectionCtrl { override func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, data: NSData) -> ()) { let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let data = try! NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions()]) self.post(data, request: request, postCompleted: postCompleted) } } class ConnectionCtrl { // func post(params : AnyObject, url : String, // postCompleted : (succeeded: Bool, data: NSData) -> ()) // { // let request = NSMutableURLRequest(URL: NSURL(string: url)!) // request.HTTPMethod = "POST" // request.addValue("application/json", forHTTPHeaderField: "Content-Type") // request.addValue("application/json", forHTTPHeaderField: "Accept") // request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions()]) // // let session = NSURLSession.sharedSession() // let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in // postCompleted(succeeded: error == nil, data: data!) // }) // // // task.resume() // // } func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, data: NSData) -> ()){ postCompleted(succeeded: false,data: "Es wird die abstrakte Klasse ConnectionCtrl".dataUsingEncoding(NSUTF8StringEncoding)!) } private func post(data : NSData, request : NSMutableURLRequest, postCompleted : (succeeded: Bool, data: NSData) -> ()) { request.HTTPMethod = "POST" request.HTTPBody = data let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in postCompleted(succeeded: error == nil, data: data!) }) task.resume() } }
7dfa849272fefb9872df9eac4d1f8960
36.619048
136
0.635289
false
false
false
false
e-sites/Natrium
refs/heads/main
Sources/Helpers/PlistHelper.swift
mit
1
// // PlistHelper.swift // CommandLineKit // // Created by Bas van Kuijck on 11/02/2019. // import Foundation enum PlistHelper { static func getValue(`for` key: String, in plistFile: String) -> String? { guard let dic = NSDictionary(contentsOfFile: plistFile) else { return nil } return dic.object(forKey: key) as? String } private static func getValueType(_ value: String) -> String { if value == "true" || value == "false" { return "bool" } else if Int(value) != nil { return "integer" } else { return "string" } } static func write(value: String, `for` key: String, in plistFile: String) { let exists = Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Print :\(key)\"", "\"\(plistFile)\"", "2>/dev/null" ]) ?? "" if exists.isEmpty { let type = getValueType(value) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key) \(type) \(value)\"", "\"\(plistFile)\"" ]) } else { Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Set :\(key) \(value)\"", "\"\(plistFile)\"" ]) } } static func write(array: [String], `for` key: String, in plistFile: String) { remove(key: key, in: plistFile) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key) array\"", "\"\(plistFile)\"" ]) for value in array { let type = getValueType(value) Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Add :\(key): \(type) \(value)\"", "\"\(plistFile)\"" ]) } } static func remove(key: String, in plistFile: String) { Shell.execute("/usr/libexec/PlistBuddy", useProxyScript: true, arguments: [ "-c", "\"Delete :\(key)\"", "\"\(plistFile)\"" ]) } }
ae2e8574c9ba536d73516717e6ade119
29.378378
96
0.496441
false
false
false
false
TouchInstinct/LeadKit
refs/heads/master
TIEcommerce/Sources/Filters/FiltersViewModel/BaseFilterViewModel.swift
apache-2.0
1
// // Copyright (c) 2022 Touch Instinct // // 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 TISwiftUtils import UIKit open class BaseFilterViewModel<CellViewModelType: FilterCellViewModelProtocol & Hashable, PropertyValue: FilterPropertyValueRepresenter & Hashable>: FilterViewModelProtocol { // MARK: - FilterViewModelProtocol public typealias Change = (indexPath: IndexPath, viewModel: CellViewModelType) public var values: [PropertyValue] = [] { didSet { filtersCollection?.update() } } public var selectedValues: [PropertyValue] = [] { didSet { filtersCollection?.update() } } public weak var filtersCollection: Updatable? public weak var pickerDelegate: FiltersPickerDelegate? public private(set) var cellsViewModels: [CellViewModelType] public init(filterPropertyValues: [PropertyValue], cellsViewModels: [CellViewModelType] = []) { self.values = filterPropertyValues self.cellsViewModels = cellsViewModels } open func filterDidSelected(atIndexPath indexPath: IndexPath) -> [Change] { let (selected, deselected) = toggleProperty(atIndexPath: indexPath) let changedValues = values .enumerated() .filter { selected.contains($0.element) || deselected.contains($0.element) } changedValues.forEach { index, element in let isSelected = selectedValues.contains(element) setSelectedCell(atIndex: index, isSelected: isSelected) setSelectedProperty(atIndex: index, isSelected: isSelected) } let changedItems = changedValues .map { Change(indexPath: IndexPath(item: $0.offset, section: .zero), viewModel: cellsViewModels[$0.offset]) } pickerDelegate?.filters(didSelected: selected) return changedItems } open func setSelectedCell(atIndex index: Int, isSelected: Bool) { cellsViewModels[index].isSelected = isSelected } open func setSelectedProperty(atIndex index: Int, isSelected: Bool) { values[index].isSelected = isSelected } }
d1f8e7314767f259bedaaae5cb515b37
36.837209
115
0.691149
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/SwiftForms/SwiftForms/descriptors/FormDescriptor.swift
mit
1
// // FormDescriptor.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormDescriptor { // MARK: Properties public let title: String public var sections: [FormSectionDescriptor] = [] // MARK: Init public init(title: String) { self.title = title } // MARK: Public public func addSection(section: FormSectionDescriptor) { sections.append(section) } public func removeSectionAtIndex(index: Int) throws { guard index >= 0 && index < sections.count - 1 else { throw FormErrorType.SectionOutOfIndex } sections.removeAtIndex(index) } public func formValues() -> [String : AnyObject] { var formValues: [String : AnyObject] = [:] for section in sections { for row in section.rows { if row.rowType != .Button { if row.value != nil { formValues[row.tag] = row.value! } else { formValues[row.tag] = NSNull() } } } } return formValues } public func validateForm() -> FormRowDescriptor? { for section in sections { for row in section.rows { if let required = row.configuration[FormRowDescriptor.Configuration.Required] as? Bool { if required && row.value == nil { return row } } } } return nil } }
febc8dfce6e63669de9512747f15c367
24.848485
104
0.509379
false
false
false
false
sffernando/SwiftLearning
refs/heads/master
FoodTracker/FoodTracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // FoodTracker // // Created by koudai on 2016/11/29. // Copyright © 2016年 fernando. All rights reserved. // import UIKit class MealTableViewController: UITableViewController { //MARK: peropeties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.leftBarButtonItem = editButtonItem if let savedMeals = loadMeals() { meals += savedMeals } else { loadSampleMeals() } } func loadSampleMeals() { let meal1 = Meal.init(name: "Caprese salad", photo: UIImage.init(named: "meal1"), rating: 5)! let meal2 = Meal.init(name: "Chicken and Potatoes", photo: UIImage.init(named: "meal2"), rating: 4)! let meal3 = Meal.init(name: "Pasta with Meatballs", photo: UIImage.init(named: "meal3"), rating: 3)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return meals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "MealTableViewCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MealTableViewCell // Configure the cell... let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.image cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source meals.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) saveMeals() } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowDetail" { let mealDetailViewController = segue.destination as! MealViewController if let selectCell = sender as? MealTableViewCell { let indexPath = tableView.indexPath(for: selectCell) let selectMeal = meals[(indexPath?.row)!] mealDetailViewController.meal = selectMeal } } else if segue.identifier == "AddItem" { print("Adding new meal.") } } @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal { if let selectIndexPath = tableView.indexPathForSelectedRow { meals[selectIndexPath.row] = meal tableView.reloadRows(at: [selectIndexPath], with: .none) } else { let newIndexPath = NSIndexPath.init(row: meals.count, section: 0) meals.append(meal) tableView.insertRows(at: [newIndexPath as IndexPath], with: .bottom) } saveMeals() } } //MARK: NSCoding func saveMeals() { let ifSuccessfulSaved = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path) if !ifSuccessfulSaved { print("Failed to save meals") } } func loadMeals() -> [Meal]? { return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal] } }
749d00fd0066536ec212603deb0885eb
34.493421
136
0.63911
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Foundation+Extras/TimeInterval+Formatter.swift
apache-2.0
1
// // TimeInterval+Formatter.swift // SwiftDate // // Created by Daniele Margutti on 14/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public extension TimeInterval { public struct ComponentsFormatterOptions { /// Fractional units may be used when a value cannot be exactly represented using the available units. /// For example, if minutes are not allowed, the value “1h 30m” could be formatted as “1.5h”. /// The default value of this property is false. public var allowsFractionalUnits: Bool = false /// Specify the units that can be used in the output. /// By default `[.year, .month, .weekOfMonth, .day, .hour, .minute, .second]` are used. public var allowedUnits: NSCalendar.Unit = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second] /// A Boolean value indicating whether to collapse the largest unit into smaller units when a certain threshold is met. /// By default is `false`. public var collapsesLargestUnit: Bool = false /// The maximum number of time units to include in the output string. /// The default value of this property is 0, which does not cause the elimination of any units. public var maximumUnitCount: Int = 0 /// The formatting style for units whose value is 0. /// By default is `.default` public var zeroFormattingBehavior: DateComponentsFormatter.ZeroFormattingBehavior = .default /// The preferred style for units. /// By default is `.abbreviated`. public var unitsStyle: DateComponentsFormatter.UnitsStyle = .abbreviated /// Locale of the formatter public var locale: LocaleConvertible? { set { self.calendar.locale = newValue?.toLocale() } get { return self.calendar.locale } } /// Calendar public var calendar: Calendar = Calendar.autoupdatingCurrent public func apply(toFormatter formatter: DateComponentsFormatter) { formatter.allowsFractionalUnits = self.allowsFractionalUnits formatter.allowedUnits = self.allowedUnits formatter.collapsesLargestUnit = self.collapsesLargestUnit formatter.maximumUnitCount = self.maximumUnitCount formatter.unitsStyle = self.unitsStyle formatter.calendar = self.calendar } public init() {} } /// Return the local thread shared formatter for date components private static func sharedFormatter() -> DateComponentsFormatter { let name = "SwiftDate_\(NSStringFromClass(DateComponentsFormatter.self))" return threadSharedObject(key: name, create: { let formatter = DateComponentsFormatter() formatter.includesApproximationPhrase = false formatter.includesTimeRemainingPhrase = false return formatter }) } @available(*, deprecated: 5.0.13, obsoleted: 5.1, message: "Use toIntervalString function instead") public func toString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String { return self.toIntervalString(options: callback) } /// Format a time interval in a string with desidered components with passed style. /// /// - Parameters: /// - units: units to include in string. /// - style: style of the units, by default is `.abbreviated` /// - Returns: string representation public func toIntervalString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String { let formatter = TimeInterval.sharedFormatter() var options = ComponentsFormatterOptions() callback?(&options) options.apply(toFormatter: formatter) return (formatter.string(from: self) ?? "") } /// Format a time interval in a string with desidered components with passed style. /// /// - Parameter options: options for formatting. /// - Returns: string representation public func toString(options: ComponentsFormatterOptions) -> String { let formatter = TimeInterval.sharedFormatter() options.apply(toFormatter: formatter) return (formatter.string(from: self) ?? "") } /// Return a string representation of the time interval in form of clock countdown (ie. 57:00:00) /// /// - Parameter zero: behaviour with zero. /// - Returns: string representation public func toClock(zero: DateComponentsFormatter.ZeroFormattingBehavior = .pad) -> String { return self.toIntervalString(options: { $0.unitsStyle = .positional $0.zeroFormattingBehavior = zero }) } /// Extract requeste time units components from given interval. /// Reference date's calendar is used to make the extraction. /// /// NOTE: /// Extraction is calendar/date based; if you specify a `refDate` calculation is made /// between the `refDate` and `refDate + interval`. /// If `refDate` is `nil` evaluation is made from `now()` and `now() + interval` in the context /// of the `SwiftDate.defaultRegion` set. /// /// - Parameters: /// - units: units to extract /// - from: starting reference date, `nil` means `now()` in the context of the default region set. /// - Returns: dictionary with extracted components public func toUnits(_ units: Set<Calendar.Component>, to refDate: DateInRegion? = nil) -> [Calendar.Component: Int] { let dateTo = (refDate ?? DateInRegion()) let dateFrom = dateTo.addingTimeInterval(-self) let components = dateFrom.calendar.dateComponents(units, from: dateFrom.date, to: dateTo.date) return components.toDict() } /// Express a time interval (expressed in seconds) in another time unit you choose. /// Reference date's calendar is used to make the extraction. /// /// - parameter component: time unit in which you want to express the calendar component /// - parameter from: starting reference date, `nil` means `now()` in the context of the default region set. /// /// - returns: the value of interval expressed in selected `Calendar.Component` public func toUnit(_ component: Calendar.Component, to refDate: DateInRegion? = nil) -> Int? { return self.toUnits([component], to: refDate)[component] } }
fa76ca21214f6219992ac32796cd4dc4
39.888112
121
0.728237
false
false
false
false
maxoll90/FSwift
refs/heads/master
FSwift/Network/ServiceUtil.swift
mit
3
// // ServiceUtil.swift // FSwift // // Created by Kelton Person on 11/15/14. // Copyright (c) 2014 Kelton. All rights reserved. // import Foundation let emptyBody:NSData = "".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! public class RequestResponse { public let statusCode: Int public let body: NSData public let headers: Dictionary<String, AnyObject> private var bodyText: String? init(statusCode: Int, body: NSData, headers: Dictionary<String, AnyObject>) { self.statusCode = statusCode self.body = body self.headers = headers } public var bodyAsText: String { if let bodyT = self.bodyText { return bodyT } else { self.bodyText = NSString(data: body, encoding: NSUTF8StringEncoding)! as String return self.bodyText! } } } public enum RequestMethod : String { case POST = "POST" case GET = "GET" case DELETE = "DELETE" case PUT = "PUT" case OPTIONS = "OPTIONS" case CONNECT = "CONNECT" case TRACE = "TRACE" case HEAD = "HEAD" } public extension String { func withParams(params: Dictionary<String, AnyObject>) -> String { let endpoint = self.hasPrefix("?") ? self : self + "?" return endpoint + (NSString(data: ServiceUtil.asParams(params), encoding: NSUTF8StringEncoding)! as String) } } public class ServiceUtil { public class func asJson(obj: AnyObject) -> NSData? { var error: NSError? return NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions.PrettyPrinted, error: &error) } public class func asParamsStr(params: Dictionary<String, AnyObject>) -> String { var pairs:[String] = [] for (key, value) in params { if let v = value as? Dictionary<String, AnyObject> { for (subKey, subValue) in v { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, subValue.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append("\(key)[\(subKey)]=\(escapedFormat)") } } else if let v = value as? [AnyObject] { for subValue in v { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, subValue.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append("\(key)[]=\(escapedFormat)") } } else { let escapedFormat = CFURLCreateStringByAddingPercentEscapes(nil, value.description, nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) pairs.append( "\(key)=\(escapedFormat)") } } let str = "&".join(pairs) return str } public class func asParams(params: Dictionary<String, AnyObject>) -> NSData { return asParamsStr(params).dataUsingEncoding(NSUTF8StringEncoding)! } public class func delete(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.DELETE, body: body, headers: headers) } public class func get(url:String, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.GET, body: emptyBody, headers: headers) } public class func post(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.POST, body: body, headers: headers) } public class func put(url:String, body: NSData = emptyBody, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.PUT, body: body, headers: headers) } public class func options(url:String, headers: Dictionary<String, AnyObject> = [:]) -> Future<RequestResponse> { return ServiceUtil.request(url, requestMethod: RequestMethod.OPTIONS, body: emptyBody, headers: headers) } public class func request(url:String, requestMethod: RequestMethod, body: NSData, headers: Dictionary<String, AnyObject>) -> Future<RequestResponse> { let request = NSMutableURLRequest(URL: NSURL(string: url)!) let session = NSURLSession.sharedSession() request.HTTPMethod = requestMethod.rawValue request.HTTPBody = body for (headerKey, headerValue) in headers { if let multiHeader = headerValue as? [String] { for str in multiHeader { request.addValue(str, forHTTPHeaderField: headerKey) } } else { request.addValue(headerValue as? String, forHTTPHeaderField: headerKey) } } let promise = Promise<RequestResponse>() var error: NSError let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in if error != nil { promise.completeWith(error) } else { let httpResponse = response as! NSHTTPURLResponse var responseHeaders:Dictionary<String, AnyObject> = [:] for (headerKey, headerValue) in httpResponse.allHeaderFields { responseHeaders[headerKey as! String] = headerValue } promise.completeWith(RequestResponse(statusCode: httpResponse.statusCode, body: data, headers: responseHeaders)) } }) task.resume() return promise.future } }
f781e77ddef0d3579775cee7f9523b66
36.63522
174
0.609291
false
false
false
false
erremauro/Password-Update
refs/heads/master
Password Update/Utils.swift
mit
1
// // Utils.swift // Password Update // // Created by Roberto Mauro on 4/23/17. // Copyright © 2017 roberto mauro. All rights reserved. // import Cocoa import Foundation class Utils { static func getAppName() -> String { let kBundleName = kCFBundleNameKey as String let appTitle = Bundle.main.infoDictionary![kBundleName] as! String return appTitle.capitalized } static func getBundleId() -> String { return Bundle.main.bundleIdentifier! } static func dialogWith(title: String, text: String, isOK: Bool = true) { let popUp = NSAlert() popUp.messageText = title popUp.informativeText = text popUp.alertStyle = isOK ? NSAlertStyle.informational : NSAlertStyle.warning popUp.addButton(withTitle: "OK") popUp.runModal() } static func shakeWindow(_ window: NSWindow) { let numberOfShakes:Int = 4 let durationOfShake:Float = 0.6 let vigourOfShake:Float = 0.01 let frame:CGRect = (window.frame) let shakeAnimation = CAKeyframeAnimation() let shakePath = CGMutablePath() shakePath.move(to: CGPoint(x: NSMinX(frame), y: NSMinY(frame))) for _ in 1...numberOfShakes { shakePath.addLine(to: CGPoint( x:NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame) )) shakePath.addLine(to: CGPoint( x:NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame) )) } shakePath.closeSubpath() shakeAnimation.path = shakePath shakeAnimation.duration = CFTimeInterval(durationOfShake) window.animations = ["frameOrigin":shakeAnimation] window.animator().setFrameOrigin((window.frame.origin)) } }
6f1a14ccc106f3a8c394e2105dc1be7f
30.064516
76
0.599688
false
false
false
false
alexito4/SwiftSandbox
refs/heads/master
LinkedList.playground/Pages/CopyOnWrite.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation var str = "Hello, playground" public class Node<T> { var value: T { get { return _value! } set { _value = newValue } } var _value: T? var next: Node! var previous: Node! init() { next = self previous = self } } extension LinkedList { mutating func copy() -> LinkedList<T> { var copy = LinkedList<T>() for node in self { copy.append(value: node) } return copy } } public struct LinkedList<T> { fileprivate var sentinel = Node<T>() private var mutableSentinel: Node<T> { mutating get { if !isKnownUniquelyReferenced(&sentinel) { sentinel = self.copy().sentinel } return sentinel } } public mutating func append(value: T) { let newNode = Node<T>() newNode.value = value let sentinel = mutableSentinel newNode.next = sentinel newNode.previous = sentinel.previous sentinel.previous.next = newNode sentinel.previous = newNode } public func value(at index: Int) -> T? { return node(at: index)?.value } private func node(at index: Int) -> Node<T>? { if index >= 0 { var node = sentinel.next! var i = index while let _ = node._value { if i == 0 { return node } i -= 1 node = node.next } } return nil } public mutating func remove(at index: Int) -> T? { let _ = mutableSentinel let found = node(at: index) guard let node = found else { return nil } return remove(node) } public func remove(_ node: Node<T>) -> T { node.previous.next = node.next node.next.previous = node.previous return node.value } public mutating func removeAll() { let sentinel = mutableSentinel sentinel.next = sentinel sentinel.previous = sentinel } } extension LinkedList: CustomStringConvertible { public var description: String { var text = "[" var node = sentinel.next! while let value = node._value { text += "\(value)" node = node.next if node._value != nil { text += ", " } } return text + "]" } } public struct LinkedListIterator<T>: IteratorProtocol { var node: Node<T> mutating public func next() -> T? { let next = node.next! guard let value = next._value else { return nil } defer { node = next } return value } } extension LinkedList: Sequence { public func makeIterator() -> LinkedListIterator<T> { return LinkedListIterator(node: sentinel) } } var list = LinkedList<Int>() list.append(value: 0) list.append(value: 1) list.append(value: 2) list.append(value: 3) list.append(value: 4) print("Original \(list)") var copy = list copy.remove(at: 2) print("Copy \(copy)") print("List \(list)") list.value(at: 2) //: [Next](@next)
71429fb584fe34a40463b92a3255c6d2
20.272727
57
0.522894
false
false
false
false
vernon99/Gamp
refs/heads/master
Gamp/AppViewController.swift
gpl-3.0
1
// // AppViewController.swift // Gamp // // Created by Mikhail Larionov on 7/19/14. // Copyright (c) 2014 Mikhail Larionov. All rights reserved. // import UIKit class AppViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollForCards: UIScrollView! var cards:Array<GACardView> = [] override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.view.backgroundColor = UIColor.whiteColor() // Label var label = UILabel(frame: CGRectMake(0, 0, 200, 20)) label.center = CGPointMake(self.view.frame.width/2, 40) label.textAlignment = NSTextAlignment.Center label.textColor = PNGreenColor label.font = UIFont(name: "Avenir-Medium", size:23.0) label.text = "General metrics" self.view.addSubview(label) // Card for var buildNumber = 0; buildNumber < builds.count; buildNumber++ { var card:GACardView? = GACardView.instanceFromNib() if let currentCard = card { // Build number currentCard.buildString = builds[buildNumber].build // Date and time let dateStringFormatter = NSDateFormatter() dateStringFormatter.dateFormat = "MM.dd.yyyy" var startDate = dateStringFormatter.dateFromString(builds[buildNumber].date) var endDate = (buildNumber == 0 ? NSDate(timeIntervalSinceNow: -86400*1) : dateStringFormatter.dateFromString(builds[buildNumber-1].date)) var endDateMinusMonth = endDate.dateByAddingTimeInterval(-86400*30) if endDateMinusMonth.compare(startDate) == NSComparisonResult.OrderedDescending { startDate = endDateMinusMonth } currentCard.startDate = startDate currentCard.endDate = endDate var dateEnd = NSDate(timeIntervalSinceNow: -86400*1) var dateStart = NSDate(timeIntervalSinceNow: -86400*31) // Sizing and updating card layout currentCard.frame.origin = CGPoint(x: Int(currentCard.frame.width)*buildNumber, y: 50) currentCard.frame.size.height = self.view.frame.size.height - currentCard.frame.origin.y; currentCard.prepare() // Adding to the scroll and to the array cards.append(currentCard) self.scrollForCards.addSubview(currentCard) // Changing scroll size if buildNumber == 0 { currentCard.load() self.scrollForCards.frame.size.width = currentCard.frame.width self.scrollForCards.contentSize = CGSize(width: currentCard.frame.width * CGFloat(builds.count), height: self.scrollForCards.frame.height) } } } } func scrollViewDidScroll(scrollView: UIScrollView!) { var indexOfPage = scrollForCards.contentOffset.x / scrollForCards.frame.width; var currentPage = Int(indexOfPage); if !cards[currentPage].loadingStarted { cards[currentPage].load() } } init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } }
0042d5329f391f54370e5c8d671a363d
38.233333
158
0.590767
false
true
false
false
avinassh/Calculator-Swift
refs/heads/master
Calculator/CalculatorBrain.swift
mit
1
// // CalculatorBrain.swift // Calculator // // Created by avi on 09/02/15. // Copyright (c) 2015 avi. All rights reserved. // import Foundation class CalculatorBrain { private enum Op: Printable { case Operand(Double) case UnaryOperation(String, Double -> Double) case BinaryOperation(String, (Double, Double) -> Double) var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _): return symbol } } } } // Alternatives: // var opStack: Array<Op> = Array<Op>() // var opStack = Array<Op>() private var opStack = [Op]() // Alternatives: // var knownOps = Dictionary<String, Op>() private var knownOps = [String: Op]() // init does not require func keyword init() { func learnOp(op: Op) { knownOps[op.description] = op } learnOp(Op.BinaryOperation("+", +)) learnOp(Op.BinaryOperation("−") { $1 - $0 }) learnOp(Op.BinaryOperation("×", *)) learnOp(Op.BinaryOperation("÷") { $1 / $0 }) learnOp(Op.UnaryOperation("√", sqrt)) learnOp(Op.UnaryOperation("cos", cos)) learnOp(Op.UnaryOperation("sin", sin)) } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { // type of operation is Optional Op (CalculatorBrain.Op?) opStack.append(operation) } return evaluate() } func evaluate() -> Double? { let (result, remainder) = evaluate(opStack) println("\(opStack) = \(result) with \(remainder) left over") return result } private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case Op.Operand(let operand): return (operand, remainingOps) case Op.UnaryOperation(_, let operation): let operandEvaluation = evaluate(remainingOps) // following might work: //return (operation(operandEvaluation.result!), operandEvaluation.remainingOps) // however if result is nil, exception will be thrown and // crash our app if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } // now, in case result is nil, the if block will fail and // // control will come out and return (nil, ops) case Op.BinaryOperation(_, let operation): let op1Evalution = evaluate(remainingOps) if let operand1 = op1Evalution.result { let op2Evalution = evaluate(op1Evalution.remainingOps) if let operand2 = op2Evalution.result { return (operation(operand1, operand2), op2Evalution.remainingOps) } } } } return (nil, ops) } }
f735907463c83454abd26d26c92fc655
33.49505
95
0.5412
false
false
false
false
everald/JetPack
refs/heads/master
Sources/UI/ShapeView.swift
mit
1
import UIKit @objc(JetPack_ShapeView) open class ShapeView: View { private var normalFillColor: UIColor? private var normalStrokeColor: UIColor? public override init() { super.init() if let layerFillColor = shapeLayer.fillColor { fillColor = UIColor(cgColor: layerFillColor) } if let layerStrokeColor = shapeLayer.strokeColor { strokeColor = UIColor(cgColor: layerStrokeColor) } } public required init?(coder: NSCoder) { super.init(coder: coder) if let layerFillColor = shapeLayer.fillColor { fillColor = UIColor(cgColor: layerFillColor) } if let layerStrokeColor = shapeLayer.strokeColor { strokeColor = UIColor(cgColor: layerStrokeColor) } } open override func action(for layer: CALayer, forKey event: String) -> CAAction? { switch event { case "fillColor", "path", "strokeColor": if let animation = super.action(for: layer, forKey: "opacity") as? CABasicAnimation { animation.fromValue = shapeLayer.path animation.keyPath = event return animation } fallthrough default: return super.action(for: layer, forKey: event) } } open var fillColor: UIColor? { get { return normalFillColor } set { guard newValue != normalFillColor else { return } normalFillColor = newValue shapeLayer.fillColor = newValue?.tinted(with: tintColor).cgColor } } public var fillColorDimsWithTint = false { didSet { guard fillColorDimsWithTint != oldValue else { return } updateActualFillColor() } } @available(*, unavailable, message: "Don't override this.") // cannot mark as final open override class var layerClass: AnyClass { return CAShapeLayer.self } open var path: UIBezierPath? { get { guard let layerPath = shapeLayer.path else { return nil } return UIBezierPath(cgPath: layerPath) } set { let shapeLayer = self.shapeLayer guard let path = newValue else { shapeLayer.path = nil return } shapeLayer.fillRule = path.usesEvenOddFillRule ? .evenOdd : .nonZero switch path.lineCapStyle { case .butt: shapeLayer.lineCap = .butt case .round: shapeLayer.lineCap = .round case .square: shapeLayer.lineCap = .square } var dashPatternCount = 0 path.getLineDash(nil, count: &dashPatternCount, phase: nil) var dashPattern = [CGFloat](repeating: 0, count: dashPatternCount) var dashPhase = CGFloat(0) path.getLineDash(&dashPattern, count: nil, phase: &dashPhase) shapeLayer.lineDashPattern = dashPattern.map { $0 as NSNumber } shapeLayer.lineDashPhase = dashPhase switch path.lineJoinStyle { case .bevel: shapeLayer.lineJoin = .bevel case .miter: shapeLayer.lineJoin = .miter case .round: shapeLayer.lineJoin = .round } shapeLayer.lineWidth = path.lineWidth shapeLayer.miterLimit = path.miterLimit shapeLayer.path = path.cgPath } } public private(set) final lazy var shapeLayer: CAShapeLayer = self.layer as! CAShapeLayer open var strokeEnd: CGFloat { get { return shapeLayer.strokeEnd } set { shapeLayer.strokeEnd = newValue } } open var strokeColor: UIColor? { get { return normalStrokeColor } set { guard newValue != normalStrokeColor else { return } normalStrokeColor = newValue shapeLayer.strokeColor = newValue?.tinted(with: tintColor).cgColor } } public var strokeColorDimsWithTint = false { didSet { guard strokeColorDimsWithTint != oldValue else { return } updateActualStrokeColor() } } open var strokeStart: CGFloat { get { return shapeLayer.strokeStart } set { shapeLayer.strokeStart = newValue } } open override func tintColorDidChange() { super.tintColorDidChange() if let originalFillColor = normalFillColor, originalFillColor.tintAlpha != nil { shapeLayer.fillColor = originalFillColor.tinted(with: tintColor).cgColor } if let originalStrokeColor = normalStrokeColor, originalStrokeColor.tintAlpha != nil { shapeLayer.strokeColor = originalStrokeColor.tinted(with: tintColor).cgColor } } private func updateActualFillColor() { let actualFillColor = normalFillColor?.tinted(for: self, dimsWithTint: fillColorDimsWithTint).cgColor guard actualFillColor != shapeLayer.fillColor else { return } shapeLayer.fillColor = actualFillColor } private func updateActualStrokeColor() { let actualStrokeColor = normalStrokeColor?.tinted(for: self, dimsWithTint: strokeColorDimsWithTint).cgColor guard actualStrokeColor != shapeLayer.strokeColor else { return } shapeLayer.strokeColor = actualStrokeColor } }
9c6b7476f3c6a9ab6780ee6068488def
20.819048
109
0.716718
false
false
false
false
lukevanin/onthemap
refs/heads/master
OnTheMap/LoginViewController.swift
mit
1
// // LoginViewController.swift // OnTheMap // // Created by Luke Van In on 2017/01/12. // Copyright © 2017 Luke Van In. All rights reserved. // // View controller for login and signup. Presented modally by the tab bar controller. // import UIKit import SafariServices import FBSDKLoginKit // // Delegate for the login controller. Delegates login actions to an external object. // class LoginViewController: UIViewController { enum State { case pending case busy } private let contentSegue = "content" private var state: State = .pending { didSet { updateState() } } // MARK: Outlets @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var udacityLoginButton: UIButton! @IBOutlet weak var facebookLoginButton: UIButton! @IBOutlet weak var signupButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: Actions // // // @IBAction func unwindToLogin(_ segue: UIStoryboardSegue) { } // // Sign up button tapped. Show web view to allow user to create an account. // @IBAction func onSignUpAction(_ sender: Any) { resignResponders() let url = URL(string: "https://www.udacity.com/account/auth#!/signup") let viewController = SFSafariViewController(url: url!) present(viewController, animated: true, completion: nil) } // // Udacity login button tapped. Try to authenticate the user with the entered username and password. // @IBAction func onUdacityLoginAction(_ sender: Any) { // Resign focus from any input fields to dismiss the keyboard. resignResponders() // Get username text input. Show an error if the username field is blank. guard let username = usernameTextField.text, !username.isEmpty else { let message = "Please enter a username." showAlert(forErrorMessage: message) { [weak self] in self?.usernameTextField.becomeFirstResponder() } return } // Get password text input. Show an error if the password field is blank. guard let password = passwordTextField.text, !password.isEmpty else { let message = "Please enter a password." showAlert(forErrorMessage: message) { [weak self] in self?.passwordTextField.becomeFirstResponder() } return } // Attempt authentication with username and password. state = .busy let userService = UdacityUserService() let interactor = LoginUseCase( request: .credentials(username: username, password: password), service: userService, completion: handleLoginResult ) interactor.execute() } // // Facebook login button tapped. Authenticate the user with Facebook, then authorize the token with Udacity API. // @IBAction func onFacebookLoginAction(_ sender: Any) { // Resign focus from any input fields to dismiss the keyboard. resignResponders() state = .busy facebookLogin(completion: handleLoginResult) } // // // private func facebookLogin(completion: @escaping (Result<Bool>) -> Void) { let login = FBSDKLoginManager() let permissions = ["public_profile"] login.logIn(withReadPermissions: permissions, from: self) { (result, error) in // Show an error alert if an error occurred... if let error = error { completion(.failure(error)) return } // ... otherwise login with the facebook token. guard let result = result else { // Facebook login did not return an error or a result. Show error and go back to pending. let error = ServiceError.response completion(.failure(error)) return } guard !result.isCancelled else { // Operation cancelled by user. Just go back to the pending state. completion(.success(false)) return } guard let token = result.token.tokenString else { // No token returned in result. let error = ServiceError.authentication completion(.failure(error)) return } // Login to udacity with facebook token. let interactor = LoginUseCase( request: .facebook(token: token), service: UdacityUserService(), completion: completion ) interactor.execute() } } // // // private func handleLoginResult(_ result: Result<Bool>) { DispatchQueue.main.async { self.state = .pending switch result { case .success(let isAuthenticated): // Logged in successfully with facebook. if isAuthenticated { self.showContent() } case .failure(let error): // Facebook login failed. Show error self.showAlert(forError: error) } } } // // Resign focus from the input texfield and dismiss the keyboard. // private func resignResponders() { usernameTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } // // Show the primary app content after successful login. // private func showContent() { performSegue(withIdentifier: self.contentSegue, sender: nil) } // MARK: View life cycle override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateState() } // MARK: State // // Update the UI to display the current state. Disables input fields and shows activity indicator while login is // in progress. // private func updateState() { switch state { case .pending: configureUI(inputEnabled: true, activityVisible: false) case .busy: configureUI(inputEnabled: false, activityVisible: true) } } // // Configure the UI with the state. Disables/enables text and button interaction, and shows/hides activity // indicator. // private func configureUI(inputEnabled: Bool, activityVisible: Bool) { usernameTextField.isEnabled = inputEnabled passwordTextField.isEnabled = inputEnabled udacityLoginButton.isEnabled = inputEnabled facebookLoginButton.isEnabled = inputEnabled signupButton.isEnabled = inputEnabled if activityVisible { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } } // // Text field delegate for login controller. // extension LoginViewController: UITextFieldDelegate { // // Dismiss keyboard when done button is tapped. // func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
471756fcd616321af069c3e04d6f7926
29.220472
118
0.585461
false
false
false
false
apple/swift-argument-parser
refs/heads/main
Tests/ArgumentParserUnitTests/InputOriginTests.swift
apache-2.0
1
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import XCTest @testable import ArgumentParser final class InputOriginTests: XCTestCase {} extension InputOriginTests { func testIsDefaultValue() { func Assert(elements: [InputOrigin.Element], expectedIsDefaultValue: Bool) { let inputOrigin = InputOrigin(elements: elements) if expectedIsDefaultValue { XCTAssertTrue(inputOrigin.isDefaultValue) } else { XCTAssertFalse(inputOrigin.isDefaultValue) } } Assert(elements: [], expectedIsDefaultValue: false) Assert(elements: [.defaultValue], expectedIsDefaultValue: true) Assert(elements: [.argumentIndex(SplitArguments.Index(inputIndex: 1))], expectedIsDefaultValue: false) Assert(elements: [.defaultValue, .argumentIndex(SplitArguments.Index(inputIndex: 1))], expectedIsDefaultValue: false) } }
045afe82029c7a9803948c5c6a0ba01e
37.212121
121
0.650278
false
true
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/Specification/Operator.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. /// AND operator /// /// Combine two specifications into a single specification. /// /// This is a shorthand for the `Specification.and()` function. /// /// Both the `left` specifiction and the `right` specifiction must be satisfied. /// /// ## Example /// /// `let spec = onlyDigits & between2And4Letters & modulus13Checksum` /// /// /// - parameter left: The specification to be checked first. /// - parameter right: The specification to be checked last. /// /// - returns: A combined specification public func & (left: Specification, right: Specification) -> Specification { return left.and(right) } /// OR operator /// /// Combine two specifications into a single specification. /// /// This is a shorthand for the `Specification.or()` function. /// /// Either the `left` specifiction or the `right` specifiction must be satisfied. /// /// ## Example /// /// `let spec = connectionTypeWifi | connectionType4G | hasOfflineData` /// /// /// - parameter left: The specification to be checked first. /// - parameter right: The specification to be checked last. /// /// - returns: A combined specification public func | (left: Specification, right: Specification) -> Specification { return left.or(right) } /// Negate operator /// /// This is a shorthand for the `Specification.not()` function. /// /// This specifiction is satisfied, when the given specification is not satisfied. /// /// This specifiction is not satisfied, when the given specification is satisfied. /// /// ## Example /// /// `let spec = ! filesystemIsFull` /// /// /// - parameter specification: The specification to be inverted. /// /// - returns: A specification public prefix func ! (specification: Specification) -> Specification { return specification.not() } /// Equivalence operator /// /// This is a shorthand for the `Specification.isSatisfiedBy()` function /// /// ## Example: /// /// `let spec = CharacterSetSpecification.decimalDigits` /// `spec == "123"` /// /// /// - parameter left: The specification that is to perform the checking /// - parameter right: The candidate object that is to be checked. /// /// - returns: `true` if the candidate object satisfies the specification, `false` otherwise. public func == (left: Specification, right: Any?) -> Bool { return left.isSatisfiedBy(right) } /// Not equivalent operator /// /// This is a shorthand for the `Specification.isSatisfiedBy()` function /// /// ## Example: /// /// `let spec = CharacterSetSpecification.decimalDigits` /// `spec != "123"` /// /// /// - parameter left: The specification that is to perform the checking /// - parameter right: The candidate object that is to be checked. /// /// - returns: `true` if the candidate object doesn't satisfy the specification, `false` otherwise. public func != (left: Specification, right: Any?) -> Bool { return !left.isSatisfiedBy(right) }
f1bee6cdfe27a47113117eefd80ab341
28.393939
99
0.693814
false
false
false
false
authorfeng/argparse.swift
refs/heads/master
argparse.swift
unlicense
1
// // argparse.swift // // Created by authorfeng on 27/08/2017. // Copyright © 2017 Author Feng. All rights reserved. // import Foundation // MARK:- Const let SUPPRESS = "==SUPPRESS==" let OPTIONAL = "?" let ZERO_OR_MORE = "*" let ONE_OR_MORE = "+" let PARSER = "A..." let REMAINDER = "..." let _UNRECOGNIZED_ARGS_ATTR = "_unrecognized_args" // MARK:- Utility functions and classes func hasatter(_ obj: Any, _ name: String) -> Bool { let mirror = Mirror(reflecting: obj) for case let (label?, _) in mirror.children { if label == name { return true } } return false } func getEnvironmentVar(_ name: String) -> String? { guard let rawValue = getenv(name) else { return nil } return String(utf8String: rawValue) } func setEnvironmentVar(name: String, value: String, overwrite: Bool) { setenv(name, value, overwrite ? 1 : 0) } struct RegexHelper { let regex: NSRegularExpression? init(_ pattern: String) { regex = try! NSRegularExpression(pattern: "^-\\d+$|^-\\d*\\.\\d+$", options: NSRegularExpression.Options.caseInsensitive) } func match(_ input: String) -> Bool { if let matchs = regex?.matches(in: input, range: NSMakeRange(0, input.utf8.count)) { return matchs.count > 0 } else { return false } } } extension String { static let None = "" static let identifierMatcher = RegexHelper("[a-z0-9A-Z\\_]*") subscript (i: Int) -> Character { return self[self.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return self[start..<end] } subscript (r: ClosedRange<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return self[start...end] } func substring(from index: Int) -> String { return self.substring(from: self.index(self.startIndex, offsetBy: index)) } func substring(to index: Int) -> String { return self.substring(to: self.index(self.startIndex, offsetBy: index)) } func lstrip(inStr: String=" ") -> String { let trimedStr = self.trimmingCharacters(in: CharacterSet(charactersIn: inStr)) if trimedStr.isEmpty { return trimedStr } let range = self.localizedStandardRange(of: trimedStr) return self.substring(from:range!.lowerBound) } func join(_ objs: Array<Any>) -> String { var js = "" if objs.isEmpty { return js } for obj in objs { js += "\(obj)\(self)" } return js.substring(to: js.index(js.startIndex, offsetBy: js.utf8.count - self.utf8.count)) } func split(_ separator: String, _ maxSplits: Int) -> Array<String> { if maxSplits == 0 { return [self] } let arr = self.components(separatedBy: separator) if maxSplits < 0 || maxSplits + 1 >= arr.count { return arr } var retArr = Array(arr[arr.startIndex ..< maxSplits]) retArr.append("=".join(Array(arr[maxSplits ..< arr.endIndex]))) return retArr } func isidentifier() -> Bool { return String.identifierMatcher.match(self) } } extension Dictionary { func hasKey(_ key: Key) -> Bool { return self.keys.contains(key) } func hasattr(_ key: Key) -> Bool { return self.hasKey(key) } mutating func setattr(_ key: Key, _ value: Value) -> Void { self.updateValue(value, forKey: key) } mutating func setdefault(forKey key: Key, _ `default`: Value?=nil) -> Value? { if self.hasKey(key) { return self[key]! } else { if let deft = `default` { self.updateValue(deft, forKey: key) return deft } else { return nil } } } func get(forKey: Key, `default`: Value) -> Value { if self.hasKey(forKey) { return self[forKey]! } else { return `default` } } mutating func pop(forKey: Key, _ `default`: Value) -> Value { self.setdefault(forKey: forKey, `default`) return self.removeValue(forKey: forKey)! } mutating func update(_ dic: Dictionary<Key, Value>) { for k in dic.keys { self.updateValue(dic[k]!, forKey: k) } } } protocol _AttributeHolder { typealias Attribute = (String, Any?) var __dict__: Dictionary<String, Any?> { get } func __repr__() -> String func _get_kwargs() -> [Attribute] func _get_args() -> [Any] } extension _AttributeHolder { public func __repr__() -> String { let type_name = type(of: self) var arg_strings: [String] = [] var star_args: [String: Any] = [:] for arg in self._get_args() { arg_strings.append("\(arg)") } for (name, value) in self._get_kwargs() { if name.isidentifier() { arg_strings.append("\(name)=\(String(describing: value))") } else { star_args[name] = value } } if !star_args.isEmpty { arg_strings.append("**\(star_args)") } return "\(type_name)(\(", ".join(arg_strings))))" } public func _get_kwargs() -> [Attribute] { var kwargs: [Attribute] = [] for key in self.__dict__.keys.sorted() { kwargs.append((key, self.__dict__[key])) } return kwargs } public func _get_args() -> [Any] { return [] } } // MARK:- Formatting Help class _Formatter { func _indent() { } } class HelpFormatter: _Formatter { var _current_indent = 0 var _indent_increment = 0 var _max_help_position = 0 var _action_max_length = 0 var _level = 0 var _width = 80 var _prog = String.None var _root_section: _Section = _Section() let _whitespace_matcher: RegexHelper let _long_break_matcher: RegexHelper override init() { self._whitespace_matcher = RegexHelper(String.None) self._long_break_matcher = self._whitespace_matcher } required init(_ prog: String, _ indent_increment: Int, _ max_help_position: Int, _ width: Int) { // default setting for width let indent_increment = (indent_increment < 0) ? 2 : indent_increment let max_help_position = (max_help_position < 0) ? 24 : max_help_position let width = (width < 0) ? 80 : width self._prog = prog self._indent_increment = indent_increment self._max_help_position = max_help_position self._max_help_position = min(max_help_position, max(width - 20, indent_increment)) self._width = width self._current_indent = 0 self._level = 0 self._action_max_length = 0 self._whitespace_matcher = RegexHelper("\\s+") self._long_break_matcher = RegexHelper("\\n\\n\\n+") super.init() self._root_section = _Section(self, nil) } // MARK: Section and indentation methods override func _indent() { self._current_indent += self._indent_increment self._level += 1 } func _dedent() { self._current_indent -= self._indent_increment assert(self._current_indent >= 0, "Indent decreased below 0.") self._level -= 1 } class _Section { let formatter: _Formatter let parent: String // todo let heading: String var items: Array<Any> = [] init() { self.formatter = _Formatter() self.parent = String.None self.heading = String.None } init(_ formatter: HelpFormatter, _ parent: String?, _ heading: String=String.None) { self.formatter = formatter if (parent != nil) { self.parent = parent! } else { self.parent = String.None } self.heading = heading self.items = [] } func format_help() -> String { if !self.parent.isEmpty { self.formatter._indent() } return String.None } } func _add_item() { } // MARK: Message building methods func start_section() { } func end_section() { } func add_text(_ text: String) { } func add_usage(_ usage: String) { } func add_argument(_ action: Action) { } func add_arguments(_ actions: Array<Action>) { for action in actions { self.add_argument(action) } } // MARK: Help-formatting methods func format_help() -> String { return "" } func _join_parts(_ part_strings: Array<String>) -> String { return "" } func _format_usage(_ useage: String) -> String { return "" } func _format_actions_usage() -> String { return "" } func _format_text(_ text: String) -> String { return "" } func _format_action(_ action: Action) -> String { return "" } func _format_action_invocation(_ action: Action) -> String { return "" } func _metavar_formatter(_ action: Action, _ default_metavar: String) -> (Int) -> String { let result: String if action.metavar != nil { result = action.metavar! } else if !action.choices.isEmpty { let choice_strs = action.choices.map {String(describing: $0)} result = String("{\(", ".join(choice_strs))}") } else { result = default_metavar } func format(_ tuple_size: Int) -> String { // todo: return result } return format } func _format_args(_ action: Action, _ default_metavar: String) -> String { let get_metavar = self._metavar_formatter(action, default_metavar) var result = "" let metaver = get_metavar(1) if action.nargs == nil { result = metaver } else if let nargs = action.nargs as? String { if nargs == OPTIONAL { result = String("[\(metaver)]") } else if nargs == ZERO_OR_MORE { result = String("[\(metaver) [\(metaver) ...]]") } else if nargs == REMAINDER { result = "..." } else if nargs == PARSER { result = String("\(get_metavar(1)) ...)") } } else if let nargs = action.nargs as? Int { result = " ".join(Array(repeating: metaver, count: nargs)) } return result } func _expand_help(_ action: Action) -> String { return "" } func _iter_indented_subactions(_ action: Action) { } func _split_lines(_ text: String, _ width: Int) -> String { return "" } func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String { return "" } func _get_help_string(_ action: Action) -> String { return action.help } func _get_default_metavar_for_optional(_ action: Action) -> String { return action.dest!.uppercased() } func _get_default_metavar_for_positional(_ action: Action) -> String { return action.dest! } } class RawDescriptionHelpFormatter: HelpFormatter { override func _fill_text(_ text: String, _ width: Int, _ indent: Int) -> String { return "" } } class RawTextHelpFormatter: RawDescriptionHelpFormatter { func _fill_text(_ text: String, _ width: Int) -> String { return "" } } class ArgumentDefaultsHelpFormatter: HelpFormatter { override func _get_help_string(_ action: Action) -> String { return "" } } class MetavarTypeHelpFormatter: HelpFormatter { override func _get_default_metavar_for_optional(_ action: Action) -> String { return "" } override func _get_default_metavar_for_positional(_ action: Action) -> String { return "" } } // MARK:- Options and Arguments func _get_action_name(_ argument: Action) -> String { if !argument.option_strings.isEmpty { return "/".join(argument.option_strings) } else if let metavar = argument.metavar { if metavar != SUPPRESS { return metavar } } else if let dest = argument.dest { if dest != SUPPRESS { return dest } } return String.None } enum AE: Error { case ArgumentError(argument: Any, message: String) case ArgumentTypeError } // MARK:- Action classes let _ACTIONS_DICTIONARY = [ "_StoreAction.Type": _StoreAction.self, "_StoreConstAction.Type": _StoreConstAction.self, "_StoreTrueAction.Type": _StoreTrueAction.self, "_StoreFalseAction.Type": _StoreFalseAction.self, "_AppendAction.Type": _AppendAction.self, "_AppendConstAction.Type": _AppendConstAction.self, "_CountAction.Type": _CountAction.self, "_HelpAction.Type": _HelpAction.self, "_VersionAction.Type": _VersionAction.self, "_SubParsersAction.Type": _SubParsersAction.self, ] func isAction(_ actionName: String) -> Bool { return _ACTIONS_DICTIONARY.hasKey(actionName) } func getAction(_ actionName: String, _ kwargs: Dictionary<String, Any>) -> Action { switch actionName { case "_StoreAction.Type": return _StoreAction(kwargs) case "_StoreConstAction.Type": return _StoreConstAction(kwargs) // case "_StoreTrueAction.Type": // action = _StoreTrueAction(kwargs) // case "_StoreFalseAction.Type": // action = _StoreFalseAction(kwargs) // case "_AppendAction.Type": // action = _AppendAction(kwargs) // case "_AppendConstAction.Type": // action = _AppendConstAction(kwargs) // case "_CountAction.Type": // action = _CountAction(kwargs) case "_HelpAction.Type": return _HelpAction(kwargs) // case "_VersionAction.Type": // action = _VersionAction(kwargs) // case "_SubParsersAction.Type": // action = _SubParsersAction(kwargs) default: return Action() } } class Action: _AttributeHolder, Hashable, Equatable { var __dict__: Dictionary<String, Any?> var container: _ActionsContainer=_ActionsContainer() var required: Bool=false var option_strings: [String] { get { if let option_strings = self.__dict__["option_strings"] as? [String] { return option_strings } else { return [] } } set { self.__dict__.updateValue(newValue, forKey: "option_strings") } } var dest: String? { get { return self.__dict__["dest"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "dest") } } var nargs: Any? { get { return self.__dict__["nargs"] as Any } set { self.__dict__.updateValue(newValue, forKey: "nargs") } } var `const`: Any? { get { return self.__dict__["const"] as Any } set { self.__dict__.updateValue(newValue, forKey: "const") } } var `default`: Any? { get { return self.__dict__["default"] as Any } set { self.__dict__.updateValue(newValue, forKey: "default") } } var type: Any.Type? { get { return self.__dict__["type"] as! Any.Type? } set { self.__dict__.updateValue(newValue, forKey: "type") } } var choices: [Any] { get { if let option_strings = self.__dict__["choices"] as? [Any] { return option_strings } else { return [] } } set { self.__dict__.updateValue(newValue, forKey: "choices") } } var help: String { get { if let help = self.__dict__["help"] as? String { return help } else { return "" } } set { self.__dict__.updateValue(newValue, forKey: "help") } } var metavar: String? { get { return self.__dict__["metavar"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "metavar") } } init() { self.__dict__ = [:] } init(option_strings: Array<String>, dest: String, nargs: String?=nil, `const`: Any?=nil, `default`: Any?=nil, type: Any.Type?=nil, choices: Array<Any>=[], required: Bool=false, help: String=String.None, metavar: String=String.None ) { self.__dict__ = [:] self.option_strings = option_strings self.dest = dest self.nargs = nargs self.`const` = `const` self.`default` = `default` self.type = type self.choices = choices self.required = required self.help = help self.metavar = metavar } func _get_kwargs() -> [Attribute] { let names = [ "option_strings", "dest", "nargs", "const", "default", "type", "choices", "help", "metavar", ] return names.map { ($0, self.__dict__[$0]) } } func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { fatalError("\(type(of: self)).__call__() not defined") } var hashValue: Int { return self.dest!.hashValue } static func == (lhs: Action, rhs: Action) -> Bool { return lhs.hashValue == rhs.hashValue } } class _StoreAction: Action { init(_ kwargs: Dictionary<String, Any>) { if let nargsStr = kwargs["nargs"] as! String? { if let nargNum = Int(nargsStr) { if nargNum == 0 { fatalError("nargs for store actions must be > 0; if you have nothing to store, actions such as store true or store const may be more appropriate") } } } if let constStr = kwargs["const"] as! String? { if !constStr.isEmpty && (kwargs["nargs"] as! String) != OPTIONAL { fatalError("nargs must be \"\(OPTIONAL)\" to supply const") } } super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs["dest"] as! String, nargs: kwargs["nargs"] as! String?, const: kwargs.hasKey("const") ? kwargs["const"] as! String : String.None, default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None, type: kwargs["type"] as? Any.Type, required: kwargs.hasKey("required") ? kwargs["required"] as! Bool : false, help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None, metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { // setattr(namespace, self.dest, values) } } class _StoreConstAction: Action { init(_ kwargs: Dictionary<String, Any>) { super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs["dest"] as! String, nargs: "0", const: kwargs["const"] as! String, default: kwargs.hasKey("default") ? kwargs["default"] as! String : String.None, help: kwargs.hasKey("help") ? kwargs["help"] as! String : String.None, metavar: kwargs.hasKey("metavar") ? kwargs["metavar"] as! String : String.None) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { } } class _StoreTrueAction: Action { } class _StoreFalseAction: Action { } class _AppendAction: Action { } class _AppendConstAction: Action { } class _CountAction: Action { } class _HelpAction: Action { init(_ kwargs: Dictionary<String, Any>) { super.init(option_strings: kwargs["option_strings"] as! Array<String>, dest: kwargs.hasKey("dest") ? kwargs["dest"] as! String : SUPPRESS, nargs: "0", default: kwargs.hasKey("default") ? kwargs["default"] as! String : SUPPRESS, help: kwargs["help"] as! String) } override func __call__(_ parser: ArgumentParser, _ namespace: [String: Any?], _ values: Any, _ option_string: String?=nil) { } } class _VersionAction: Action { } class _SubParsersAction: Action { } // MARK:- Type classes class FileType { init() { } } // MARK:- Optional and Positional Parsing class Namespace: _AttributeHolder { var __dict__: Dictionary<String, Any?> init(_ kwargs: Dictionary<String, Any?>=[:]) { self.__dict__ = [:] for item in kwargs { self.__dict__.updateValue(item.value, forKey: item.key) } } } class _ActionsContainer { var _get_formatter_enable: Bool { get { return false } } var description: String? = nil var prefix_chars: String = "-" var `default`: String? = nil var conflict_handler: String = String.None var _defaults: Dictionary<String, Any> = [:] var _registries: Dictionary<String, Dictionary<String, String>> = [:] var _actions: Array<Action> = [] var _option_string_actions: Dictionary<String, Action> = [:] var _action_groups: Array<_ArgumentGroup> = [] var _mutually_exclusive_groups: Array<_ArgumentGroup> = [] var _negative_number_matcher: RegexHelper = RegexHelper(String.None) var _has_negative_number_optionals: Array<Any> = [] static let _CONFLICT_HANDLER = [ "_handle_conflict_error" : _handle_conflict_error, "_handle_conflict_resolve" : _handle_conflict_resolve, ] init() { } init(description: String?, prefix_chars: String, `default`: String?, conflict_handler: String) { self.description = description self.`default` = `default` self.prefix_chars = prefix_chars self.conflict_handler = conflict_handler // set up registries self._registries = [:] // register actions self.register(registry_name: "action", value: String.None, object: "_StoreAction.Type") self.register(registry_name: "action", value: "store", object: "_StoreAction.Type") self.register(registry_name: "action", value: "store_const", object: "_StoreConstAction.Type") self.register(registry_name: "action", value: "store_true", object: "_StoreTrueAction.Type") self.register(registry_name: "action", value: "store_false", object: "_StoreFalseAction.Type") self.register(registry_name: "action", value: "append", object: "_AppendAction.Type") self.register(registry_name: "action", value: "append_const", object: "_AppendConstAction.Type") self.register(registry_name: "action", value: "count", object: "_CountAction.Type") self.register(registry_name: "action", value: "help", object: "_HelpAction.Type") self.register(registry_name: "action", value: "version", object: "_VersionAction.Type") self.register(registry_name: "action", value: "parsers", object: "_SubParsersAction.Type") // raise an exception if the conflict handler is invalid self._get_handler() // action storage self._actions = [] self._option_string_actions = [:] // groups self._action_groups = [] self._mutually_exclusive_groups = [] // defaults storage self._defaults = [:] // determines whether an "option" looks like a negative number self._negative_number_matcher = RegexHelper("^-\\d+$|^-\\d*\\.\\d+$") // whether or not there are any optionals that look like negative // numbers -- uses a list so it can be shared and edited self._has_negative_number_optionals = [] } // MARK: Registration methods func register(registry_name: String, value: String, object: String) -> Void { self._registries.setdefault(forKey: registry_name, [:]) self._registries[registry_name]?.updateValue(object, forKey: value) } func _registry_get(registry_name: String, value: String, `default`: String=String.None) -> String { return self._registries[registry_name]!.get(forKey: value, default: `default`) } // MARK: Namespace default accessor methods func set_defaultsset_defaults(_ kwargs: Dictionary<String, Any>){ } func get_default() -> Any { return "" } // MARK: Adding argument actions func add_argument(_ args: String..., kwargs: Dictionary<String, Any>=[:]) -> Action { // if no positional args are supplied or only one is supplied and // it doesn't look like an option string, parse a positional argument let chars = self.prefix_chars var kwargs = kwargs if args.isEmpty || args.count == 1 && !chars.contains(args[0][0]){ if !args.isEmpty && kwargs.hasKey("dest") { fatalError("dest supplied twice for positional argument") } kwargs = self._get_positional_kwargs(dest: args.first!, kwargs: kwargs) } else { kwargs = self._get_optional_kwargs(args: args, kwargs: kwargs) } // otherwise, we're adding an optional argument if !kwargs.hasKey("default") { let dest = kwargs["dest"] as! String if self._defaults.keys.contains(dest) { kwargs["default"] = self._defaults[dest] } else if let deft = self.`default` { kwargs["default"] = deft } } // create the action object, and add it to the parser let actionName = self._pop_action_class(kwargs: kwargs) if !isAction(actionName) { fatalError("unknown action \"\(actionName)\"") } let action = getAction(actionName, kwargs) // raise an error if the metavar does not match the type let type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))") // todo // if not callable(type_func) { // fatalError("\(actionName) is not callable") // } // raise an error if the metavar does not match the type if self._get_formatter_enable { self._get_formatter()._format_args(action, String.None) // todo // catch TypeError // fatalError("length of metavar tuple does not match nargs") } return self._add_action(action) } func add_argument_group(args: String..., kwargs: Dictionary<String, Any>=[:]) -> _ArgumentGroup { let title = (args.count > 0) ? args.first : String.None let description = (args.count > 1) ? args[1] : String.None let group = _ArgumentGroup(container: self, title: title!, description: description, kwargs: kwargs) self._action_groups.append(group) return group } func add_mutually_exclusive_group() -> Void { } func _add_action(_ action: Action) -> Action { // resolve any conflicts self._check_conflict(action) // add to actions list self._actions.append(action) action.container = self // index the action by any option strings it has for option_string in action.option_strings { self._option_string_actions[option_string] = action } // set the flag if any option strings look like negative numbers for option_string in action.option_strings { if self._negative_number_matcher.match(option_string) { if !self._has_negative_number_optionals.isEmpty { self._has_negative_number_optionals.append(true) } } } // return the created action return action } func _get_handler() -> String { let handler_func_name = "_handle_conflict_\(self.conflict_handler)" if _ActionsContainer._CONFLICT_HANDLER.hasKey(handler_func_name) { return handler_func_name } else { fatalError("invalid conflict_resolution value: \(handler_func_name)") } } func _check_conflict(_ action: Action) { // find all options that conflict with this option var confl_optionals: Array<(String, Action)> = [] for option_string in action.option_strings { if self._option_string_actions.hasKey(option_string) { let confl_optional = self._option_string_actions[option_string] confl_optionals.append((option_string, confl_optional!)) } } // resolve any conflicts if !confl_optionals.isEmpty { let conflict_handler_func_name = self._get_handler() self._do_conflict_handle(conflict_handler_func_name, action, confl_optionals) } } func _handle_conflict_error(_ action: Action, _ conflicting_actions: Array<(String, Action)>) { var message = "" // todo ", ".join(conflicting_actions) // todo: ArgumentError fatalError(message) } func _handle_conflict_resolve(_ action: Action, _ confl_optionals: Array<(String, Action)>) { } func _do_conflict_handle(_ conflict_handler_func_name: String, _ action: Action, _ confl_optionals: Array<(String, Action)>) { switch conflict_handler_func_name { case "_handle_conflict_error": self._handle_conflict_error(action, confl_optionals) break case "_handle_conflict_resolve": self._handle_conflict_resolve(action, confl_optionals) break default: break } } func _add_container_actions(_ container: _ActionsContainer) -> Void { } func _get_positional_kwargs(dest: String, kwargs: Dictionary<String, Any>) -> Dictionary<String, Any> { var kwargs = kwargs if kwargs.hasKey("required") { fatalError("'required' is an invalid argument for positionals") } if ![OPTIONAL, ZERO_OR_MORE].contains(kwargs["nargs"] as! String) { kwargs["required"] = true } if kwargs["nargs"] as! String == ZERO_OR_MORE && !kwargs.keys.contains("default") { kwargs["required"] = true } kwargs["dest"] = dest kwargs["option_strings"] = [] return kwargs } func _get_optional_kwargs(args: Array<String>, kwargs: Dictionary<String, Any>) -> Dictionary<String, Any> { // determine short and long option strings var kwargs = kwargs var option_strings: Array<String> = [] var long_option_strings: Array<String> = [] for option_string in args { // error on strings that don't start with an appropriate prefix if !self.prefix_chars.contains(option_string[0]) { fatalError("invalid option string \(option_string): must start with a character \(self.prefix_chars)") } // strings starting with two prefix characters are long options option_strings.append(option_string) if option_string.lengthOfBytes(using: String.Encoding.utf8) > 1 && self.prefix_chars.contains(option_string[1]) { long_option_strings.append(option_string) } } // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' var dest:String = String.None if kwargs.hasKey("dest") { dest = kwargs["dest"] as! String } if dest.isEmpty { var dest_option_string:String if !long_option_strings.isEmpty { dest_option_string = long_option_strings.first! } else { dest_option_string = option_strings.first! } dest = dest_option_string.lstrip(inStr: self.prefix_chars) if dest.isEmpty { fatalError("dest: is required for options like \(option_strings)") } dest = dest.replacingOccurrences(of: "-", with: "_") } // return the updated keyword arguments kwargs["dest"] = dest kwargs["option_strings"] = option_strings return kwargs } func _pop_action_class(kwargs: Dictionary<String, Any>, _ `default`: String=String.None) -> String { var kwargs = kwargs let action = kwargs.pop(forKey: "action", `default`) as! String return self._registry_get(registry_name: "action", value: action, default: action) } func _get_formatter() -> HelpFormatter { fatalError("_get_formatter() not implemented in \(Mirror(reflecting: self).subjectType))") } } class _ArgumentGroup: _ActionsContainer { var title: String = String.None var _group_actions: Array<Action.Type> = [] override init() { super.init() } init(container: _ActionsContainer, title: String=String.None, description: String=String.None, kwargs: Dictionary<String, Any>) { var kwargs = kwargs // add any missing keyword arguments by checking the container kwargs.setdefault(forKey: "conflict_handler", container.conflict_handler) kwargs.setdefault(forKey: "prefix_chars", container.prefix_chars) kwargs.setdefault(forKey: "default", container.`default`) super.init(description: description, prefix_chars: kwargs["prefix_chars"] as! String, default: kwargs["default"] as? String, conflict_handler: kwargs["conflict_handler"] as! String) // group attributes self.title = title self._group_actions = [] // share most attributes with the container self._registries = container._registries self._actions = container._actions self._option_string_actions = container._option_string_actions self._defaults = container._defaults self._has_negative_number_optionals = container._has_negative_number_optionals self._mutually_exclusive_groups = container._mutually_exclusive_groups } } class _MutuallyExclusiveGroup: _ArgumentGroup { } class ArgumentParser: _ActionsContainer, _AttributeHolder { var __dict__: Dictionary<String, Any?> override var _get_formatter_enable: Bool { get { return true } } var allow_abbrev: Bool=true var epilog: String? var fromfile_prefix_chars: String?=nil var _positionals: _ArgumentGroup=_ArgumentGroup() var _optionals: _ArgumentGroup=_ArgumentGroup() var _subparsers: _ArgumentGroup? var prog: String? { get { return self.__dict__["prog"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "prog") } } var formatter_class: HelpFormatter.Type { get { if let formatter_class = self.__dict__["formatter_class"] as? HelpFormatter.Type { return formatter_class } else { return HelpFormatter.self } } set { self.__dict__.updateValue(newValue, forKey: "formatter_class") } } var add_help: Bool { get { if let add_help = self.__dict__["add_help"] as? Bool { return add_help } else { return true } } set { self.__dict__.updateValue(newValue, forKey: "add_help") } } var usage: String? { get { return self.__dict__["usage"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "usage") } } override var description: String? { get { return self.__dict__["description"] as! String? } set { self.__dict__.updateValue(newValue, forKey: "description") } } override var conflict_handler: String { get { if let conflict_handler = self.__dict__["conflict_handler"] as? String { return conflict_handler } else { return "error" } } set { self.__dict__.updateValue(newValue, forKey: "conflict_handler") } } init(prog: String? = nil, usage: String? = nil, description: String? = nil, epilog: String? = nil, parents: Array<_ActionsContainer>=[], formatter_class: HelpFormatter.Type = HelpFormatter.self, prefix_chars: String = "-", fromfile_prefix_chars: String? = nil, `default`: String? = nil, conflict_handler: String = "error", add_help: Bool=true, allow_abbrev: Bool=true) { self.__dict__ = [:] super.init(description: description, prefix_chars: prefix_chars, default: `default`, conflict_handler: conflict_handler) // default setting for prog if let _ = prog { self.prog = prog } else { // todo: path.basename self.prog = CommandLine.arguments[0] } self.usage = usage self.epilog = epilog self.formatter_class = formatter_class self.fromfile_prefix_chars = fromfile_prefix_chars self.add_help = add_help self.allow_abbrev = allow_abbrev self._positionals = self.add_argument_group(args: "positional arguments") self._optionals = self.add_argument_group(args: "optional arguments") self._subparsers = nil // register types class identity: Action { } self.register(registry_name: "type", value: String.None, object: "identity.self") // add help argument if necessary // (using explicit default to override global default) let default_prefix = prefix_chars.contains("-") ? "-" : prefix_chars[0] if self.add_help { self.add_argument(default_prefix+"h", default_prefix+default_prefix+"help", kwargs: ["action": "help", "default": SUPPRESS, "help": "show this help message and exit"]) } // add parent arguments and defaults for parent in parents { self._add_container_actions(parent) // todo // let defaults = parent._defaults // self._defaults.update(defaults) } } // MARK: Pretty __repr__ methods func _get_kwargs() -> [Attribute] { let names = [ "prog", "usage", "description", "formatter_class", "conflict_handler", "add_help", ] return names.map { ($0, self.__dict__[$0]) } } // MARK: Optional/Positional adding methods func add_subparsers(_ kwargs: Dictionary<String, Any>) -> Action { return Action() } // MARK: Command line argument parsing methods func parse_args(_ args: Array<String>=[], _ namespace: Dictionary<String, Any>=[:]) -> Dictionary<String, Any> { let (args, argv) = self.parse_known_args(args: args, namespace: namespace) if !argv.isEmpty { fatalError("unrecognized arguments: \(argv.joined(separator: " "))") } return args } func parse_known_args( args: Array<String>=[], namespace: Dictionary<String, Any>=[:]) -> (Dictionary<String, Any>, Array<String>) { var namespace = namespace var args = args if args.isEmpty { // args default to the system args args = Array(CommandLine.arguments.suffix(from: 1)) } else { // make sure that args are mutable } // default Namespace built from parser defaults // if namespace is None: // namespace = Namespace() // add any action defaults that aren't present for action in self._actions { if action.dest != SUPPRESS { // if !hasattr(obj: namespace, name: action.dest) { if !namespace.hasattr(action.dest!) { var defaultEqualSUPPRESS = false if let `default` = action.`default` as? String { defaultEqualSUPPRESS = (`default` == SUPPRESS) } if !defaultEqualSUPPRESS { namespace.updateValue(action.`default`, forKey: action.dest!) } } } } // add any parser defaults that aren't present for dest in self._defaults.keys { // if !hasattr(obj: namespace, name: dest) { if !namespace.hasattr(dest) { namespace.updateValue(self._defaults[dest], forKey: dest) } } //# parse the arguments and exit if there are any errors (namespace, args) = self._parse_known_args(arg_strings: args, namespace: namespace) // if hasattr(obj: namespace, name: _UNRECOGNIZED_ARGS_ATTR) { if namespace.hasattr(_UNRECOGNIZED_ARGS_ATTR) { args += namespace[_UNRECOGNIZED_ARGS_ATTR] as! Array<String> namespace.removeValue(forKey: _UNRECOGNIZED_ARGS_ATTR) } return (namespace, args) } func _parse_known_args(arg_strings: Array<String>, namespace: Dictionary<String, Any>) -> (Dictionary<String, Any>, Array<String>) { var arg_strings = arg_strings // replace arg strings that are file references if (self.fromfile_prefix_chars != String.None) { arg_strings = self._read_args_from_files(arg_strings: arg_strings) } // map all mutually exclusive arguments to the other arguments // they can't occur with var action_conflicts: Dictionary<Action, Any> = [:] for mutex_group in self._mutually_exclusive_groups { let group_actions = mutex_group._group_actions var c = 0 for mutex_action in mutex_group._group_actions { c += 1 // todo } } // find all option indices, and determine the arg_string_pattern // which has an 'O' if there is an option at an index, // an 'A' if there is an argument, or a '-' if there is a '--' var option_string_indices: Dictionary<Int, Any> = [:] var arg_string_pattern_parts: Array<String> = [] var i = 0 for arg_string in arg_strings { // all args after -- are non-options if arg_string == "--" { arg_string_pattern_parts.append("-") for arg_string in arg_strings { arg_string_pattern_parts.append("A") } } // otherwise, add the arg to the arg strings // and note the index if it was an option else { let option_tuple = self._parse_optional(arg_string) var pattern: String if option_tuple.isEmpty { pattern = "A" } else { option_string_indices[i] = option_tuple pattern = "O" } arg_string_pattern_parts.append(pattern) } } // join the pieces together to form the pattern let arg_strings_pattern = "".join(arg_string_pattern_parts) // converts arg strings to the appropriate and then takes the action var seen_actions = Set<Action>() var seen_non_default_actions = Set<Action>() func take_action(_ action: Action, _ argument_strings: Array<String>, option_string: String?=nil) { seen_actions.insert(action) let argument_values = self._get_values(action, argument_strings) // error if this argument is not allowed with other previously seen arguments, // assuming that actions that use the default value don't really count as "present" if argument_values as! _OptionalNilComparisonType != action.`default` { seen_non_default_actions.insert(action) if let actions = action_conflicts[action] { if let actionArray = actions as? Array<Action> { for conflict_action in actionArray { if seen_non_default_actions.contains(conflict_action) { // raise ArgumentError fatalError("not allowed with argument \(_get_action_name(conflict_action))") } } } } } // take the action if we didn't receive a SUPPRESS value (e.g. from a default) var takeAction = true if let avStr = argument_values as? String { if avStr == SUPPRESS { takeAction = false } } if takeAction { action.__call__(self, namespace, argument_values, option_string) } } return ([:], []) } func _read_args_from_files(arg_strings: Array<String>) -> Array<String> { return arg_strings } func convert_arg_line_to_args(_ arg_line: String) -> Array<String> { return [arg_line] } func _match_argument(_ action: Action, _ arg_strings_pattern: String) -> Int { return 0 } func _match_arguments_partial(_ action: Action, _ arg_strings_pattern: String) -> Array<String> { var result: Array<String> = [] return result } func _parse_optional(_ arg_string: String) -> Array<Any> { // if it's an empty string, it was meant to be a positional if arg_string.isEmpty { return [] } // if it doesn't start with a prefix, it was meant to be positional if !self.prefix_chars.contains(arg_string[0]) { return [] } // if the option string is present in the parser, return the action if self._option_string_actions.hasKey(arg_string) { let action = self._option_string_actions[arg_string] return [action, arg_string, String.None] } // if it's just a single character, it was meant to be positional if arg_string.utf8.count == 1 { return [] } // if the option string before the "=" is present, return the action if arg_string.contains("=") { let splitedStr = arg_string.split("=", 1) let option_string = splitedStr.first! let explicit_arg = splitedStr.last! if self._option_string_actions.hasKey(option_string) { let action = self._option_string_actions[option_string] return [action, option_string, explicit_arg] } } if self.allow_abbrev { // search through all possible prefixes of the option string // and all actions in the parser for possible interpretations let option_tuples = self._get_option_tuples(arg_string) // if multiple actions match, the option string was ambiguous if option_tuples.count > 1 { let options = ", ".join(option_tuples.map {"\($0[1] as! String)"}) self.error("ambiguous option: \(arg_string) could match \(options)") } // if exactly one action matched, this segmentation is good, // so return the parsed action else if option_tuples.count == 1 { return option_tuples.first! } } // if it was not found as an option, but it looks like a negative // number, it was meant to be positional // unless there are negative-number-like options if self._negative_number_matcher.match(arg_string) { if self._has_negative_number_optionals.isEmpty { return [] } } // if it contains a space, it was meant to be a positional if arg_string.contains(" ") { return [] } // it was meant to be an optional but there is no such option // in this parser (though it might be a valid option in a subparser) return [String.None, arg_string, String.None] } func _get_option_tuples(_ option_string: String) -> Array<Array<Any>> { var result: Array<Array<Any>> = [] // option strings starting with two prefix characters are only split at the '=' let chars = self.prefix_chars var option_prefix: String var explicit_arg: String if chars.contains(option_string[0]) && chars.contains(option_string[1]) { if option_string.contains("=") { let arr = option_string.split("=", 1) option_prefix = arr.first! explicit_arg = arr.last! } else { option_prefix = option_string explicit_arg = String.None } for option_string in self._option_string_actions.keys { if option_string.hasPrefix(option_prefix) { let action: Action = self._option_string_actions[option_string]! let tup: Array<Any> = [action, option_string, explicit_arg] result.append(tup) } } } // single character options can be concatenated with their arguments // but multiple character options always have to have their argument separate else if chars.contains(option_string[0]) && !chars.contains(option_string[1]) { option_prefix = option_string explicit_arg = String.None let short_option_prefix = option_string.substring(to: 2) let short_explicit_arg = option_string.substring(from: 2) for option_string in self._option_string_actions.keys { if option_string == short_option_prefix { let action = self._option_string_actions[option_string] let tup: Array<Any> = [action, option_string, short_explicit_arg] result.append(tup) } else if option_string.hasPrefix(option_prefix) { let action = self._option_string_actions[option_string] let tup: Array<Any> = [action, option_string, short_explicit_arg] result.append(tup) } } } // shouldn't ever get here else { self.error("unexpected option string: \(option_string)") } // return the collected option tuples return result } func _get_nargs_pattern(_ action: Action) -> String { return String.None } // MAKR: Value conversion methods func _get_values(_ action: Action, _ arg_strings: Array<String>) -> Any { // for everything but PARSER, REMAINDER args, strip out first '--' var arg_strings = arg_strings var needRemove = true if let nargs = action.nargs as? String { if [PARSER, REMAINDER].contains(nargs) { needRemove = false } } if needRemove { // arg_strings.remove("--") var index = arg_strings.count - 1 while index >= 0 { if "--" == arg_strings[index] { arg_strings.remove(at: index) } index -= 1 } } // optional argument produces a default when not present var value: Any? var otherType = true // all other types of nargs produce a list if let nargs = action.nargs as? String { otherType = false if arg_strings.isEmpty && nargs == OPTIONAL { if action.option_strings.isEmpty { value = action.`const` } else { value = action.`default` } if let valueStr = value as? String { value = self._get_value(action, valueStr) self._check_value(action, value) } } // when nargs='*' on a positional, if there were no command-line // args, use the default if it is anything other than None else if arg_strings.isEmpty && nargs == ZERO_OR_MORE && action.option_strings.isEmpty { if (action.`default` != nil) { value = action.`default` } else { value = arg_strings } self._check_value(action, value) } // single argument or optional argument produces a single value else if arg_strings.count == 1 && nargs == OPTIONAL { let arg_string = arg_strings.first value = self._get_value(action, arg_string!) self._check_value(action, value) } // REMAINDER arguments convert all values, checking none else if nargs == REMAINDER { value = arg_strings.map {self._get_value(action, $0)} } // PARSER arguments convert all values, but check only the first else if nargs == PARSER { value = arg_strings.map {self._get_value(action, $0)} self._check_value(action, (value as! Array<Any>).first) } else { otherType = true } } // single argument or optional argument produces a single value if arg_strings.count == 1 && action.nargs == nil { let arg_string = arg_strings.first value = self._get_value(action, arg_string!) self._check_value(action, value) otherType = false } // all other types of nargs produce a list if otherType { value = arg_strings.map {self._get_value(action, $0)} for v in value as! Array<Any> { self._check_value(action, v) } } // return the converted value return value } func _get_value(_ action: Action, _ arg_string: String) -> Any { var type_func = self._registry_get(registry_name: "type", value: "\(String(describing: action.type))", default: "\(String(describing: action.type))") // todo // check if type_func callable // convert the value to the appropriate type // todo // ArgumentTypeErrors indicate errors // TypeErrors or ValueErrors also indicate errors // return the converted value return arg_string } func _check_value(_ action: Action, _ value: Any) { // converted value must be one of the choices (if specified) // if !action.choices.isEmpty && !action.choices.contains(where: value as! (Any) throws -> Bool) { if false { fatalError("invalid choice: \(value) (choose from \(action.choices))") } } // MARK: Help-formatting methods func format_usage() -> String { return "" } func format_help() -> String { return "" } override func _get_formatter() -> HelpFormatter { return self.formatter_class.init(self.prog!, -1, -1, -1) } // MARK: Help-printing methods func print_usage() { } func print_help() { } func _print_message() { } // MARK: Exiting methods func exit(_ status: Int=0, _ message: String=String.None) { if !message.isEmpty { } } func error(_ message: String) { } }
49f63731d52c228a7980c092f749248d
31.542857
189
0.553468
false
false
false
false
qutheory/vapor
refs/heads/main
Sources/XCTVapor/XCTHTTPResponse.swift
mit
2
public struct XCTHTTPResponse { public var status: HTTPStatus public var headers: HTTPHeaders public var body: ByteBuffer } extension XCTHTTPResponse { private struct _ContentContainer: ContentContainer { var body: ByteBuffer var headers: HTTPHeaders var contentType: HTTPMediaType? { return self.headers.contentType } mutating func encode<E>(_ encodable: E, using encoder: ContentEncoder) throws where E : Encodable { fatalError("Encoding to test response is not supported") } func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable { try decoder.decode(D.self, from: self.body, headers: self.headers) } func decode<C>(_ content: C.Type, using decoder: ContentDecoder) throws -> C where C : Content { var decoded = try decoder.decode(C.self, from: self.body, headers: self.headers) try decoded.afterDecode() return decoded } } public var content: ContentContainer { _ContentContainer(body: self.body, headers: self.headers) } } extension Response.Body { var isEmpty: Bool { return self.count == 0 } } public func XCTAssertContent<D>( _ type: D.Type, _ res: XCTHTTPResponse, file: StaticString = #file, line: UInt = #line, _ closure: (D) throws -> () ) rethrows where D: Decodable { guard let contentType = res.headers.contentType else { XCTFail("response does not contain content type", file: (file), line: line) return } let content: D do { let decoder = try ContentConfiguration.global.requireDecoder(for: contentType) content = try decoder.decode(D.self, from: res.body, headers: res.headers) } catch { XCTFail("could not decode body: \(error)", file: (file), line: line) return } try closure(content) } public func XCTAssertContains(_ haystack: String?, _ needle: String?, file: StaticString = #file, line: UInt = #line) { let file = (file) switch (haystack, needle) { case (.some(let haystack), .some(let needle)): XCTAssert(haystack.contains(needle), "\(haystack) does not contain \(needle)", file: file, line: line) case (.some(let haystack), .none): XCTFail("\(haystack) does not contain nil", file: file, line: line) case (.none, .some(let needle)): XCTFail("nil does not contain \(needle)", file: file, line: line) case (.none, .none): XCTFail("nil does not contain nil", file: file, line: line) } } public func XCTAssertEqualJSON<T>(_ data: String?, _ test: T, file: StaticString = #file, line: UInt = #line) where T: Codable & Equatable { guard let data = data else { XCTFail("nil does not equal \(test)", file: (file), line: line) return } do { let decoded = try JSONDecoder().decode(T.self, from: Data(data.utf8)) XCTAssertEqual(decoded, test, file: (file), line: line) } catch { XCTFail("could not decode \(T.self): \(error)", file: (file), line: line) } }
ab199c01ef05e67c9d2942578ae81c36
31.265306
119
0.623023
false
false
false
false
wrengels/Amplify4
refs/heads/master
Amplify4/Amplify4/Amplify4/Document.swift
gpl-2.0
1
// // Document.swift // Amplify4 // // Created by Bill Engels on 1/15/15. // Copyright (c) 2015 Bill Engels. All rights reserved. // import Cocoa class Document: NSDocument { var text = "" override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) // Add any code here that needs to be executed once the windowController has loaded the document's window. } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String? { // Returns the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead. return "Document" } override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } }
d89533d14536cb3855b050efbefa53ea
40.277778
198
0.708389
false
false
false
false
DannyvanSwieten/SwiftSignals
refs/heads/master
GameEngine/Grid.swift
gpl-3.0
1
// // Grid.swift // SwiftEngine // // Created by Danny van Swieten on 2/15/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import Foundation class Grid<T: Arithmetic> { var data: UnsafeMutablePointer<T>? var size = 0 init(aSize: Int) { size = aSize data = UnsafeMutablePointer<T>.alloc(size * size) } deinit { data?.destroy() } subscript(row: Int) -> UnsafeMutablePointer<T> { return data!.advancedBy(row * size) } } func heightMap(size: Int, initialValue: Float) -> Grid<Float>{ let grid = Grid<Float>(aSize: size) grid[0][0] = fmodf(Float(rand()), 1.0) grid[0][size] = fmodf(Float(rand()), 1.0) grid[size][size] = fmodf(Float(rand()), 1.0) grid[size][0] = fmodf(Float(rand()), 1.0) return grid }
67802e357dcad7089782f41f876933d1
20.692308
62
0.577515
false
false
false
false
daniel-barros/Comedores-UGR
refs/heads/master
Comedores UGR/MenuTableViewController.swift
mit
1
// // MenuTableViewController.swift // Comedores UGR // // Created by Daniel Barros López on 3/9/16. /* MIT License Copyright (c) 2016 Daniel Barros Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // import UIKit import EventKitUI import SafariServices class MenuTableViewController: UITableViewController { let fetcher = WeekMenuFetcher() var weekMenu = [DayMenu]() var error: FetcherError? var lastTimeTableViewReloaded: Date? /// `false` when there's a saved menu or the vc has already fetched since viewDidLoad(). var isFetchingForFirstTime = true fileprivate let lastUpdateRowHeight: CGFloat = 46.45 // MARK: - override func viewDidLoad() { super.viewDidLoad() weekMenu = fetcher.savedMenu ?? [] NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 150 if weekMenu.isEmpty == false { tableView.contentOffset.y = lastUpdateRowHeight // Hides "last update" row isFetchingForFirstTime = false } refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: #selector(fetchData), for: .valueChanged) updateSeparatorsInset(for: tableView.frame.size) if fetcher.needsToUpdateMenu { if isFetchingForFirstTime { refreshControl!.layoutIfNeeded() refreshControl!.beginRefreshing() tableView.contentOffset.y = -tableView.contentInset.top } fetchData() } } deinit { NotificationCenter.default.removeObserver(self) } func appDidBecomeActive(_ notification: Notification) { // Menu was updated externally and changes need to be reflected in UI if let savedMenu = fetcher.savedMenu, savedMenu != weekMenu { self.error = nil weekMenu = savedMenu tableView.reloadData() } else { // This makes sure that only the date for today's menu is highlighted if let lastReload = lastTimeTableViewReloaded, Calendar.current.isDateInToday(lastReload) == false { tableView.reloadData() } // Menu needs to be updated if fetcher.needsToUpdateMenu { fetchData() } } } func fetchData() { if fetcher.isFetching == false { fetcher.fetchMenu(completionHandler: { menu in self.error = nil let menuChanged = self.weekMenu != menu self.weekMenu = menu self.lastTimeTableViewReloaded = Date() self.isFetchingForFirstTime = false mainQueue { if menuChanged { self.tableView.reloadData() } else { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row } UIView.animate(withDuration: 0.5) { if self.refreshControl!.isRefreshing { self.refreshControl!.endRefreshing() } } } }, errorHandler: { error in self.error = error self.lastTimeTableViewReloaded = Date() self.isFetchingForFirstTime = false mainQueue { if self.weekMenu.isEmpty { self.tableView.reloadData() } else { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row showing error message temporarily delay(1) { self.error = nil // Next time first cell is loaded it will show last update date instead of error message } } UIView.animate(withDuration: 0.5) { if self.refreshControl!.isRefreshing { self.refreshControl!.endRefreshing() } } } }) } } @IBAction func prepareForUnwind(_ segue: UIStoryboardSegue) { } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) updateSeparatorsInset(for: size) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if weekMenu.isEmpty { return isFetchingForFirstTime ? 0 : 1 } return weekMenu.count + 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if weekMenu.isEmpty == false { // First row shows error message if any (eventually dismissed, see fetchData()), or last update date if indexPath.row == 0 { if let error = error { let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell cell.configure(with: error) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "LastUpdateCell", for: indexPath) as! LastUpdateTableViewCell cell.configure(with: fetcher.lastUpdate) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuTableViewCell cell.configure(with: weekMenu[indexPath.row - 1]) return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell cell.configure(with: error) return cell } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.row == 0 { return false } if self.weekMenu[indexPath.row - 1].isClosedMenu { return false } return true } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if weekMenu.isEmpty || indexPath.row == 0 { return nil } let menu = self.weekMenu[indexPath.row - 1] let calendarAction = addToCalendarRowAction(for: menu) if let allergensRowAction = allergensInfoRowAction(for: menu) { return [calendarAction, allergensRowAction] } else { return [calendarAction] } } // MARK: - UIScrollViewDelegate // Avoids "last update" row scrolling down to first dish row override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if lastUpdateRowIsVisible { self.tableView.scrollToRow(at: IndexPath(row: 1, section: 0), at: .top, animated: true) } } } // MARK: Helpers private extension MenuTableViewController { func addToCalendarRowAction(for menu: DayMenu) -> UITableViewRowAction { let rowAction = UITableViewRowAction(style: .normal, title: NSLocalizedString("Add to\nCalendar"), handler: { action, indexPath in switch EventManager.authorizationStatus { case .authorized: self.presentEventEditViewController(for: menu) case .denied: self.presentAlertController(title: NSLocalizedString("Access Denied"), message: NSLocalizedString("Please go to the app's settings and allow us to access your calendars."), showsGoToSettings: true) case .notDetermined: self.requestEventAccessPermission(for: menu) case .restricted: self.presentAlertController(title: NSLocalizedString("Access Restricted"), message: NSLocalizedString("Access to calendars is restricted, possibly due to parental controls being in place."), showsGoToSettings: false) } }) rowAction.backgroundColor = .customAlternateRedColor return rowAction } func allergensInfoRowAction(for menu: DayMenu) -> UITableViewRowAction? { if let _ = menu.allergens { // TODO: Implement return nil } else { return nil } } func presentEventEditViewController(for menu: DayMenu) { let eventVC = EKEventEditViewController() let eventStore = EKEventStore() eventVC.eventStore = eventStore eventVC.editViewDelegate = self eventVC.event = EventManager.createEvent(in: eventStore, for: menu) self.present(eventVC, animated: true, completion: nil) } func presentAlertController(title: String, message: String, showsGoToSettings: Bool) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel"), style: .cancel, handler: { action in self.dismiss(animated: true, completion: nil) self.tableView.isEditing = false }) alertController.addAction(cancelAction) if showsGoToSettings { let settingsAction = UIAlertAction(title: NSLocalizedString("Go to Settings"), style: .default, handler: { action in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) }) alertController.addAction(settingsAction) alertController.preferredAction = settingsAction } self.present(alertController, animated: true, completion: nil) } func requestEventAccessPermission(for menu: DayMenu) { EventManager.requestAccessPermission { granted in mainQueue { if granted { self.presentEventEditViewController(for: menu) } else { self.tableView.isEditing = false } } } } var lastUpdateRowIsVisible: Bool { let offset = navigationController!.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height return weekMenu.isEmpty == false && tableView.contentOffset.y < lastUpdateRowHeight - offset } /// Updates the table view's separators left inset according to the given size. func updateSeparatorsInset(for size: CGSize) { tableView.separatorInset.left = size.width * 0.2 - 60 } } // MARK: - EKEventEditViewDelegate extension MenuTableViewController: EKEventEditViewDelegate { func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { if let event = controller.event, action == .saved { EventManager.saveDefaultInfo(from: event) } dismiss(animated: true, completion: nil) self.tableView.isEditing = false } }
e7b8758d1c0579d55b4dc3602093f06e
37.289552
246
0.613783
false
false
false
false
shnhrrsn/SHNUrlRouter
refs/heads/master
Tests/UrlRouterTests.swift
mit
2
// // UrlRouterTests.swift // SHNUrlRouter // // Copyright (c) 2015-2018 Shaun Harrison // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import SHNUrlRouter class UrlRouterTests: XCTestCase { func testReadMeExample() { var router = UrlRouter() var selectedIndex = -1 var id = -1 var section: String? router.add("id", pattern: "[0-9]+") router.add("section", pattern: "profile|activity") router.register("feed") { (parameters) in selectedIndex = 0 } router.register("user/{id}/{section?}") { (parameters) in guard let stringId = parameters["id"], let intId = Int(stringId) else { return } selectedIndex = 1 id = intId section = parameters["section"] ?? "default" } XCTAssertTrue(router.dispatch(for: "http://example.com/feed")) XCTAssertEqual(selectedIndex, 0) XCTAssertFalse(router.dispatch(for: "http://example.com/user")) XCTAssertTrue(router.dispatch(for: "http://example.com/user/5")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "default") XCTAssertTrue(router.dispatch(for: "http://example.com/user/5/profile")) XCTAssertEqual(id, 5) XCTAssertEqual(section, "profile") } func testBasicDispatchingOfRoutes() { var router = UrlRouter() var dispatched = false router.register("foo/bar") { _ in dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/bar")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithParameter() { var router = UrlRouter() var dispatched = false router.register("foo/{bar}") { parameters in XCTAssertEqual(parameters["bar"], "swift") dispatched = true } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertTrue(dispatched) } func testBasicDispatchingOfRoutesWithOptionalParameter() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{bar}/{baz?}") { parameters in dispatched = "\(parameters["bar"] ?? "").\(parameters["baz"] ?? "1")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/4")) XCTAssertEqual(dispatched, "swift.4") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift")) XCTAssertEqual(dispatched, "swift.1") } func testBasicDispatchingOfRoutesWithOptionalParameters() { var router = UrlRouter() var dispatched: String? = nil router.register("foo/{name}/boom/{age?}/{location?}") { parameters in dispatched = "\(parameters["name"] ?? "").\(parameters["age"] ?? "56").\(parameters["location"] ?? "ca")" } XCTAssertTrue(router.dispatch(for: "http://example.com/foo/steve/boom")) XCTAssertEqual(dispatched, "steve.56.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4")) XCTAssertEqual(dispatched, "swift.4.ca") XCTAssertTrue(router.dispatch(for: "http://example.com/foo/swift/boom/4/org")) XCTAssertEqual(dispatched, "swift.4.org") } }
10485942348e81ce7093c2bd9f68f924
30.309524
108
0.713815
false
true
false
false
justaninja/clients_list
refs/heads/master
ClientsList/ClientsList/Location.swift
mit
1
// // Location.swift // ClientsList // // Created by Konstantin Khokhlov on 29.06.17. // Copyright © 2017 Konstantin Khokhlov. All rights reserved. // import Foundation import CoreLocation /// A location model struct. struct Location: Equatable { // MARK: - Keys private let nameKey = "name" private let latitudeKey = "latitudeKey" private let longitudeKey = "longitudeKey" // MARK: - Properties let name: String let coordinate: CLLocationCoordinate2D? var plistDictionary: [String: Any] { var dict = [String: Any]() dict[nameKey] = name if let coordinate = coordinate { dict[latitudeKey] = coordinate.latitude dict[longitudeKey] = coordinate.longitude } return dict } // MARK: - Inits init(name: String, coordinate: CLLocationCoordinate2D? = nil) { self.name = name self.coordinate = coordinate } init?(dictionary: [String: Any]) { guard let name = dictionary[nameKey] as? String else { return nil } let coordinate: CLLocationCoordinate2D? if let latitude = dictionary[latitudeKey] as? Double, let longitude = dictionary[longitudeKey] as? Double { coordinate = CLLocationCoordinate2DMake(latitude, longitude) } else { coordinate = nil } self.name = name self.coordinate = coordinate } } func == (lhs: Location, rhs: Location) -> Bool { if lhs.coordinate?.latitude != rhs.coordinate?.latitude { return false } if lhs.coordinate?.longitude != rhs.coordinate?.longitude { return false } if lhs.name != rhs.name { return false } return true }
39b0e18245a5565f884cd237c49bc3a1
23.671429
115
0.621309
false
false
false
false
skyline75489/Honeymoon
refs/heads/master
Honeymoon/Server.swift
mit
1
// // Server.swift // Honeymoon // // Created by skyline on 15/9/29. // Copyright © 2015年 skyline. All rights reserved. // import Foundation import GCDWebServer public class Server { let webServer = GCDWebServer() var handlerMap = [Rule:Handler]() var url:String { get { return self.webServer.serverURL.absoluteString } } init() { webServer.addDefaultHandlerForMethod("GET", requestClass: GCDWebServerRequest.self, processBlock: {request in let errorResp = GCDWebServerDataResponse(HTML: "<html><body><h3>Not Found</h3></body></html>") errorResp.statusCode = 404 return errorResp }) webServer.addDefaultHandlerForMethod("POST", requestClass: GCDWebServerRequest.self, processBlock: {request in let errorResp = GCDWebServerDataResponse(HTML: "<html><body><h3>Not Found</h3></body></html>") errorResp.statusCode = 404 return errorResp }) } public func addRoute(route:String, method: String, requestClass: AnyClass=GCDWebServerRequest.self, handlerClosure: HandlerClosure) { let r = Rule(rule: route, method: method) if r.variables.count > 0 { let h = Handler(path: route, method: method, handlerClosure: handlerClosure, pathRegex: r._regex?.pattern, parameters: r.variables) self.addHandlerWithParameter(h, requestClass: requestClass) } else { let h = Handler(path: route, method: method, handlerClosure: handlerClosure) self.addHandler(h, requestClass: requestClass) } } public func addStaticHandler(basePath:String, dir:String) { self.webServer.addGETHandlerForBasePath(basePath, directoryPath: dir, indexFilename: nil, cacheAge: 3600, allowRangeRequests: false) } private func addHandler(handler:Handler, requestClass:AnyClass=GCDWebServerRequest.self) { webServer.addHandlerForMethod(handler.method, path: handler.path, requestClass: requestClass, processBlock: { request in let req = self.prepareRequest(request) let resp = handler.handlerClosure!(req) var returnResp = Response(body: "") if let resp = resp as? Response { returnResp = resp } if let resp = resp as? String { returnResp = Response(body: resp) } return self.prepareResponse(returnResp) }) } private func addHandlerWithParameter(handler: Handler, requestClass:AnyClass=GCDWebServerRequest.self) { webServer.addHandlerForMethod(handler.method, pathRegex: handler.pathRegex, requestClass: requestClass, processBlock: { request in let r = Regex(pattern: handler.pathRegex!) var params = [String:String]() if let m = r.match(request.path) { for var i = 0 ; i < handler.routeParameters?.count; i++ { let key = handler.routeParameters?[i] params[key!] = m.group(i+1) } } let req = self.prepareRequest(request, routeParams:params) let resp = handler.handlerClosure!(req) var returnResp = Response(body: "") if let resp = resp as? Response { returnResp = resp } if let resp = resp as? String { returnResp = Response(body: resp) } return self.prepareResponse(returnResp) }) } private func prepareRequest(request:GCDWebServerRequest, routeParams:[String:String]?=nil) -> Request { let req = Request() req.method = request.method req.path = request.path req.params = routeParams if let r = request as? GCDWebServerURLEncodedFormRequest { req.form = [String:String]() for (k, v) in r.arguments { let newKey = String(k) let newValue = v as! String req.form?[newKey] = newValue } } return req } private func prepareResponse(response: Response) -> GCDWebServerResponse { if let redirect = response.redirect { return GCDWebServerResponse(redirect: NSURL(string: redirect), permanent: false) } let resp = GCDWebServerDataResponse.init(HTML: response.body) resp.statusCode = response.statusCode! resp.contentType = response.contentType resp.contentLength = response.contentLength! return resp } public func start(port:UInt?=nil) { if let port = port { webServer.runWithPort(port, bonjourName: "GCD Web Server") } else { webServer.runWithPort(8000, bonjourName: "GCD Web Server") } } }
d08a2905cb9715de9c568c45f2900e8a
37.186047
143
0.599594
false
false
false
false
tiehuaz/iOS-Application-for-AURIN
refs/heads/master
AurinProject/SidebarMenu/MapViewController.swift
apache-2.0
1
// // MapViewController.swift // AurinProject // // Created by tiehuaz on 8/29/15. // Copyright (c) 2015 AppCoda. All rights reserved. // import UIKit import MapKit /* Second Visualizaiton interface based on retured data, drawing polygon for each data based on geospatial information * also put red pin in each polygon to show details for this polygon. */ class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var menuButton:UIBarButtonItem! @IBOutlet weak var mapView: MKMapView! let user = Singleton.sharedInstance var measureNum :CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } print(user.mapData.count) } override func viewWillAppear(animated: Bool) { addPolygonToMap() openMapForPlace() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if (overlay is MKPolygon) { var overlayPathView = MKPolygonRenderer(overlay: overlay) overlayPathView.fillColor = UIColor.redColor().colorWithAlphaComponent(measureNum) overlayPathView.strokeColor = UIColor.blackColor().colorWithAlphaComponent(0.7) overlayPathView.lineWidth = 5 return overlayPathView } else if (overlay is MKPolyline) { var overlayPathView = MKPolylineRenderer(overlay: overlay) overlayPathView.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) overlayPathView.lineWidth = 1 return overlayPathView } return nil } func addPolygonToMap() { for (suburbName,polygon) in user.mapData{ var stringArr = suburbName.componentsSeparatedByString(":") var points = polygon var range = Double(stringArr[3])! if user.flag == 0{ if range<10{ measureNum = 0.2 }else if(range>=10&&range<15){ measureNum = 0.4 }else if(range>=15&&range<20){ measureNum = 0.6 }else{ measureNum = 0.8 } }else if user.flag == 1{ if range<80000{ measureNum = 0.2 }else if(range>=80000&&range<120000){ measureNum = 0.4 }else if(range>=120000&&range<160000){ measureNum = 0.6 }else{ measureNum = 0.8 } }else if user.flag == 2{ if range<30{ measureNum = 0.2 }else if(range>=30&&range<35){ measureNum = 0.4 }else if(range>=35&&range<40){ measureNum = 0.6 }else{ measureNum = 0.8 } } var polygon = MKPolygon(coordinates: &points, count: points.count) self.mapView.addOverlay(polygon) var lati : Double = Double(stringArr[1])! var lonti : Double = Double(stringArr[2])! var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(lati,lonti) var objectAnnotation = MKPointAnnotation() objectAnnotation.coordinate = pinLocation objectAnnotation.title = stringArr[0] as! String if user.flag == 0{ objectAnnotation.subtitle = "housing stress: \(range)" }else if user.flag == 1{ objectAnnotation.subtitle = "population: \(range)" }else if user.flag == 2{ objectAnnotation.subtitle = "numeric: \(range), Severity: \(stringArr[4])" } self.mapView.addAnnotation(objectAnnotation) } } func openMapForPlace() { let span = MKCoordinateSpanMake(1, 1) let location = CLLocationCoordinate2D( latitude: (-37.796286-37.804424-37.852993)/3, longitude: (144.927181+145.027181+144.927181)/3 ) let region = MKCoordinateRegion(center: location, span: span) // let regionDistance: CLLocationDistance = 1000000 mapView.setRegion(region, animated: true) } @IBAction func returnButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } }
538032ef2716cd10ff420d0d61bb9a03
33.123288
118
0.557607
false
false
false
false
iOSDevLog/ijkplayer
refs/heads/master
ijkplayer-Swift/ijkplayer-Swift/Demo/IJKDemoInputURLViewController.swift
lgpl-2.1
1
// // IJKDemoInputURLViewController.swift // ijkplayer-Swift // // Created by iOS Dev Log on 2017/8/24. // Copyright © 2017年 iOSDevLog. All rights reserved. // import UIKit class IJKDemoInputURLViewController: UIViewController, UITextViewDelegate { let rtmp = "rtmp://live.hkstv.hk.lxdns.com/live/hks" let m3u8 = "https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8" let rtsp = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov" @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() title = "Input URL" textView.delegate = self navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Play", style: .done, target: self, action: #selector(self.onClickPlayButton)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textView.text = rtsp } @objc func onClickPlayButton() { let url = URL(string: textView.text) let scheme: String? = url?.scheme?.lowercased() if (scheme == "http") || (scheme == "https") || (scheme == "rtmp") || (scheme == "rtsp") { IJKPlayerViewController.present(from: self, withTitle: "URL: \(String(describing: url))", url: url!, completion: {() -> Void in self.navigationController?.popViewController(animated: false) }) } } func textViewDidEndEditing(_ textView: UITextView) { onClickPlayButton() } }
40a15dd7048e25a1731c839c4eb4459a
33.477273
145
0.632169
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSPopUpButtonSpec.swift
gpl-3.0
5
import Quick import Nimble import ReactiveCocoa import ReactiveSwift import Result import AppKit final class NSPopUpButtonSpec: QuickSpec { override func spec() { describe("NSPopUpButton") { var button: NSPopUpButton! var window: NSWindow! weak var _button: NSButton? let testTitles = (0..<100).map { $0.description } beforeEach { window = NSWindow() button = NSPopUpButton(frame: .zero) _button = button for (i, title) in testTitles.enumerated() { let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") item.tag = 1000 + i button.menu?.addItem(item) } window.contentView?.addSubview(button) } afterEach { autoreleasepool { button.removeFromSuperview() button = nil } expect(_button).to(beNil()) } it("should emit selected index changes") { var values = [Int]() button.reactive.selectedIndexes.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1, 99] } it("should emit selected title changes") { var values = [String]() button.reactive.selectedTitles.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == ["1", "99"] } it("should accept changes from its bindings to its index values") { let (signal, observer) = Signal<Int?, NoError>.pipe() button.reactive.selectedIndex <~ SignalProducer(signal) observer.send(value: 1) expect(button.indexOfSelectedItem) == 1 observer.send(value: 99) expect(button.indexOfSelectedItem) == 99 observer.send(value: nil) expect(button.indexOfSelectedItem) == -1 expect(button.selectedItem?.title).to(beNil()) } it("should accept changes from its bindings to its title values") { let (signal, observer) = Signal<String?, NoError>.pipe() button.reactive.selectedTitle <~ SignalProducer(signal) observer.send(value: "1") expect(button.selectedItem?.title) == "1" observer.send(value: "99") expect(button.selectedItem?.title) == "99" observer.send(value: nil) expect(button.selectedItem?.title).to(beNil()) expect(button.indexOfSelectedItem) == -1 } it("should emit selected item changes") { var values = [NSMenuItem]() button.reactive.selectedItems.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) let titles = values.map { $0.title } expect(titles) == ["1", "99"] } it("should emit selected tag changes") { var values = [Int]() button.reactive.selectedTags.observeValues { values.append($0) } button.menu?.performActionForItem(at: 1) button.menu?.performActionForItem(at: 99) expect(values) == [1001, 1099] } it("should accept changes from its bindings to its tag values") { let (signal, observer) = Signal<Int, NoError>.pipe() button.reactive.selectedTag <~ SignalProducer(signal) observer.send(value: 1001) expect(button.selectedItem?.tag) == 1001 expect(button.indexOfSelectedItem) == 1 observer.send(value: 1099) expect(button.selectedItem?.tag) == 1099 expect(button.indexOfSelectedItem) == 99 observer.send(value: 1042) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 // Sending an invalid tag number doesn't change the selection observer.send(value: testTitles.count + 1) expect(button.selectedItem?.tag) == 1042 expect(button.indexOfSelectedItem) == 42 } } } }
e752d1ea6631925664228c4b309cb112
27.181818
72
0.665054
false
false
false
false
migchaves/EGTracker
refs/heads/master
Pod/Classes/TrackerDataBase/EGTrackerDBManager.swift
mit
1
// // EGTrackerDBManager.swift // TinyGoi // // Created by Miguel Chaves on 26/02/16. // Copyright © 2016 E-Goi. All rights reserved. // import UIKit import CoreData class EGTrackerDBManager: NSObject { // MARK: - Class Properties var managedObjectContext: NSManagedObjectContext var managedObjectModel: NSManagedObjectModel var persistentStoreCoordinator: NSPersistentStoreCoordinator // MARK: - Init class override init() { self.managedObjectModel = NSManagedObjectModel.init(contentsOfURL: EGTrackerDBManager.getModelUrl())! self.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: self.managedObjectModel) do { try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: EGTrackerDBManager.storeURL(), options: nil) } catch let error as NSError { print(error) abort() } self.managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType) self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator self.managedObjectContext.mergePolicy = NSOverwriteMergePolicy } // MARK: - Shared Instance class var sharedInstance: EGTrackerDBManager { struct Singleton { static let instance = EGTrackerDBManager() } return Singleton.instance } // MARK: - Create and Save objects func managedObjectOfType(objectType: String) -> NSManagedObject { let newObject = NSEntityDescription.insertNewObjectForEntityForName(objectType, inManagedObjectContext: self.managedObjectContext) return newObject } func saveContext() { if (!self.managedObjectContext.hasChanges) { return } else { do { try self.managedObjectContext.save() } catch let exception as NSException { print("Error while saving \(exception.userInfo) : \(exception.reason)") } catch { print("Error while saving data!") } } } // MARK: - Retrieve data func allEntriesOfType(objectType: String) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true do { let result = try self.managedObjectContext.executeFetchRequest(request) return result } catch { print("Error executing request in the Data Base") } return [] } func getEntryOfType(objectType: String, propertyName: String, propertyValue: AnyObject) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true let predicate = NSPredicate(format: "\(propertyName) == \(propertyValue)") request.predicate = predicate do { let result = try self.managedObjectContext.executeFetchRequest(request) var returnArray: [AnyObject] = [AnyObject]() for element in result { returnArray.append(element) } return returnArray } catch { print("Error executing request in the Data Base") } return [] } func deleteAllEntriesOfType(objectType: String) { let elements = allEntriesOfType(objectType) if (elements.count > 0) { for element in elements { self.managedObjectContext.deleteObject(element as! NSManagedObject) } saveContext() } } func deleteObject(object: NSManagedObject) { self.managedObjectContext.deleteObject(object) saveContext() } // MARK: - Private functions static private func getModelUrl() -> NSURL { return NSBundle.mainBundle().URLForResource("TrackerDataBase", withExtension: "momd")! } static private func storeURL () -> NSURL? { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last let storeUrl = applicationDocumentsDirectory?.URLByAppendingPathComponent("TrackerDataBase.sqlite") return storeUrl } }
a7cd776a51c14bbf1bfb5f7b6fe107e0
31.433333
144
0.622738
false
false
false
false
daher-alfawares/iBeacon
refs/heads/master
Beacon/Beacon/ViewController.swift
apache-2.0
1
// // ViewController.swift // Beacon // // Created by Daher Alfawares on 1/19/15. // Copyright (c) 2015 Daher Alfawares. All rights reserved. // import UIKit class ViewController: UITableViewController { let beacons = BeaconDataSource() override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self; self.tableView.dataSource = self; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.beacons.count() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // View let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell // Model let beaconInfo = self.beacons.beaconInfoAtIndex(indexPath.row) // Control cell.textLabel?.text = beaconInfo.name cell.detailTextLabel?.text = beaconInfo.uuid return cell; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // View let beaconViewController = segue.destinationViewController as BeaconViewController // Model let tableView = self.tableView; let index = tableView.indexPathForCell(sender as UITableViewCell) let row = index?.row let beacon = self.beacons.beaconInfoAtIndex (row!) as BeaconInfo beaconViewController.beaconName = beacon.name beaconViewController.beaconUUID = beacon.uuid beaconViewController.beaconImageName = beacon.image beaconViewController.beaconMajor = beacon.major beaconViewController.beaconMinor = beacon.minor } }
faadb1b1d0cb47914902c7e294e5729d
29.783333
118
0.64104
false
false
false
false
Binglin/MappingAce
refs/heads/master
Mapping/ViewController.swift
mit
2
// // ViewController.swift // Mapping // // Created by 郑林琴 on 16/10/10. // Copyright © 2016年 Ice Butterfly. All rights reserved. // import UIKit import MappingAce class ViewController: UIViewController { struct PhoneNumber: Mapping { var tel: String var type: String } override func viewDidLoad() { super.viewDidLoad() self.testStructMapping() self.testStructMappingWithDefaultValue() } func testStructMapping(){ struct UserArrayPhoneEntity: Mapping{ var age: Int? var name: String? var phone: PhoneNumber var phones: [PhoneNumber] } let phone: [String : Any] = [ "tel": "186xxxxxxxx", "type": "work" ] let phones = Array(repeating: phone, count: 10) let dic: [String : Any] = [ "age" : 14.0, "name": "Binglin", "phone": phone, "phones": phones ] let user = UserArrayPhoneEntity(fromDic: dic) let serialized = user.toDictionary() print(serialized) } func testStructMappingWithDefaultValue(){ struct UserArrayPhoneEntity: InitMapping{ var age: Int? var name: String = "default" var phone: PhoneNumber? var phones: [PhoneNumber] = [] } struct PhoneNumber: Mapping { var tel: String var type: String } let phone: [String : Any] = [ "tel": "186xxxxxxxx", "type": "work" ] let phones = Array(repeating: phone, count: 10) let dic: [String : Any] = [ "age" : 14.0, "phone": phone, "phones": phones ] let user = UserArrayPhoneEntity(fromDic: dic) let serialized = user.toDictionary() print(serialized) } }
ac420361c3f254786e07bc8f036a99af
20.572917
57
0.487687
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Processor/HTMLProcessor.swift
gpl-2.0
2
import Foundation /// Struct to represent a HTML element /// public struct HTMLElement { public enum TagType { case selfClosing case closed case single } public let tag: String public let attributes: [ShortcodeAttribute] public let type: TagType public let content: String? } /// A class that processes a string and replace the designated shortcode for the replacement provided strings /// open class HTMLProcessor: Processor { /// Whenever an HTML is found by the processor, this closure will be executed so that elements can be customized. /// public typealias Replacer = (HTMLElement) -> String? // MARK: - Basic Info let element: String // MARK: - Regex private enum CaptureGroups: Int { case all = 0 case name case arguments case selfClosingElement case content case closingTag static let allValues: [CaptureGroups] = [.all, .name, .arguments, .selfClosingElement, .content, .closingTag] } /// Regular expression to detect attributes /// Capture groups: /// /// 1. The element name /// 2. The element argument list /// 3. The self closing `/` /// 4. The content of a element when it wraps some content. /// 5. The closing tag. /// private lazy var htmlRegexProcessor: RegexProcessor = { [unowned self] in let pattern = "\\<(\(element))(?![\\w-])([^\\>\\/]*(?:\\/(?!\\>)[^\\>\\/]*)*?)(?:(\\/)\\>|\\>(?:([^\\<]*(?:\\<(?!\\/\\1\\>)[^\\<]*)*)(\\<\\/\\1\\>))?)" let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) return RegexProcessor(regex: regex) { (match: NSTextCheckingResult, text: String) -> String? in return self.process(match: match, text: text) } }() // MARK: - Parsing & processing properties private let attributesParser = ShortcodeAttributeParser() private let replacer: Replacer // MARK: - Initializers public init(for element: String, replacer: @escaping Replacer) { self.element = element self.replacer = replacer } // MARK: - Processing public func process(_ text: String) -> String { return htmlRegexProcessor.process(text) } } // MARK: - Regex Match Processing Logic private extension HTMLProcessor { /// Processes an HTML Element regex match. /// func process(match: NSTextCheckingResult, text: String) -> String? { guard match.numberOfRanges == CaptureGroups.allValues.count else { return nil } let attributes = self.attributes(from: match, in: text) let elementType = self.elementType(from: match, in: text) let content: String? = match.captureGroup(in: CaptureGroups.content.rawValue, text: text) let htmlElement = HTMLElement(tag: element, attributes: attributes, type: elementType, content: content) return replacer(htmlElement) } // MARK: - Regex Match Processing Logic /// Obtains the attributes from an HTML element match. /// private func attributes(from match: NSTextCheckingResult, in text: String) -> [ShortcodeAttribute] { guard let attributesText = match.captureGroup(in: CaptureGroups.arguments.rawValue, text: text) else { return [] } return attributesParser.parse(attributesText) } /// Obtains the element type for an HTML element match. /// private func elementType(from match: NSTextCheckingResult, in text: String) -> HTMLElement.TagType { if match.captureGroup(in: CaptureGroups.selfClosingElement.rawValue, text: text) != nil { return .selfClosing } else if match.captureGroup(in: CaptureGroups.closingTag.rawValue, text: text) != nil { return .closed } return .single } }
2be83d46dc0db518328f8018115a8afd
31.08871
159
0.615481
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/Seismography/Demangler.swift
mit
1
/// Demangler.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation private let MAXIMUM_SUBST_REPEAT_COUNT = 2048 public final class Demangler { public final class Node { public enum Kind: Hashable { case global case identifier(String) case module(String) case data case function case tuple case emptyTuple case firstElementMarker case tupleElement case type case bottomType case typeType case functionType case argumentTuple case substitutedType } let kind: Kind var children: [Node] = [] public init(_ kind: Kind) { self.kind = kind } func addChild(_ node: Node) { self.children.append(node) } func reverseChildren() { self.children.reverse() } fileprivate func contains(_ kind: Kind) -> Bool { guard self.kind != kind else { return true } return self.children.contains { $0.contains(kind) } } public func print(to stream: TextOutputStream) { return Printer(root: self, stream: stream).printRoot() } final class Printer { let root: Node var stream: TextOutputStream init(root: Node, stream: TextOutputStream) { self.root = root self.stream = stream } } } private let buffer: Data private var position = 0 private var nodeStack = [Node]() private var substitutions = [Node]() private var substitutionBuffer = [String]() private var nextWordIdx = 0 public init(_ text: Data) { self.substitutionBuffer = [String](repeating: "", count: MAXIMUM_WORDS_CAPACITY) self.nodeStack.reserveCapacity(16) self.substitutions.reserveCapacity(16) self.buffer = text } public static func demangleSymbol(_ mangledName: String) -> Node? { let dem = Demangler(mangledName.data(using: .utf8)!) let prefixLength = dem.getManglingPrefixLength(mangledName) guard prefixLength > 0 else { return nil } dem.position += prefixLength if !dem.demangleTopLevel() { return nil } let topLevel = dem.createNode(.global) for nd in dem.nodeStack { switch nd.kind { case .type: topLevel.addChild(nd.children.first!) default: topLevel.addChild(nd) } } guard !topLevel.children.isEmpty else { return nil } return topLevel } } // MARK: Core Demangling Routines fileprivate extension Demangler { func demangleTopLevel() -> Bool { while self.position < self.buffer.count { guard let node = self.demangleEntity() else { return false } pushNode(node) } return true } func demangleEntity() -> Node? { switch nextChar() { case ManglingScalars.UPPERCASE_A: return self.demangleSubstitutions() case ManglingScalars.UPPERCASE_B: return createNode(.type, [createNode(.bottomType)]) case ManglingScalars.UPPERCASE_D: return self.demangleDataType() case ManglingScalars.UPPERCASE_F: return self.demangleFunction() case ManglingScalars.LOWERCASE_F: return self.demangleFunctionType() case ManglingScalars.UPPERCASE_G: return self.demangleBoundGenericType() case ManglingScalars.UPPERCASE_T: return self.createNode(.type, [createNode(.typeType)]) case ManglingScalars.LOWERCASE_T: return self.popTuple() case ManglingScalars.LOWERCASE_Y: return self.createNode(.emptyTuple) case ManglingScalars.UNDERSCORE: return self.createNode(.firstElementMarker) default: pushBack() return demangleIdentifier() } } func demangleNumber() -> Int? { guard peekChar().isDigit else { return nil } var number = 0 while true { let c = peekChar() guard c.isDigit else { return number } let newNum = (10 * number) + Int(c - ManglingScalars.ZERO) if newNum < number { return nil } number = newNum nextChar() } } func demangleIdentifier() -> Node? { var hasWordSubsts = false var isPunycoded = false let c = peekChar() guard c.isDigit else { return nil } if c == ManglingScalars.ZERO { nextChar() if peekChar() == ManglingScalars.ZERO { nextChar() isPunycoded = true } else { hasWordSubsts = true } } var result = "" repeat { while hasWordSubsts && peekChar().isLetter { let c = nextChar() let proposedIdx: Int if c.isLowerLetter { proposedIdx = Int(c - ManglingScalars.LOWERCASE_A) } else { assert(c.isUpperLetter) proposedIdx = Int(c - ManglingScalars.UPPERCASE_A) hasWordSubsts = false } guard proposedIdx < self.nextWordIdx else { return nil } assert(proposedIdx < MAXIMUM_WORDS_CAPACITY) let cachedWord = self.substitutionBuffer[Int(proposedIdx)] result.append(cachedWord) } if nextIf(ManglingScalars.ZERO) { break } guard let numChars = demangleNumber() else { return nil } if isPunycoded { nextIf(ManglingScalars.DOLLARSIGN) } guard self.position + numChars <= buffer.count else { return nil } let sliceData = buffer.subdata(in: position..<position + numChars) let slice = String(data: sliceData, encoding: .utf8)! guard !isPunycoded else { let punycoder = Punycode() guard let punyString = punycoder.decode(utf8String: slice.utf8) else { return nil } result.append(punyString) self.position += numChars continue } result.append(slice) var wordStartPos: Int? for idx in 0...sliceData.count { let c = idx < sliceData.count ? sliceData[idx] : 0 guard let startPos = wordStartPos else { if c.isStartOfWord { wordStartPos = idx } continue } if ManglingScalars.isEndOfWord(c, sliceData[idx - 1]) { if idx - startPos >= 2 && self.nextWordIdx < MAXIMUM_WORDS_CAPACITY { let wordData = sliceData.subdata(in: startPos..<idx) let wordString = String(data: wordData, encoding: .utf8)! self.substitutionBuffer[self.nextWordIdx] = wordString self.nextWordIdx += 1 } wordStartPos = nil } } self.position += numChars } while hasWordSubsts guard !result.isEmpty else { return nil } let identNode = createNode(.identifier(result)) addSubstitution(identNode) return identNode } } // MARK: Demangling Substitutions fileprivate extension Demangler { func demangleSubstitutions() -> Node? { var repeatCount = -1 while true { switch nextChar() { case 0: // End of text. return nil case let c where c.isLowerLetter: let lowerLetter = Int(c - ManglingScalars.LOWERCASE_A) guard let subst = pushSubstitutions(repeatCount, lowerLetter) else { return nil } pushNode(subst) repeatCount = -1 // Additional substitutions follow. continue case let c where c.isUpperLetter: let upperLetter = Int(c - ManglingScalars.UPPERCASE_A) // No more additional substitutions. return pushSubstitutions(repeatCount, upperLetter) case let c where c == ManglingScalars.DOLLARSIGN: // The previously demangled number is the large (> 26) index of a // substitution. let idx = repeatCount + 26 + 1 guard idx < self.substitutions.count else { return nil } return self.substitutions[idx] default: pushBack() // Not a letter? Then it's the repeat count (no underscore) // or a large substitution index (underscore). guard let nextRepeatCount = demangleNumber() else { return nil } repeatCount = nextRepeatCount } } } func pushSubstitutions(_ repeatCount: Int, _ idx: Int) -> Node? { guard idx < self.substitutions.count else { return nil } guard repeatCount <= MAXIMUM_SUBST_REPEAT_COUNT else { return nil } let substitutedNode = self.substitutions[idx] guard 0 < repeatCount else { return substitutedNode } for _ in 0..<repeatCount { pushNode(substitutedNode) } return substitutedNode } } // MARK: Demangling Declarations fileprivate extension Demangler { func popTuple() -> Node? { let root = createNode(.tuple) var firstElem = false repeat { firstElem = popNode(.firstElementMarker) != nil let tupleElmt = createNode(.tupleElement) guard let type = popNode(.type) else { return nil } tupleElmt.addChild(type) root.addChild(tupleElmt) } while (!firstElem) root.reverseChildren() return createNode(.type, [root]) } func popModule() -> Node? { if let ident = popNode(), case let .identifier(text) = ident.kind { return createNode(.module(text)) } return popNode({ $0.kind.isModule }) } func popContext() -> Node? { if let module = popModule() { return module } guard let type = popNode(.type) else { return popNode({ $0.kind.isContext }) } guard type.children.count == 1 else { return nil } guard let child = type.children.first else { return nil } guard child.kind.isContext else { return nil } return child } func demangleDataType() -> Node? { guard let name = popNode({ $0.kind.isIdentifier }) else { return nil } guard let context = popContext() else { return nil } let type = createNode(.type, [createNode(.data, [context, name])]) addSubstitution(type) return type } func demangleFunction() -> Node? { guard let type = popNode(.type) else { return nil } guard let fnType = type.children.first, fnType.kind == .functionType else { return nil } guard let name = popNode({ $0.kind.isIdentifier }) else { return nil } guard let context = popContext() else { return nil } return createNode(.function, [context, name, type]) } func demangleFunctionType() -> Node? { let funcType = createNode(.functionType) if let params = demangleFunctionPart(.argumentTuple) { funcType.addChild(params) } guard let returnType = popNode(.type) else { return nil } funcType.addChild(returnType) return createNode(.type, [funcType]) } func demangleFunctionPart(_ kind: Node.Kind) -> Node? { let type: Node if popNode(.emptyTuple) != nil { type = createNode(.type, [createNode(.tuple)]) } else { type = popNode(.type)! } return createNode(kind, [type]) } func demangleBoundGenericType() -> Node? { guard let nominal = popNode(.type)?.children[0] else { return nil } var typeList = [Node]() if popNode(.emptyTuple) == nil { let type = popNode(.type)! if type.children[0].kind == .tuple { typeList.append(contentsOf: type.children[0].children) } else { typeList.append(type.children[0]) } } let args = createNode(.argumentTuple, typeList) switch nominal.kind { case .data: let boundNode = createNode(.substitutedType, [nominal, args]) let nty = createNode(.type, [boundNode]) self.addSubstitution(nty) return nty default: fatalError() } } } // MARK: Parsing fileprivate extension Demangler { func peekChar() -> UInt8 { guard self.position < self.buffer.count else { return 0 } return self.buffer[position] } @discardableResult func nextChar() -> UInt8 { guard self.position < self.buffer.count else { return 0 } defer { self.position += 1 } return buffer[position] } @discardableResult func nextIf(_ c: UInt8) -> Bool { guard peekChar() == c else { return false } self.position += 1 return true } func pushBack() { assert(position > 0) position -= 1 } func consumeAll() -> String { let str = buffer.dropFirst(position) self.position = buffer.count return String(bytes: str, encoding: .utf8)! } } // MARK: Manipulating The Node Stack fileprivate extension Demangler { func createNode(_ k: Node.Kind, _ children: [Node] = []) -> Node { let node = Node(k) for child in children { node.addChild(child) } return node } func pushNode(_ Nd: Node) { nodeStack.append(Nd) } func popNode() -> Node? { return self.nodeStack.popLast() } func popNode(_ kind: Node.Kind) -> Node? { guard let lastNode = nodeStack.last else { return nil } guard lastNode.kind == kind else { return nil } return popNode() } func popNode(_ pred: (Node) -> Bool) -> Node? { guard let lastNode = nodeStack.last else { return nil } guard pred(lastNode) else { return nil } return popNode() } private func addSubstitution(_ Nd: Node) { self.substitutions.append(Nd) } private func getManglingPrefixLength(_ mangledName: String) -> Int { guard !mangledName.isEmpty else { return 0 } guard mangledName.starts(with: MANGLING_PREFIX) else { return 0 } return MANGLING_PREFIX.count } } // MARK: Demangler Node Attributes fileprivate extension Demangler.Node.Kind { var isContext: Bool { switch self { case .data: return true case .function: return true case .module(_): return true case .substitutedType: return true case .global: return false case .identifier(_): return false case .tuple: return false case .emptyTuple: return false case .firstElementMarker: return false case .tupleElement: return false case .type: return false case .bottomType: return false case .typeType: return false case .functionType: return false case .argumentTuple: return false } } var isModule: Bool { switch self { case .module(_): return true default: return false } } var isIdentifier: Bool { switch self { case .identifier(_): return true default: return false } } } // MARK: Printing extension Demangler.Node.Printer { func printRoot() { print(self.root) } func print(_ node: Demangler.Node) { switch node.kind { case .global: printChildren(node.children) case let .identifier(str): self.stream.write(str) case let .module(str): self.stream.write(str) case .data: let ctx = node.children[0] let name = node.children[1] print(ctx) self.stream.write(".") print(name) case .function: let ctx = node.children[0] let name = node.children[1] let type = node.children[2] print(ctx) self.stream.write(".") print(name) print(type.children[0]) case .argumentTuple: print(node.children[0]) case .type: print(node.children[0]) case .bottomType: self.stream.write("_") case .functionType: let params = node.children[0] let retTy = node.children[1] self.stream.write("(") print(params) if !params.children.isEmpty { self.stream.write(", ") } self.stream.write("(") print(retTy) self.stream.write(") -> _") self.stream.write(")") case .tuple: printChildren(node.children, separator: ", ") case .tupleElement: let type = node.children[0] print(type) case .emptyTuple: self.stream.write("()") default: fatalError("\(node.kind)") } } func printChildren(_ children: [Demangler.Node], separator: String = "") { guard let last = children.last else { return } for child in children.dropLast() { print(child) stream.write(separator) } print(last) } }
8d555a9b8d1eb630428c9ae5ce3f58ae
22.252125
79
0.605933
false
false
false
false
algolia/algoliasearch-client-swift
refs/heads/master
Sources/AlgoliaSearchClient/Client/Search/SearchClient+Wait.swift
mit
1
// // SearchClient+Wait.swift // // // Created by Vladislav Fitc on 22/01/2021. // import Foundation public extension Client { // MARK: - Task status /** Check the current TaskStatus of a given Task. - parameter taskID: of the indexing [Task]. - parameter requestOptions: Configure request locally with [RequestOptions] */ @discardableResult func taskStatus(for taskID: AppTaskID, requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<TaskInfo>) -> Operation & TransportTask { let command = Command.Advanced.AppTaskStatus(taskID: taskID, requestOptions: requestOptions) return execute(command, completion: completion) } /** Check the current TaskStatus of a given Task. - parameter taskID: of the indexing [Task]. - parameter requestOptions: Configure request locally with [RequestOptions] */ @discardableResult func taskStatus(for taskID: AppTaskID, requestOptions: RequestOptions? = nil) throws -> TaskInfo { let command = Command.Advanced.AppTaskStatus(taskID: taskID, requestOptions: requestOptions) return try execute(command) } // MARK: - Wait task /** Wait for a Task to complete before executing the next line of code, to synchronize index updates. All write operations in Algolia are asynchronous by design. It means that when you add or update an object to your index, our servers will reply to your request with a TaskID as soon as they understood the write operation. The actual insert and indexing will be done after replying to your code. You can wait for a task to complete by using the TaskID and this method. - parameter taskID: of the indexing task to wait for. - parameter requestOptions: Configure request locally with RequestOptions */ @discardableResult func waitTask(withID taskID: AppTaskID, timeout: TimeInterval? = nil, requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<TaskStatus>) -> Operation { let task = WaitTask(client: self, taskID: taskID, timeout: timeout, requestOptions: requestOptions, completion: completion) return launch(task) } /** Wait for a Task to complete before executing the next line of code, to synchronize index updates. All write operations in Algolia are asynchronous by design. It means that when you add or update an object to your index, our servers will reply to your request with a TaskID as soon as they understood the write operation. The actual insert and indexing will be done after replying to your code. You can wait for a task to complete by using the TaskID and this method. - parameter taskID: of the indexing task to wait for. - parameter requestOptions: Configure request locally with RequestOptions */ @discardableResult func waitTask(withID taskID: AppTaskID, timeout: TimeInterval? = nil, requestOptions: RequestOptions? = nil) throws -> TaskStatus { let task = WaitTask(client: self, taskID: taskID, timeout: timeout, requestOptions: requestOptions, completion: { _ in }) return try launch(task) } }
a98a08dd40e0003c6ad499c79a2ad7e4
40.686047
116
0.640167
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Controllers/Settings/Passphrase/Views/PassphraseWordView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit import SweetUIKit class PassphraseWordView: UIControl { static let height: CGFloat = 35 private lazy var background: UIView = { let view = UIView(withAutoLayout: true) view.layer.cornerRadius = 4 view.clipsToBounds = true view.isUserInteractionEnabled = false view.addDashedBorder() return view }() private lazy var backgroundOverlay: UIView = { let view = UIView(withAutoLayout: true) view.backgroundColor = UIColor.black.withAlphaComponent(0.3) view.isUserInteractionEnabled = false view.layer.cornerRadius = 3 view.clipsToBounds = true view.alpha = 0 return view }() private lazy var wordLabel: UILabel = { let view = UILabel(withAutoLayout: true) view.font = Theme.preferredRegular() view.textColor = Theme.darkTextColor view.textAlignment = .center view.isUserInteractionEnabled = false view.adjustsFontForContentSizeCategory = true return view }() private lazy var feedbackGenerator: UIImpactFeedbackGenerator = { UIImpactFeedbackGenerator(style: .light) }() var word: Word? convenience init(with word: Word) { self.init(withAutoLayout: true) self.word = word wordLabel.text = word.text addSubview(background) background.addSubview(backgroundOverlay) addSubview(wordLabel) NSLayoutConstraint.activate([ self.background.topAnchor.constraint(equalTo: self.topAnchor), self.background.leftAnchor.constraint(equalTo: self.leftAnchor), self.background.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.background.rightAnchor.constraint(equalTo: self.rightAnchor), self.backgroundOverlay.topAnchor.constraint(equalTo: self.topAnchor, constant: 1), self.backgroundOverlay.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 1), self.backgroundOverlay.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -1), self.backgroundOverlay.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -1), self.wordLabel.topAnchor.constraint(equalTo: self.topAnchor), self.wordLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10), self.wordLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor), self.wordLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10), self.heightAnchor.constraint(equalToConstant: PassphraseWordView.height).priority(.defaultHigh) ]) setNeedsLayout() } override func layoutIfNeeded() { super.layoutIfNeeded() layoutBorder() } func layoutBorder() { for shape in shapeLayers { shape.bounds = bounds shape.position = CGPoint(x: bounds.width / 2, y: bounds.height / 2) shape.path = UIBezierPath(roundedRect: bounds, cornerRadius: 4).cgPath } } func setBorder(dashed: Bool) { for shape in shapeLayers { shape.lineDashPattern = dashed ? [5, 5] : nil } } var shapeLayers: [CAShapeLayer] { guard let sublayers = self.background.layer.sublayers else { return [] } return sublayers.compactMap { layer in layer as? CAShapeLayer } } func getSize() -> CGSize { layoutIfNeeded() return frame.size } var isAddedForVerification: Bool = false { didSet { UIView.highlightAnimation { self.wordLabel.alpha = self.isAddedForVerification ? 0 : 1 self.background.backgroundColor = self.isAddedForVerification ? nil : Theme.lightTextColor self.alpha = self.isAddedForVerification ? 0.6 : 1 self.setBorder(dashed: self.isAddedForVerification) } } } override var isHighlighted: Bool { didSet { if isHighlighted != oldValue { feedbackGenerator.impactOccurred() UIView.highlightAnimation { self.backgroundOverlay.alpha = self.isHighlighted ? 1 : 0 } } } } } extension UIView { func addDashedBorder() { let shapeLayer = CAShapeLayer() shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.black.withAlphaComponent(0.1).cgColor shapeLayer.lineWidth = 2 shapeLayer.lineJoin = kCALineJoinRound self.layer.addSublayer(shapeLayer) } }
6ea945dbed292f81d3bd0c07e7c29d23
32.024691
107
0.651215
false
false
false
false
grpc/grpc-swift
refs/heads/main
Tests/GRPCTests/EchoHelpers/Interceptors/EchoInterceptorFactories.swift
apache-2.0
1
/* * Copyright 2021, gRPC Authors 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 EchoModel import GRPC // MARK: - Client internal final class EchoClientInterceptors: Echo_EchoClientInterceptorFactoryProtocol { #if swift(>=5.6) internal typealias Factory = @Sendable () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #else internal typealias Factory = () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #endif // swift(>=5.6) private let factories: [Factory] internal init(_ factories: Factory...) { self.factories = factories } private func makeInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } } // MARK: - Server internal final class EchoServerInterceptors: Echo_EchoServerInterceptorFactoryProtocol { internal typealias Factory = () -> ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse> private var factories: [Factory] = [] internal init(_ factories: Factory...) { self.factories = factories } internal func register(_ factory: @escaping Factory) { self.factories.append(factory) } private func makeInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } }
7249bf1cd77cc95deda00f3c059dbbae
31.829545
95
0.734856
false
false
false
false
peferron/algo
refs/heads/master
EPI/Linked Lists/Remove the kth last element from a list/swift/test.swift
mit
1
import Darwin func nodes(_ count: Int) -> [Node] { let nodes = (0..<count).map { _ in Node() } for i in 0..<count - 1 { nodes[i].next = nodes[i + 1] } return nodes } ({ let n = nodes(3) let newHead = n[0].removeLast(0) guard newHead === n[0] && n[0].next === n[1] && n[1].next == nil else { print("Failed test removing last node") exit(1) } })() ({ let n = nodes(3) let newHead = n[0].removeLast(1) guard newHead === n[0] && n[0].next === n[2] && n[2].next == nil else { print("Failed test removing 2nd last node") exit(1) } })() ({ let n = nodes(3) let newHead = n[0].removeLast(2) guard newHead === n[1] && n[1].next === n[2] && n[2].next == nil else { print("Failed test removing 3rd last node") exit(1) } })() ({ let n = nodes(1) let newHead = n[0].removeLast(0) guard newHead == nil else { print("Failed test removing only node") exit(1) } })()
11a15797d5bc7613eae1d0cc02b4970e
19.632653
75
0.497527
false
true
false
false
AnRanScheme/MagiRefresh
refs/heads/master
Example/MagiRefresh/MagiRefresh/Default/MagiRefreshDefaults.swift
mit
3
// // MagiRefreshDefaults.swift // MagiRefresh // // Created by anran on 2018/9/4. // Copyright © 2018年 anran. All rights reserved. // import UIKit public enum MagiRefreshStyle: Int { case native = 0 case replicatorWoody case replicatorAllen case replicatorCircle case replicatorDot case replicatorArc case replicatorTriangle case animatableRing case animatableArrow } public class MagiRefreshDefaults { public var headerDefaultStyle: MagiRefreshStyle = .animatableArrow public var footerDefaultStyle: MagiRefreshStyle = .native public var themeColor: UIColor = UIColor.blue public var backgroundColor: UIColor = UIColor.white public var headPullingText: String = "继续下拉" public var footPullingText: String = "继续上拉" public var readyText: String = "松开刷新" public var refreshingText: String = "正在加载" public static let shared = MagiRefreshDefaults() }
0838446240364f27266585508b41b1c3
25.138889
70
0.723698
false
false
false
false
boostcode/tori
refs/heads/master
Sources/tori/main.swift
apache-2.0
1
/** * Copyright boostco.de 2016 * * 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 // kitura import KituraSys import KituraNet import Kitura // mongodb orm import MongoKitten // logger import LoggerAPI import HeliumLogger Log.logger = HeliumLogger() #if os(Linux) import Glibc #endif // router setup let router = Router() // roles enum Role: Int { case Admin case Guest // add your extra roles here } // database setup let db = setupDb() setupTori() // MARK: - Start adding here your collections // get config let (_, _, _, toriPort, _, _) = getConfiguration() // setup server let server = HttpServer.listen( port: toriPort, delegate: router ) Log.debug("Tori is running at port \(toriPort)") Server.run()
976f4b3d3f2cddf6a00ee25ef87be83f
18.640625
74
0.719968
false
false
false
false
mflint/ios-tldr-viewer
refs/heads/master
tldr-viewer/ListViewModel.swift
mit
1
// // ListViewModel.swift // tldr-viewer // // Created by Matthew Flint on 30/12/2015. // Copyright © 2015 Green Light. All rights reserved. // import Foundation import UIKit /* The list of commands is loaded by the `DataSource` class, and passes through a series of decorators before arriving at the ListViewModel: +------------+ | DataSource | +------+-----+ | +---------------+--------------+ | FilteringDataSourceDecorator | +---------------+--------------+ | +-----------------------------------+-----------------------------------+ | SwitchingDataSourceDecorator | | | | +------------------------------+ +------------------------------+ | | | SearchingDataSourceDecorator | | FavouriteDataSourceDecorator | | | +------------------------------+ +------------------------------+ | +-----------------------------------+-----------------------------------+ | +-------+-------+ | ListViewModel | +---------------+ `DataSource` loads the raw command data from the `Documents` directory. It can refresh data from the network if necessary. `FilteringDataSourceDecorator` filters the command data, removing commands that the user never wants to see. This might be due to their locale or their preferred platforms. `SwitchingDataSourceDecorator` is a type which can switch between multiple other decorators. Currently is has two, one for each of the segmented controls on the List Commands screen. `SearchableDataSourceDecorator` filters the Command list based on the user's search criteria. `FavouritesDataSourceDecorator` filters the Command list based on the user's favourite commands. */ class ListViewModel: NSObject { // no-op closures until the ViewController provides its own var updateSegmentSignal: () -> Void = {} var updateSignal: (_ indexPath: IndexPath?) -> Void = {(indexPath) in} var showDetail: (_ detailViewModel: DetailViewModel) -> Void = {(vm) in} var cancelSearchSignal: () -> Void = {} var canSearch: Bool { return DataSources.sharedInstance.switchingDataSource.isSearchable } var canRefresh: Bool { return DataSources.sharedInstance.switchingDataSource.isRefreshable } var lastUpdatedString: String { if let lastUpdateTime = DataSources.sharedInstance.baseDataSource.lastUpdateTime() { let lastUpdatedDateTime = dateFormatter.string(from: lastUpdateTime) return Localizations.CommandList.AllCommands.UpdatedDateTime(lastUpdatedDateTime) } return "" } var searchText: String { return DataSources.sharedInstance.searchingDataSource.searchText } let searchPlaceholder = Localizations.CommandList.AllCommands.SearchPlaceholder var itemSelected: Bool = false var requesting: Bool { return DataSources.sharedInstance.baseDataSource.requesting } // TODO: animate tableview contents when this changes // TODO: cache sectionViewModels for each selectable datasource, and only update when we get an update signal from that datasource var sectionViewModels = [SectionViewModel]() var sectionIndexes = [String]() var dataSourceNames: [String]! var detailVisible: Bool = false private let dataSource = DataSources.sharedInstance.switchingDataSource private let dateFormatter = DateFormatter() var selectedDataSourceIndex: Int { get { return DataSources.sharedInstance.switchingDataSource.selectedDataSourceIndex } set { let switcher = DataSources.sharedInstance.switchingDataSource switcher.selectedDataSourceIndex = newValue // update the selected datasource (segment control) in the UI updateSegmentSignal() } } private var cellViewModels = [BaseCellViewModel]() override init() { super.init() dataSource.add(delegate: self) dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short dataSourceNames = DataSources.sharedInstance.switchingDataSource.underlyingDataSources.map({ (switchable) -> String in return switchable.name }) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.externalCommandChange(notification:)), name: Constant.ExternalCommandChangeNotification.name, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.detailShown(notification:)), name: Constant.DetailViewPresence.shownNotificationName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ListViewModel.detailHidden(notification:)), name: Constant.DetailViewPresence.hiddenNotificationName, object: nil) DataSources.sharedInstance.baseDataSource.loadInitialCommands() } deinit { NotificationCenter.default.removeObserver(self) } @objc func externalCommandChange(notification: Notification) { guard let userInfo = notification.userInfo, let commandName = userInfo[Constant.ExternalCommandChangeNotification.commandNameKey] as? String, let command = DataSources.sharedInstance.baseDataSource.commandWith(name: commandName) else { return } showCommand(commandName: command.name) } @objc func detailShown(notification: Notification) { detailVisible = true } @objc func detailHidden(notification: Notification) { detailVisible = false } func refreshData() { DataSources.sharedInstance.baseDataSource.refresh() } private func update() { var vms = [BaseCellViewModel]() let commands = dataSource.commands if dataSource.isRefreshable { if requesting { let cellViewModel = LoadingCellViewModel() vms.append(cellViewModel) } let baseDataSource = DataSources.sharedInstance.baseDataSource if let errorText = baseDataSource.requestError { let cellViewModel = ErrorCellViewModel(errorText: errorText, buttonAction: { baseDataSource.refresh() }) vms.append(cellViewModel) } else if !requesting, let oldIndexCell = OldIndexCellViewModel.create() { vms.append(oldIndexCell) } } if commands.count == 0 { switch dataSource.selectedDataSourceType { case .all: if !DataSources.sharedInstance.searchingDataSource.searchText.isEmpty { // no search results let cellViewModel = NoResultsCellViewModel(searchTerm: searchText, buttonAction: { let url = URL(string: "https://github.com/tldr-pages/tldr/blob/master/CONTRIBUTING.md")! UIApplication.shared.open(url, options: [:], completionHandler: nil) }) vms.append(cellViewModel) } case .favourites: vms.append(NoFavouritesCellViewModel()) } } for command in commands { let cellViewModel = CommandCellViewModel(command: command, action: { let detailViewModel = DetailViewModel(command: command) self.showDetail(detailViewModel) }) vms.append(cellViewModel) } cellViewModels = vms makeSectionsAndCells() updateSignal(nil) } private func makeSectionsAndCells() { // all sections var sections = [SectionViewModel]() // current section var currentSection: SectionViewModel? for cellViewModel in cellViewModels { if currentSection == nil || !currentSection!.accept(cellViewModel: cellViewModel) { currentSection = SectionViewModel(firstCellViewModel: cellViewModel) sections.append(currentSection!) } } sectionViewModels = SectionViewModel.sort(sections: sections) sectionIndexes = sectionViewModels.map({ section in section.title }) } func didSelectRow(at indexPath: IndexPath) { selectRow(indexPath: indexPath) cancelSearchSignal() } private func selectRow(indexPath: IndexPath) { itemSelected = true sectionViewModels[indexPath.section].cellViewModels[indexPath.row].performAction() } func filterTextDidChange(text: String) { setFilter(text: text) } private func setFilter(text: String) { DataSources.sharedInstance.searchingDataSource.searchText = text } func filterCancel() { cancelSearchSignal() setFilter(text: "") } func showCommand(commandName: String) { // kill any search cancelSearchSignal() DataSources.sharedInstance.searchingDataSource.searchText = "" // now find the NSIndexPath for the CommandCellViewModel for this command name var indexPath: IndexPath? for (sectionIndex, sectionViewModel) in sectionViewModels.enumerated() { for (cellIndex, cellViewModel) in sectionViewModel.cellViewModels.enumerated() { if let commandCellViewModel = cellViewModel as? CommandCellViewModel { if commandCellViewModel.command.name == commandName { indexPath = IndexPath(row: cellIndex, section: sectionIndex) } } } } if let indexPath = indexPath { if (!detailVisible) { // this will trigger the segue. If detail already visible, the detail viewmodel will handle it selectRow(indexPath: indexPath) } updateSignal(indexPath) } } func showDetailWhenHorizontallyCompact() -> Bool { return itemSelected } } extension ListViewModel: DataSourceDelegate { func dataSourceDidUpdate(dataSource: DataSourcing) { update() } }
d12a27a7739b29a2e3b01681716f18fa
36.850174
193
0.58888
false
false
false
false
andyyhope/Elbbbird
refs/heads/master
Elbbbird/Model/User.swift
gpl-3.0
1
// // User.swift // Elbbbird // // Created by Andyy Hope on 16/03/2016. // Copyright © 2016 Andyy Hope. All rights reserved. // import Foundation import SwiftyJSON struct Links { let web: String let twitter: String init?(json: JSON) { self.web = json["web"].stringValue self.twitter = json["twitter"].stringValue } } struct User { let id: Int let username: String let name: String? let bio: String? let location: String? let avatarURL: String let htmlURL: String let followers: Count? let following: Count? let likes: Count? let projects: Count? let shots: Count? let teams: Count? init?(json: JSON) { self.id = json["id"].intValue self.username = json["username"].stringValue self.name = json["name"].stringValue self.bio = json["bio"].stringValue self.location = json["location"].stringValue self.avatarURL = json["avatar_url"].stringValue self.htmlURL = json["html_url"].stringValue self.followers = Count(url: json["followers_url"].stringValue, count: json["followers_count"].intValue) self.following = Count(url: json["following_url"].stringValue, count: json["following_count"].intValue) self.likes = Count(url: json["likes_url"].stringValue, count: json["likes_count"].intValue) self.projects = Count(url: json["projects_url"].stringValue, count: json["projects_count"].intValue) self.shots = Count(url: json["shots_url"].stringValue, count: json["shots_count"].intValue) self.teams = Count(url: json["teams_url"].stringValue, count: json["teams_count"].intValue) } }
712cf4c5420b490a66ce114751b3c65b
25.22973
70
0.558763
false
false
false
false
alaphao/gitstatus
refs/heads/master
GitStatus/GitStatus/GitButton2.swift
mit
1
// // GitButton2.swift // GitStatus // // Created by Aleph Retamal on 4/30/15. // Copyright (c) 2015 Guilherme Ferreira de Souza. All rights reserved. // import UIKit @IBDesignable class GitButton2: UIButton { var bgLayer: CAGradientLayer! let colorTop = UIColor(hex: "fcfcfc").CGColor let colorBottom = UIColor(hex: "eeeeee").CGColor override func drawRect(rect: CGRect) { if bgLayer == nil { bgLayer = CAGradientLayer() bgLayer.frame = self.bounds bgLayer.colors = [colorTop, colorBottom] bgLayer.locations = [0.0, 1.0] bgLayer.borderColor = UIColor(hex: "d5d5d5").CGColor bgLayer.borderWidth = 1 bgLayer.cornerRadius = 3 self.layer.insertSublayer(bgLayer, atIndex: 0) } } }
a84a4de1810198fac2083dc970f817b8
23.628571
72
0.586527
false
false
false
false
CryptoKitten/CryptoEssentials
refs/heads/master
Sources/BytesSequence.swift
mit
1
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. import Foundation public struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] public init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } public func makeIterator() -> AnyIterator<ArraySlice<UInt8>> { var offset:Int = 0 return AnyIterator { let end = Swift.min(self.chunkSize, self.data.count - offset) let result = self.data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } }
effa166e456cf14a5e2a53370fe34692
45.176471
216
0.704459
false
false
false
false
mattjgalloway/emoncms-ios
refs/heads/master
EmonCMSiOS/ViewModel/FeedChartViewModel.swift
mit
1
// // FeedChartViewModel.swift // EmonCMSiOS // // Created by Matt Galloway on 19/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RxSwift import RxCocoa final class FeedChartViewModel { private let account: Account private let api: EmonCMSAPI private let feedId: String // Inputs let active = Variable<Bool>(false) let dateRange: Variable<DateRange> let refresh = ReplaySubject<()>.create(bufferSize: 1) // Outputs private(set) var dataPoints: Driver<[DataPoint]> private(set) var isRefreshing: Driver<Bool> init(account: Account, api: EmonCMSAPI, feedId: String) { self.account = account self.api = api self.feedId = feedId self.dateRange = Variable<DateRange>(DateRange.relative(.hour8)) self.dataPoints = Driver.empty() let isRefreshing = ActivityIndicator() self.isRefreshing = isRefreshing.asDriver() let becameActive = self.active.asObservable() .filter { $0 == true } .distinctUntilChanged() .becomeVoid() let refreshSignal = Observable.of(self.refresh, becameActive) .merge() let dateRange = self.dateRange.asObservable() self.dataPoints = Observable.combineLatest(refreshSignal, dateRange) { $1 } .flatMapLatest { [weak self] dateRange -> Observable<[DataPoint]> in guard let strongSelf = self else { return Observable.empty() } let feedId = strongSelf.feedId let (startDate, endDate) = dateRange.calculateDates() let interval = Int(endDate.timeIntervalSince(startDate) / 500) return strongSelf.api.feedData(strongSelf.account, id: feedId, at: startDate, until: endDate, interval: interval) .catchErrorJustReturn([]) .trackActivity(isRefreshing) } .asDriver(onErrorJustReturn: []) } }
04725b253c5143543f86c252bfe1e369
26.727273
121
0.691257
false
false
false
false
safx/iOS9-InterApp-DnD-Demo
refs/heads/master
SampleX/Shape.swift
mit
1
// // Shape.swift // ios9-dnd-demo // // Created by Safx Developer on 2015/09/27. // // import UIKit enum Shape { case Rectangle(pos: CGPoint, size: CGSize, color: UIColor) case Ellipse(pos: CGPoint, size: CGSize, color: UIColor) static func createShape(type: String, size: CGSize, color: String) -> Shape? { let pos = CGPointMake(-10000, -10000) // FIXME let color = Shape.stringToColor(color: color) switch type { case "rectangle": return .Rectangle(pos: pos, size: size, color: color) case "ellipse": return .Ellipse (pos: pos, size: size, color: color) default: return nil } } mutating func changePosition(pos: CGPoint) { switch self { case .Rectangle(let (_, size, color)): self = .Rectangle(pos: pos, size: size, color: color) case .Ellipse(let (_, size, color)): self = .Ellipse(pos: pos, size: size, color: color) } } static func colorToString(color: UIColor) -> String { var c = [CGFloat](count: 4, repeatedValue: 0.0) color.getRed(&c[0], green: &c[1], blue: &c[2], alpha: &c[3]) return c[0...2].map{String(format:"%02X", Int(255 * $0))}.joinWithSeparator("") } static func stringToColor(color c: String) -> UIColor { precondition(c.characters.count == 6) let cs = [ c[Range(start: c.startIndex, end: c.startIndex.advancedBy(2))], c[Range(start: c.startIndex.advancedBy(2), end: c.startIndex.advancedBy(4))], c[Range(start: c.startIndex.advancedBy(4), end: c.startIndex.advancedBy(6))] ].flatMap{ Int($0, radix: 16) } assert(cs.count == 3) let z = cs.map{ CGFloat($0) } return UIColor(red: z[0], green: z[1], blue: z[2], alpha: CGFloat(1.0)) } var position: CGPoint { switch self { case .Rectangle(let (p, _, _)): return p case .Ellipse(let (p, _, _)): return p } } var string: String { switch self { case .Rectangle(let (_, s, c)): return "rectangle,\(Int(s.width)),\(Int(s.height)),\(Shape.colorToString(c))" case .Ellipse(let (_, s, c)): return "ellipse,\(Int(s.width)),\(Int(s.height)),\(Shape.colorToString(c))" } } } protocol Drawable { func draw() } extension Shape: Drawable { func draw() { color.setFill() path.fill() } private var color: UIColor { switch self { case .Rectangle(let (_, _, color)): return color case .Ellipse(let (_, _, color)): return color } } private var path: UIBezierPath { switch self { case .Rectangle(let (pos, size, _)): return UIBezierPath(rect: CGRect(origin: pos, size: size)) case .Ellipse(let (pos, size, _)): return UIBezierPath(ovalInRect: CGRect(origin: pos, size: size)) } } } extension Shape { func isClicked(pos: CGPoint) -> Bool { switch self { case .Rectangle(let (p, s, _)): let rect = CGRect(origin: p, size: s) return CGRectContainsPoint(rect, pos) case .Ellipse(let (p, s, _)): let rw = s.width / 2 let rh = s.height / 2 let c = CGPointMake(p.x + rw, p.y + rh) let x = pos.x - c.x let y = pos.y - c.y let w = rw * rw let h = rh * rh return (x * x) / w + (y * y) / h <= 1.0 } } }
140956a6d14ea79629097220c86ac067
30.468468
117
0.540796
false
false
false
false
JJMoon/MySwiftCheatSheet
refs/heads/master
LogTimerLogic/HtUtilTimers.swift
apache-2.0
1
// // HtUtilTimers.swift // heartisense // // Created by Jongwoo Moon on 2015. 10. 27.. // Copyright © 2015년 gyuchan. All rights reserved. // import Foundation class HtGenTimer : NSObject { var startTime = NSDate.timeIntervalSinceReferenceDate() var endTime = NSDate.timeIntervalSinceReferenceDate() var totalSec: Double { get { return endTime - startTime } } var timeSinceStart: Double { get { return NSDate.timeIntervalSinceReferenceDate() - startTime } } var timeSinceEnd: Double { get { return NSDate.timeIntervalSinceReferenceDate() - endTime } } func markStart() { startTime = NSDate.timeIntervalSinceReferenceDate() } func markEnd() { endTime = NSDate.timeIntervalSinceReferenceDate() } } class HtDelayTimer : NSObject { var defaultDelayTime = 0.1 var theTimer = NSTimer() var theAction: (Void)-> Void = { } func doAction() { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(defaultDelayTime * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), theAction) } func cancel() { theTimer.invalidate() } func setDelay(delay:Double, closure:()->()) { // 딜레이 함수.. theAction = closure theTimer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(HtDelayTimer.doAction), userInfo: nil, repeats: false) // 한번만 실행.. } } ////////////////////////////////////////////////////////////////////// _//////////_ [ Pause .. << >> ] _//////////_ // MARK: - Pause 용 타이머 class HtUnitJob : NSObject { var actTimeInSec:Double = 0 var theAction: (Void)-> Void = { } override init() { super.init() } convenience init(pTime: Double, pAct : ()->()) { self.init() self.actTimeInSec = pTime self.theAction = pAct } } class HtPauseCtrlTimer : HtStopWatch { var arrJobs = [HtUnitJob]() func resetJobs() { resetTime() arrJobs = [HtUnitJob]() } func addJob(pTime: Double, pAct : (Void)->Void) { let newJob = HtUnitJob(pTime: pTime, pAct: pAct) arrJobs.append(newJob) } func updateJob() { setDueTime() if arrJobs.count == 0 || dueTime < arrJobs[0].actTimeInSec { return } let curJob = arrJobs[0] curJob.theAction() arrJobs.removeAtIndex(0) } }
bb0805baed99446b2a8061c7ed9e351d
26.885057
129
0.584501
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/C29Scope.swift
mit
1
// // C29Scope // Copper // This is our work-horse class, holding the logic for all operations dealing with CopperRecords // and talking back to the network about them. // // Created by Doug Williams on 12/18/14. // Copyright (c) 2014 Doug Williams. All rights reserved. // @objc public enum C29Scope: Int { // We must use Ints because these are included in @objc protocols which don't support String backing stores // New and unset case Null = -1 // unset in API terms // Order and these numbers matter in two ways // First: they signify common groupings (see isMulti... and isDynamicRecord() below) // Second: they represent the preferred order of display on the Identity Sheet and Request Sheet // Multi entries -- records that can have 0-N of the same entries // enums can't have stored properties so we leave them here in comments for future reference // let MultiRawValueMin = 1000 // let MultiRawValueMax = 1999 case Name = 1000 case Picture = 1001 case Phone = 1002 case Email = 1003 case Username = 1004 case Address = 1005 case Birthday = 1006 case Signature = 1007 // Set entries case ContactsFavorites = 3001 private static let scopesWithKeys: [C29Scope: String] = [C29Scope.Address: "address", C29Scope.ContactsFavorites: "contacts", C29Scope.Email: "email", C29Scope.Name: "name", C29Scope.Phone: "phone", C29Scope.Picture: "picture", C29Scope.Username: "username", C29Scope.Birthday: "birthday", C29Scope.Signature: "signature"] public static let All = [C29Scope] (scopesWithKeys.keys) public static let DefaultScopes = [C29Scope.Name, C29Scope.Picture, C29Scope.Phone] public static func fromString(scope: String) -> C29Scope? { let keys = scopesWithKeys.filter { $1 == scope }.map { $0.0 } // note: returns an array if keys.count > 0 { return keys.first } return C29Scope?() } public var value: String? { return C29Scope.scopesWithKeys[self] } public var displayName : String { switch self { case .Address: return "Street Address".localized case .ContactsFavorites: return "Favorite People 👪".localized case .Email: return "Email Address".localized case .Name: return "Name".localized case .Phone: return "Phone Number".localized case .Picture: return "Picture".localized case .Username: return "Username".localized case .Birthday: return "Birthday".localized case .Signature: return "Signature".localized case .Null: return "null".localized } } public func sectionTitle(numberOfRecords: Int = 0) -> String { switch self { case .Address: if numberOfRecords < 2 { return "Shipping Address".localized.uppercaseString } else { return "Addresses".localized.uppercaseString } case .ContactsFavorites: return "Contacts".localized.uppercaseString case .Email: if numberOfRecords < 2 { return "Email".localized.uppercaseString } else { return "Emails".localized.uppercaseString } case .Name, .Picture: return "Profile".localized.uppercaseString case .Phone: if numberOfRecords < 2 { return "Number".localized.uppercaseString } else { return "Numbers".localized.uppercaseString } case .Username: return "Username".localized default: return self.displayName.uppercaseString } } public var addRecordString: String { switch self { case .Address: return "add new shipping address".localized case .Email: return "add new email".localized case .Phone: return "add new phone".localized case .Username: return "add your preferred username".localized case .Birthday: return "add your birthday".localized case .Signature: return "add your signature 👆🏾".localized default: return "We don't use addEntry for this scope 🦄" } } public func createRecord() -> CopperRecordObject? { switch self { case .Address: return CopperAddressRecord() case .ContactsFavorites: return CopperContactsRecord() case .Email: return CopperEmailRecord() case .Name: return CopperNameRecord() case .Phone: return CopperPhoneRecord() case .Picture: return CopperPictureRecord() case .Username: return CopperUsernameRecord() case .Birthday: return CopperDateRecord() case .Signature: return CopperSignatureRecord() default: return CopperRecordObject?() } } var dataKeys: [ScopeDataKeys] { switch self { case .Address: return [.AddressStreetOne, .AddressStreetTwo, .AddressCity, .AddressState, .AddressZip, .AddressCountry] case .ContactsFavorites: return [.ContactsContacts] case .Email: return [.EmailAddress] case .Name: return [.NameFirstName, .NameLastName] case .Phone: return [.PhoneNumber] case .Picture: return [.PictureImage, .PictureURL] case .Username: return [.Username] case .Birthday: return [.Date] case .Signature: return [.SignatureImage, .SignatureURL] case .Null: return [] } } public static func getCommaDelinatedString(fromScopes scopes: [C29Scope]?) -> String { guard let scopes = scopes else { return "" } var scopesStrings = [String]() for scopeString in scopes { scopesStrings.append(scopeString.value!) } return scopesStrings.joinWithSeparator(",") } // This is only used for SingleLineEditCell.swift, to set the perferredKeyboard for entry // this could potentially be much more robust for all types but for now we limit it to CopperMultiRecords. // For example, the AddressEditCell programmatically sets it's own, hard coded, since there is only (currently) one address type public var preferredKeyboard: UIKeyboardType? { switch self { case .Email: return .EmailAddress case .Phone: return .PhonePad default: return UIKeyboardType?() } } } enum ScopeDataKeys: String { // .Address case AddressStreetOne = "street_one" case AddressStreetTwo = "street_two" case AddressCity = "city" case AddressState = "state" case AddressZip = "zip" case AddressCountry = "country" // .Email case EmailAddress = "email" // .Contacts favorites case ContactsContacts = "contacts" // .Name case NameFirstName = "first_name" case NameLastName = "last_name" // .Phone case PhoneNumber = "phone_number" // .Picture case PictureImage = "picture" case PictureURL = "url" // .Username case Username = "username" // .Birthdate case Date = "date" // .Signature case SignatureImage = "image" case SignatureURL = "imageUrl" }
b248caaca3011600a4f61c025ee2117d
30.942387
132
0.590903
false
false
false
false
appnexus/mobile-sdk-ios
refs/heads/master
examples/SimpleMediation/SimpleMediation/ANAdAdapterNativeAdMob.swift
apache-2.0
1
// // CustomAdapter.swift // SimpleMediation // // Created by System on 17/05/22. // Copyright © 2022 Xandr. All rights reserved. // import Foundation import AppNexusSDK import GoogleMobileAds @objc(ANAdAdapterNativeAdMob) public class ANAdAdapterNativeAdMob : NSObject , ANNativeCustomAdapter , GADNativeAdLoaderDelegate, GADNativeAdDelegate { var nativeAdLoader: GADAdLoader! var proxyViewController : ANProxyViewController! var nativeAd: GADNativeAd? override init() { super.init() // hasExpired = true proxyViewController = ANProxyViewController() } public func requestNativeAd( withServerParameter parameterString: String?, adUnitId: String?, targetingParameters: ANTargetingParameters? ) { nativeAdLoader = GADAdLoader( adUnitID: adUnitId!, rootViewController: proxyViewController as? UIViewController, adTypes: [GADAdLoaderAdType.native], options: []) nativeAdLoader.delegate = self nativeAdLoader.load(GADRequest()) } public var requestDelegate: ANNativeCustomAdapterRequestDelegate? // @nonobjc public var hasExpired: Bool? public var nativeAdDelegate: ANNativeCustomAdapterAdDelegate? public var expired: ObjCBool? public func hasExpired() -> DarwinBoolean{ return false } public func registerView(forImpressionTrackingAndClickHandling view: UIView, withRootViewController rvc: UIViewController, clickableViews: [Any]?) { print("registerView by Ab") // public func registerView(forImpressionTrackingAndClickHandling view: UIView, withRootViewController rvc: UIViewController, clickableViews: [Any]?) { proxyViewController.rootViewController = rvc proxyViewController.adView = view if (nativeAd != nil) { if view is GADNativeAdView { let nativeContentAdView = view as? GADNativeAdView nativeContentAdView?.nativeAd = nativeAd } return; } } public func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) { // self.hasExpired = false let response = ANNativeMediatedAdResponse( customAdapter: self, networkCode: ANNativeAdNetworkCode.adMob) nativeAd.delegate = self response?.title = nativeAd.headline response?.body = nativeAd.body response?.iconImageURL = nativeAd.icon?.imageURL response?.iconImageURL = nativeAd.icon?.imageURL response?.mainImageURL = (nativeAd.images?.first)?.imageURL response?.callToAction = nativeAd.callToAction response?.rating = ANNativeAdStarRating( value: CGFloat(nativeAd.starRating?.floatValue ?? 0.0), scale: Int(5.0)) response?.customElements = [ kANNativeElementObject: nativeAd ] requestDelegate?.didLoadNativeAd!(response!) } public func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) { requestDelegate?.didFail!(toLoadNativeAd: ANAdResponseCode.unable_TO_FILL()) } public func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) { // The native ad was shown. self.nativeAdDelegate?.adDidLogImpression!() } public func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) { // The native ad was clicked on. self.nativeAdDelegate?.adWasClicked!() } public func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) { // The native ad will present a full screen view. self.nativeAdDelegate?.didPresentAd!() } public func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) { // The native ad will dismiss a full screen view. self.nativeAdDelegate?.willCloseAd!() } public func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) { // The native ad did dismiss a full screen view. self.nativeAdDelegate?.didCloseAd!() } public func nativeAdWillLeaveApplication(_ nativeAd: GADNativeAd) { // The native ad will cause the application to become inactive and // open a new application. self.nativeAdDelegate?.willLeaveApplication!() } // public func hasExpired() -> Bool { // return true // } }
beccf933026b437058fe5ab50f687f4e
31.369565
154
0.659279
false
false
false
false
saitjr/STFakeLabel
refs/heads/master
Example/STFakeLabel-Swift/STFakeLabel-Swift/classes-Swift/STFakeLabel/STFakeAnimation.swift
mit
2
// // STFakeAnimation.swift // STFakeLabel-Swift // // Created by TangJR on 12/4/15. // Copyright © 2015 tangjr. 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 /** STFakeAnimation is an Swift extension that adds fake 3D animation to UIlabel object class. It is intended to be simple, lightweight, and easy to use. Animate just need a single line of code 'st_startAnimation' method animate with direction and new text */ extension UILabel { enum STFakeAnimationDirection: Int { case Right = 1 ///< left to right case Left = -1 ///< right to left case Down = -2 ///< up to down case Up = 2 ///< down to up } func st_startAnimation(direction: STFakeAnimationDirection, toText: String!) { if st_isAnimatin! { return } st_isAnimatin = true let fakeLabel = UILabel() fakeLabel.frame = frame fakeLabel.text = toText fakeLabel.textAlignment = textAlignment fakeLabel.textColor = textColor fakeLabel.font = font fakeLabel.backgroundColor = backgroundColor != nil ? backgroundColor : UIColor.clearColor() self.superview!.addSubview(fakeLabel) var labelOffsetX: CGFloat = 0.0 var labelOffsetY: CGFloat = 0.0 var labelScaleX: CGFloat = 0.1 var labelScaleY: CGFloat = 0.1 if direction == .Down || direction == .Up { labelOffsetY = CGFloat(direction.rawValue) * CGRectGetHeight(self.bounds) / 4.0; labelScaleX = 1.0; } if direction == .Left || direction == .Right { labelOffsetX = CGFloat(direction.rawValue) * CGRectGetWidth(self.bounds) / 2.0; labelScaleY = 1.0; } fakeLabel.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(labelScaleX, labelScaleY), CGAffineTransformMakeTranslation(labelOffsetX, labelOffsetY)) UIView.animateWithDuration(Config.STFakeLabelAnimationDuration, animations: { () -> Void in fakeLabel.transform = CGAffineTransformIdentity self.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(labelScaleX, labelScaleY), CGAffineTransformMakeTranslation(-labelOffsetX, -labelOffsetY)) }) { (finish: Bool) -> Void in self.transform = CGAffineTransformIdentity self.text = toText fakeLabel.removeFromSuperview() self.st_isAnimatin = false } } // animation duration private struct Config { static var STFakeLabelAnimationDuration = 0.7 } // st_isAnimating asscoiate key private struct AssociatedKeys { static var STFakeLabelAnimationIsAnimatingKey = "STFakeLabelAnimationIsAnimatingKey" } // default is false private var st_isAnimatin: Bool? { get { let isAnimating = objc_getAssociatedObject(self, &AssociatedKeys.STFakeLabelAnimationIsAnimatingKey) as? Bool // if variable is not set, return false as default guard let _ = isAnimating else { return false } return isAnimating } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.STFakeLabelAnimationIsAnimatingKey, newValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
27cd548737d2b38af000832492709758
39.371681
170
0.656216
false
false
false
false
apple/swift-syntax
refs/heads/main
Sources/SwiftParserDiagnostics/Utils.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { /// Remove any leading or trailing spaces. /// This is necessary to avoid depending SwiftParser on Foundation. func trimmingWhitespace() -> String { let charactersToDrop: [Character] = [" ", "\t", "\n", "\r"] var result: Substring = Substring(self) result = result.drop(while: { charactersToDrop.contains($0) }) while let lastCharacter = result.last, charactersToDrop.contains(lastCharacter) { result = result.dropLast(1) } return String(result) } func withFirstLetterUppercased() -> String { if let firstLetter = self.first { return firstLetter.uppercased() + self.dropFirst() } else { return self } } } extension Collection { /// If the collection contains a single element, return it, otherwise `nil`. var only: Element? { if !isEmpty && index(after: startIndex) == endIndex { return self.first! } else { return nil } } }
208a0991b97e528a3fef1c25c0804379
32.227273
85
0.601231
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPosix/Bootstrap.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore #if os(Windows) import ucrt import func WinSDK.GetFileType import let WinSDK.FILE_TYPE_PIPE import let WinSDK.INVALID_HANDLE_VALUE import struct WinSDK.DWORD import struct WinSDK.HANDLE #endif #if swift(>=5.7) /// The type of all `channelInitializer` callbacks. internal typealias ChannelInitializerCallback = @Sendable (Channel) -> EventLoopFuture<Void> #else /// The type of all `channelInitializer` callbacks. internal typealias ChannelInitializerCallback = (Channel) -> EventLoopFuture<Void> #endif /// Common functionality for all NIO on sockets bootstraps. internal enum NIOOnSocketsBootstraps { internal static func isCompatible(group: EventLoopGroup) -> Bool { return group is SelectableEventLoop || group is MultiThreadedEventLoopGroup } } /// A `ServerBootstrap` is an easy way to bootstrap a `ServerSocketChannel` when creating network servers. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = ServerBootstrap(group: group) /// // Specify backlog and enable SO_REUSEADDR for the server itself /// .serverChannelOption(ChannelOptions.backlog, value: 256) /// .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// /// // Set the handlers that are applied to the accepted child `Channel`s. /// .childChannelInitializer { channel in /// // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. /// channel.pipeline.addHandler(BackPressureHandler()).flatMap { () in /// // make sure to instantiate your `ChannelHandlers` inside of /// // the closure as it will be invoked once per connection. /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// } /// /// // Enable SO_REUSEADDR for the accepted Channels /// .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16) /// .childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator()) /// let channel = try! bootstrap.bind(host: host, port: port).wait() /// /* the server will now be accepting connections */ /// /// try! channel.closeFuture.wait() // wait forever as we never close the Channel /// ``` /// /// The `EventLoopFuture` returned by `bind` will fire with a `ServerSocketChannel`. This is the channel that owns the listening socket. /// Each time it accepts a new connection it will fire a `SocketChannel` through the `ChannelPipeline` via `fireChannelRead`: as a result, /// the `ServerSocketChannel` operates on `Channel`s as inbound messages. Outbound messages are not supported on a `ServerSocketChannel` /// which means that each write attempt will fail. /// /// Accepted `SocketChannel`s operate on `ByteBuffer` as inbound data, and `IOData` as outbound data. public final class ServerBootstrap { private let group: EventLoopGroup private let childGroup: EventLoopGroup private var serverChannelInit: Optional<ChannelInitializerCallback> private var childChannelInit: Optional<ChannelInitializerCallback> @usableFromInline internal var _serverChannelOptions: ChannelOptions.Storage @usableFromInline internal var _childChannelOptions: ChannelOptions.Storage private var enableMPTCP: Bool /// Create a `ServerBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ServerBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group, childGroup: group)! } /// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`. /// /// The `EventLoopGroup`s `group` and `childGroup` must be compatible, otherwise the program will crash. /// `ServerBootstrap` is compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. /// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on. public convenience init(group: EventLoopGroup, childGroup: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else { preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with group: \(group) and " + "childGroup: \(childGroup) at least one of which is incompatible.") } self.init(validatingGroup: group, childGroup: childGroup)! } /// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`, validating /// that the `EventLoopGroup`s are compatible with `ServerBootstrap`. /// /// - parameters: /// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with. /// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on. If `nil`, `group` is used. public init?(validatingGroup group: EventLoopGroup, childGroup: EventLoopGroup? = nil) { let childGroup = childGroup ?? group guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else { return nil } self.group = group self.childGroup = childGroup self._serverChannelOptions = ChannelOptions.Storage() self._childChannelOptions = ChannelOptions.Storage() self.serverChannelInit = nil self.childChannelInit = nil self._serverChannelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1) self.enableMPTCP = false } #if swift(>=5.7) /// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The `ServerSocketChannel` uses the accepted `Channel`s as inbound messages. /// /// - note: To set the initializer for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelInitializer`. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. @preconcurrency public func serverChannelInitializer(_ initializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.serverChannelInit = initializer return self } #else /// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The `ServerSocketChannel` uses the accepted `Channel`s as inbound messages. /// /// - note: To set the initializer for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelInitializer`. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. public func serverChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.serverChannelInit = initializer return self } #endif #if swift(>=5.7) /// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. Note that if the `initializer` fails then the error will be /// fired in the *parent* channel. /// /// - warning: The `initializer` will be invoked once for every accepted connection. Therefore it's usually the /// right choice to instantiate stateful `ChannelHandler`s within the closure to make sure they are not /// accidentally shared across `Channel`s. There are expert use-cases where stateful handler need to be /// shared across `Channel`s in which case the user is responsible to synchronise the state access /// appropriately. /// /// The accepted `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. @preconcurrency public func childChannelInitializer(_ initializer: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.childChannelInit = initializer return self } #else /// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. Note that if the `initializer` fails then the error will be /// fired in the *parent* channel. /// /// - warning: The `initializer` will be invoked once for every accepted connection. Therefore it's usually the /// right choice to instantiate stateful `ChannelHandler`s within the closure to make sure they are not /// accidentally shared across `Channel`s. There are expert use-cases where stateful handler need to be /// shared across `Channel`s in which case the user is responsible to synchronise the state access /// appropriately. /// /// The accepted `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - parameters: /// - initializer: A closure that initializes the provided `Channel`. public func childChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.childChannelInit = initializer return self } #endif /// Specifies a `ChannelOption` to be applied to the `ServerSocketChannel`. /// /// - note: To specify options for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelOption`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func serverChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._serverChannelOptions.append(key: option, value: value) return self } /// Specifies a `ChannelOption` to be applied to the accepted `SocketChannel`s. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func childChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._childChannelOptions.append(key: option, value: value) return self } /// Specifies a timeout to apply to a bind attempt. Currently unsupported. /// /// - parameters: /// - timeout: The timeout that will apply to the bind attempt. public func bindTimeout(_ timeout: TimeAmount) -> Self { return self } /// Enables multi-path TCP support. /// /// This option is only supported on some systems, and will lead to bind /// failing if the system does not support it. Users are recommended to /// only enable this in response to configuration or feature detection. /// /// > Note: Enabling this setting will re-enable Nagle's algorithm, even if it /// > had been disabled. This is a temporary workaround for a Linux kernel /// > limitation. /// /// - parameters: /// - value: Whether to enable MPTCP or not. public func enableMPTCP(_ value: Bool) -> Self { self.enableMPTCP = value // This is a temporary workaround until we get some stable Linux kernel // versions that support TCP_NODELAY and MPTCP. if value { self._serverChannelOptions.remove(key: ChannelOptions.tcpOption(.tcp_nodelay)) } return self } /// Bind the `ServerSocketChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to bind on. /// - port: The port to bind on. public func bind(host: String, port: Int) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Bind the `ServerSocketChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> { return bind0 { address } } /// Bind the `ServerSocketChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system. public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return bind0 { try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } /// Bind the `ServerSocketChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system. /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`. public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> { if cleanupExistingSocketFile { do { try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) } catch { return group.next().makeFailedFuture(error) } } return self.bind(unixDomainSocketPath: unixDomainSocketPath) } #if !os(Windows) /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound stream socket. @available(*, deprecated, renamed: "withBoundSocket(_:)") public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return withBoundSocket(descriptor) } #endif /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound stream socket. public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel { if enableMPTCP { throw ChannelError.operationUnsupported } return try ServerSocketChannel(socket: socket, eventLoop: eventLoop, group: childEventLoopGroup) } return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in let promise = eventLoop.makePromise(of: Void.self) serverChannel.registerAlreadyConfigured0(promise: promise) return promise.futureResult } } private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel { return try ServerSocketChannel(eventLoop: eventLoop, group: childEventLoopGroup, protocolFamily: address.protocol, enableMPTCP: enableMPTCP) } return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in serverChannel.registerAndDoSynchronously { serverChannel in serverChannel.bind(to: address) } } } private func bind0(makeServerChannel: (_ eventLoop: SelectableEventLoop, _ childGroup: EventLoopGroup, _ enableMPTCP: Bool) throws -> ServerSocketChannel, _ register: @escaping (EventLoop, ServerSocketChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let eventLoop = self.group.next() let childEventLoopGroup = self.childGroup let serverChannelOptions = self._serverChannelOptions let serverChannelInit = self.serverChannelInit ?? { _ in eventLoop.makeSucceededFuture(()) } let childChannelInit = self.childChannelInit let childChannelOptions = self._childChannelOptions let serverChannel: ServerSocketChannel do { serverChannel = try makeServerChannel(eventLoop as! SelectableEventLoop, childEventLoopGroup, self.enableMPTCP) } catch { return eventLoop.makeFailedFuture(error) } return eventLoop.submit { serverChannelOptions.applyAllChannelOptions(to: serverChannel).flatMap { serverChannelInit(serverChannel) }.flatMap { serverChannel.pipeline.addHandler(AcceptHandler(childChannelInitializer: childChannelInit, childChannelOptions: childChannelOptions), name: "AcceptHandler") }.flatMap { register(eventLoop, serverChannel) }.map { serverChannel as Channel }.flatMapError { error in serverChannel.close0(error: error, mode: .all, promise: nil) return eventLoop.makeFailedFuture(error) } }.flatMap { $0 } } private class AcceptHandler: ChannelInboundHandler { public typealias InboundIn = SocketChannel private let childChannelInit: ((Channel) -> EventLoopFuture<Void>)? private let childChannelOptions: ChannelOptions.Storage init(childChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?, childChannelOptions: ChannelOptions.Storage) { self.childChannelInit = childChannelInitializer self.childChannelOptions = childChannelOptions } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event is ChannelShouldQuiesceEvent { context.channel.close().whenFailure { error in context.fireErrorCaught(error) } } context.fireUserInboundEventTriggered(event) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { let accepted = self.unwrapInboundIn(data) let ctxEventLoop = context.eventLoop let childEventLoop = accepted.eventLoop let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) } @inline(__always) func setupChildChannel() -> EventLoopFuture<Void> { return self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture<Void> in childEventLoop.assertInEventLoop() return childChannelInit(accepted) } } @inline(__always) func fireThroughPipeline(_ future: EventLoopFuture<Void>) { ctxEventLoop.assertInEventLoop() future.flatMap { (_) -> EventLoopFuture<Void> in ctxEventLoop.assertInEventLoop() guard context.channel.isActive else { return context.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) } context.fireChannelRead(data) return context.eventLoop.makeSucceededFuture(()) }.whenFailure { error in ctxEventLoop.assertInEventLoop() self.closeAndFire(context: context, accepted: accepted, err: error) } } if childEventLoop === ctxEventLoop { fireThroughPipeline(setupChildChannel()) } else { fireThroughPipeline(childEventLoop.flatSubmit { return setupChildChannel() }.hop(to: ctxEventLoop)) } } private func closeAndFire(context: ChannelHandlerContext, accepted: SocketChannel, err: Error) { accepted.close(promise: nil) if context.eventLoop.inEventLoop { context.fireErrorCaught(err) } else { context.eventLoop.execute { context.fireErrorCaught(err) } } } } } #if swift(>=5.6) @available(*, unavailable) extension ServerBootstrap: Sendable {} #endif private extension Channel { func registerAndDoSynchronously(_ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> { // this is pretty delicate at the moment: // In many cases `body` must be _synchronously_ follow `register`, otherwise in our current // implementation, `epoll` will send us `EPOLLHUP`. To have it run synchronously, we need to invoke the // `flatMap` on the eventloop that the `register` will succeed on. self.eventLoop.assertInEventLoop() return self.register().flatMap { self.eventLoop.assertInEventLoop() return body(self) } } } /// A `ClientBootstrap` is an easy way to bootstrap a `SocketChannel` when creating network clients. /// /// Usually you re-use a `ClientBootstrap` once you set it up and called `connect` multiple times on it. /// This way you ensure that the same `EventLoop`s will be shared across all your connections. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = ClientBootstrap(group: group) /// // Enable SO_REUSEADDR. /// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .channelInitializer { channel in /// // always instantiate the handler _within_ the closure as /// // it may be called multiple times (for example if the hostname /// // resolves to both IPv4 and IPv6 addresses, cf. Happy Eyeballs). /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// try! bootstrap.connect(host: "example.org", port: 12345).wait() /// /* the Channel is now connected */ /// ``` /// /// The connected `SocketChannel` will operate on `ByteBuffer` as inbound and on `IOData` as outbound messages. public final class ClientBootstrap: NIOClientTCPBootstrapProtocol { private let group: EventLoopGroup #if swift(>=5.7) private var protocolHandlers: Optional<@Sendable () -> [ChannelHandler]> #else private var protocolHandlers: Optional<() -> [ChannelHandler]> #endif private var _channelInitializer: ChannelInitializerCallback private var channelInitializer: ChannelInitializerCallback { if let protocolHandlers = self.protocolHandlers { let channelInitializer = _channelInitializer return { channel in channelInitializer(channel).flatMap { channel.pipeline.addHandlers(protocolHandlers(), position: .first) } } } else { return self._channelInitializer } } @usableFromInline internal var _channelOptions: ChannelOptions.Storage private var connectTimeout: TimeAmount = TimeAmount.seconds(10) private var resolver: Optional<Resolver> private var bindTarget: Optional<SocketAddress> private var enableMPTCP: Bool /// Create a `ClientBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ClientBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("ClientBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `ClientBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self.group = group self._channelOptions = ChannelOptions.Storage() self._channelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1) self._channelInitializer = { channel in channel.eventLoop.makeSucceededFuture(()) } self.protocolHandlers = nil self.resolver = nil self.bindTarget = nil self.enableMPTCP = false } #if swift(>=5.7) /// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - warning: The `handler` closure may be invoked _multiple times_ so it's usually the right choice to instantiate /// `ChannelHandler`s within `handler`. The reason `handler` may be invoked multiple times is that to /// successfully set up a connection multiple connections might be setup in the process. Assuming a /// hostname that resolves to both IPv4 and IPv6 addresses, NIO will follow /// [_Happy Eyeballs_](https://en.wikipedia.org/wiki/Happy_Eyeballs) and race both an IPv4 and an IPv6 /// connection. It is possible that both connections get fully established before the IPv4 connection /// will be closed again because the IPv6 connection 'won the race'. Therefore the `channelInitializer` /// might be called multiple times and it's important not to share stateful `ChannelHandler`s in more /// than one `Channel`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self._channelInitializer = handler return self } #else /// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages. /// /// - warning: The `handler` closure may be invoked _multiple times_ so it's usually the right choice to instantiate /// `ChannelHandler`s within `handler`. The reason `handler` may be invoked multiple times is that to /// successfully set up a connection multiple connections might be setup in the process. Assuming a /// hostname that resolves to both IPv4 and IPv6 addresses, NIO will follow /// [_Happy Eyeballs_](https://en.wikipedia.org/wiki/Happy_Eyeballs) and race both an IPv4 and an IPv6 /// connection. It is possible that both connections get fully established before the IPv4 connection /// will be closed again because the IPv6 connection 'won the race'. Therefore the `channelInitializer` /// might be called multiple times and it's important not to share stateful `ChannelHandler`s in more /// than one `Channel`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self._channelInitializer = handler return self } #endif #if swift(>=5.7) /// Sets the protocol handlers that will be added to the front of the `ChannelPipeline` right after the /// `channelInitializer` has been called. /// /// Per bootstrap, you can only set the `protocolHandlers` once. Typically, `protocolHandlers` are used for the TLS /// implementation. Most notably, `NIOClientTCPBootstrap`, NIO's "universal bootstrap" abstraction, uses /// `protocolHandlers` to add the required `ChannelHandler`s for many TLS implementations. @preconcurrency public func protocolHandlers(_ handlers: @escaping @Sendable () -> [ChannelHandler]) -> Self { precondition(self.protocolHandlers == nil, "protocol handlers can only be set once") self.protocolHandlers = handlers return self } #else /// Sets the protocol handlers that will be added to the front of the `ChannelPipeline` right after the /// `channelInitializer` has been called. /// /// Per bootstrap, you can only set the `protocolHandlers` once. Typically, `protocolHandlers` are used for the TLS /// implementation. Most notably, `NIOClientTCPBootstrap`, NIO's "universal bootstrap" abstraction, uses /// `protocolHandlers` to add the required `ChannelHandler`s for many TLS implementations. public func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self { precondition(self.protocolHandlers == nil, "protocol handlers can only be set once") self.protocolHandlers = handlers return self } #endif /// Specifies a `ChannelOption` to be applied to the `SocketChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } /// Specifies a timeout to apply to a connection attempt. /// /// - parameters: /// - timeout: The timeout that will apply to the connection attempt. public func connectTimeout(_ timeout: TimeAmount) -> Self { self.connectTimeout = timeout return self } /// Specifies the `Resolver` to use or `nil` if the default should be used. /// /// - parameters: /// - resolver: The resolver that will be used during the connection attempt. public func resolver(_ resolver: Resolver?) -> Self { self.resolver = resolver return self } /// Enables multi-path TCP support. /// /// This option is only supported on some systems, and will lead to bind /// failing if the system does not support it. Users are recommended to /// only enable this in response to configuration or feature detection. /// /// > Note: Enabling this setting will re-enable Nagle's algorithm, even if it /// > had been disabled. This is a temporary workaround for a Linux kernel /// > limitation. /// /// - parameters: /// - value: Whether to enable MPTCP or not. public func enableMPTCP(_ value: Bool) -> Self { self.enableMPTCP = value // This is a temporary workaround until we get some stable Linux kernel // versions that support TCP_NODELAY and MPTCP. if value { self._channelOptions.remove(key: ChannelOptions.tcpOption(.tcp_nodelay)) } return self } /// Bind the `SocketChannel` to `address`. /// /// Using `bind` is not necessary unless you need the local address to be bound to a specific address. /// /// - note: Using `bind` will disable Happy Eyeballs on this `Channel`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> ClientBootstrap { self.bindTarget = address return self } func makeSocketChannel(eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily) throws -> SocketChannel { return try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily, enableMPTCP: self.enableMPTCP) } /// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established. /// /// - parameters: /// - host: The host to connect to. /// - port: The port to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(host: String, port: Int) -> EventLoopFuture<Channel> { let loop = self.group.next() let resolver = self.resolver ?? GetaddrinfoResolver(loop: loop, aiSocktype: .stream, aiProtocol: .tcp) let connector = HappyEyeballsConnector(resolver: resolver, loop: loop, host: host, port: port, connectTimeout: self.connectTimeout) { eventLoop, protocolFamily in return self.initializeAndRegisterNewChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) { $0.eventLoop.makeSucceededFuture(()) } } return connector.resolveAndConnect() } private func connect(freshChannel channel: Channel, address: SocketAddress) -> EventLoopFuture<Void> { let connectPromise = channel.eventLoop.makePromise(of: Void.self) channel.connect(to: address, promise: connectPromise) let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) { connectPromise.fail(ChannelError.connectTimeout(self.connectTimeout)) channel.close(promise: nil) } connectPromise.futureResult.whenComplete { (_: Result<Void, Error>) in cancelTask.cancel() } return connectPromise.futureResult } internal func testOnly_connect(injectedChannel: SocketChannel, to address: SocketAddress) -> EventLoopFuture<Channel> { return self.initializeAndRegisterChannel(injectedChannel) { channel in return self.connect(freshChannel: channel, address: address) } } /// Specify the `address` to connect to for the TCP `Channel` that will be established. /// /// - parameters: /// - address: The address to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { return self.initializeAndRegisterNewChannel(eventLoop: self.group.next(), protocolFamily: address.protocol) { channel in return self.connect(freshChannel: channel, address: address) } } /// Specify the `unixDomainSocket` path to connect to for the UDS `Channel` that will be established. /// /// - parameters: /// - unixDomainSocketPath: The _Unix domain socket_ path to connect to. /// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected. public func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { do { let address = try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) return self.connect(to: address) } catch { return self.group.next().makeFailedFuture(error) } } #if !os(Windows) /// Use the existing connected socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the connected stream socket. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. @available(*, deprecated, renamed: "withConnectedSocket(_:)") public func withConnectedSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return self.withConnectedSocket(descriptor) } #endif /// Use the existing connected socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the connected stream socket. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { let eventLoop = group.next() let channelInitializer = self.channelInitializer let channel: SocketChannel do { channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, socket: socket) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return self._channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } private func initializeAndRegisterNewChannel(eventLoop: EventLoop, protocolFamily: NIOBSDSocket.ProtocolFamily, _ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let channel: SocketChannel do { channel = try self.makeSocketChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) } catch { return eventLoop.makeFailedFuture(error) } return self.initializeAndRegisterChannel(channel, body) } private func initializeAndRegisterChannel(_ channel: SocketChannel, _ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let channelInitializer = self.channelInitializer let channelOptions = self._channelOptions let eventLoop = channel.eventLoop @inline(__always) func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { if let bindTarget = self.bindTarget { return channel.bind(to: bindTarget).flatMap { channelInitializer(channel) } } else { return channelInitializer(channel) } }.flatMap { eventLoop.assertInEventLoop() return channel.registerAndDoSynchronously(body) }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension ClientBootstrap: Sendable {} #endif /// A `DatagramBootstrap` is an easy way to bootstrap a `DatagramChannel` when creating datagram clients /// and servers. /// /// Example: /// /// ```swift /// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) /// defer { /// try! group.syncShutdownGracefully() /// } /// let bootstrap = DatagramBootstrap(group: group) /// // Enable SO_REUSEADDR. /// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) /// .channelInitializer { channel in /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// let channel = try! bootstrap.bind(host: "127.0.0.1", port: 53).wait() /// /* the Channel is now ready to send/receive datagrams */ /// /// try channel.closeFuture.wait() // Wait until the channel un-binds. /// ``` /// /// The `DatagramChannel` will operate on `AddressedEnvelope<ByteBuffer>` as inbound and outbound messages. public final class DatagramBootstrap { private let group: EventLoopGroup private var channelInitializer: Optional<ChannelInitializerCallback> @usableFromInline internal var _channelOptions: ChannelOptions.Storage /// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `DatagramBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("DatagramBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self._channelOptions = ChannelOptions.Storage() self.group = group self.channelInitializer = nil } #if swift(>=5.7) /// Initialize the bound `DatagramChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #else /// Initialize the bound `DatagramChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #endif /// Specifies a `ChannelOption` to be applied to the `DatagramChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } #if !os(Windows) /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound datagram socket. @available(*, deprecated, renamed: "withBoundSocket(_:)") public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> { return self.withBoundSocket(descriptor) } #endif /// Use the existing bound socket file descriptor. /// /// - parameters: /// - descriptor: The _Unix file descriptor_ representing the bound datagram socket. public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> { func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, socket: socket) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult } } /// Bind the `DatagramChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to bind on. /// - port: The port to bind on. public func bind(host: String, port: Int) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Bind the `DatagramChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to bind on. public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> { return bind0 { address } } /// Bind the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system. public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return bind0 { return try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } /// Bind the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system. /// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`. public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> { if cleanupExistingSocketFile { do { try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath) } catch { return group.next().makeFailedFuture(error) } } return self.bind(unixDomainSocketPath: unixDomainSocketPath) } private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, protocolFamily: address.protocol, protocolSubtype: .default) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in channel.register().flatMap { channel.bind(to: address) } } } /// Connect the `DatagramChannel` to `host` and `port`. /// /// - parameters: /// - host: The host to connect to. /// - port: The port to connect to. public func connect(host: String, port: Int) -> EventLoopFuture<Channel> { return connect0 { return try SocketAddress.makeAddressResolvingHost(host, port: port) } } /// Connect the `DatagramChannel` to `address`. /// /// - parameters: /// - address: The `SocketAddress` to connect to. public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> { return connect0 { address } } /// Connect the `DatagramChannel` to a UNIX Domain Socket. /// /// - parameters: /// - unixDomainSocketPath: The path of the UNIX Domain Socket to connect to. `path` must not exist, it will be created by the system. public func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> { return connect0 { return try SocketAddress(unixDomainSocketPath: unixDomainSocketPath) } } private func connect0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> { let address: SocketAddress do { address = try makeSocketAddress() } catch { return group.next().makeFailedFuture(error) } func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel { return try DatagramChannel(eventLoop: eventLoop, protocolFamily: address.protocol, protocolSubtype: .default) } return withNewChannel(makeChannel: makeChannel) { (eventLoop, channel) in channel.register().flatMap { channel.connect(to: address) } } } private func withNewChannel(makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, _ bringup: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> { let eventLoop = self.group.next() let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } let channelOptions = self._channelOptions let channel: DatagramChannel do { channel = try makeChannel(eventLoop as! SelectableEventLoop) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() return bringup(eventLoop, channel) }.map { channel }.flatMapError { error in eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension DatagramBootstrap: Sendable {} #endif /// A `NIOPipeBootstrap` is an easy way to bootstrap a `PipeChannel` which uses two (uni-directional) UNIX pipes /// and makes a `Channel` out of them. /// /// Example bootstrapping a `Channel` using `stdin` and `stdout`: /// /// let channel = try NIOPipeBootstrap(group: group) /// .channelInitializer { channel in /// channel.pipeline.addHandler(MyChannelHandler()) /// } /// .withPipes(inputDescriptor: STDIN_FILENO, outputDescriptor: STDOUT_FILENO) /// public final class NIOPipeBootstrap { private let group: EventLoopGroup private var channelInitializer: Optional<ChannelInitializerCallback> @usableFromInline internal var _channelOptions: ChannelOptions.Storage /// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`. /// /// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `NIOPipeBootstrap` is /// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by /// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for /// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public convenience init(group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { preconditionFailure("NIOPipeBootstrap is only compatible with MultiThreadedEventLoopGroup and " + "SelectableEventLoop. You tried constructing one with \(group) which is incompatible.") } self.init(validatingGroup: group)! } /// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible. /// /// - parameters: /// - group: The `EventLoopGroup` to use. public init?(validatingGroup group: EventLoopGroup) { guard NIOOnSocketsBootstraps.isCompatible(group: group) else { return nil } self._channelOptions = ChannelOptions.Storage() self.group = group self.channelInitializer = nil } #if swift(>=5.7) /// Initialize the connected `PipeChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and outbound messages. Please note that /// `IOData.fileRegion` is _not_ supported for `PipeChannel`s because `sendfile` only works on sockets. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. @preconcurrency public func channelInitializer(_ handler: @escaping @Sendable (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #else /// Initialize the connected `PipeChannel` with `initializer`. The most common task in initializer is to add /// `ChannelHandler`s to the `ChannelPipeline`. /// /// The connected `Channel` will operate on `ByteBuffer` as inbound and outbound messages. Please note that /// `IOData.fileRegion` is _not_ supported for `PipeChannel`s because `sendfile` only works on sockets. /// /// - parameters: /// - handler: A closure that initializes the provided `Channel`. public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self { self.channelInitializer = handler return self } #endif /// Specifies a `ChannelOption` to be applied to the `PipeChannel`. /// /// - parameters: /// - option: The option to be applied. /// - value: The value for the option. @inlinable public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self { self._channelOptions.append(key: option, value: value) return self } private func validateFileDescriptorIsNotAFile(_ descriptor: CInt) throws { #if os(Windows) // NOTE: this is a *non-owning* handle, do *NOT* call `CloseHandle` let hFile: HANDLE = HANDLE(bitPattern: _get_osfhandle(descriptor))! if hFile == INVALID_HANDLE_VALUE { throw IOError(errnoCode: EBADF, reason: "_get_osfhandle") } // The check here is different from other platforms as the file types on // Windows are different. SOCKETs and files are different domains, and // as a result we know that the descriptor is not a socket. The only // other type of file it could be is either character or disk, neither // of which support the operations here. switch GetFileType(hFile) { case DWORD(FILE_TYPE_PIPE): break default: throw ChannelError.operationUnsupported } #else var s: stat = .init() try withUnsafeMutablePointer(to: &s) { ptr in try Posix.fstat(descriptor: descriptor, outStat: ptr) } switch s.st_mode & S_IFMT { case S_IFREG, S_IFDIR, S_IFLNK, S_IFBLK: throw ChannelError.operationUnsupported default: () // Let's default to ok } #endif } /// Create the `PipeChannel` with the provided file descriptor which is used for both input & output. /// /// This method is useful for specialilsed use-cases where you want to use `NIOPipeBootstrap` for say a serial line. /// /// - note: If this method returns a succeeded future, SwiftNIO will close `fileDescriptor` when the `Channel` /// becomes inactive. You _must not_ do any further operations with `fileDescriptor`, including `close`. /// If this method returns a failed future, you still own the file descriptor and are responsible for /// closing it. /// /// - parameters: /// - fileDescriptor: The _Unix file descriptor_ for the input & output. /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withInputOutputDescriptor(_ fileDescriptor: CInt) -> EventLoopFuture<Channel> { let inputFD = fileDescriptor let outputFD = try! Posix.dup(descriptor: fileDescriptor) return self.withPipes(inputDescriptor: inputFD, outputDescriptor: outputFD).flatMapErrorThrowing { error in try! Posix.close(descriptor: outputFD) throw error } } /// Create the `PipeChannel` with the provided input and output file descriptors. /// /// The input and output file descriptors must be distinct. If you have a single file descriptor, consider using /// `ClientBootstrap.withConnectedSocket(descriptor:)` if it's a socket or /// `NIOPipeBootstrap.withInputOutputDescriptor` if it is not a socket. /// /// - note: If this method returns a succeeded future, SwiftNIO will close `inputDescriptor` and `outputDescriptor` /// when the `Channel` becomes inactive. You _must not_ do any further operations `inputDescriptor` or /// `outputDescriptor`, including `close`. /// If this method returns a failed future, you still own the file descriptors and are responsible for /// closing them. /// /// - parameters: /// - inputDescriptor: The _Unix file descriptor_ for the input (ie. the read side). /// - outputDescriptor: The _Unix file descriptor_ for the output (ie. the write side). /// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`. public func withPipes(inputDescriptor: CInt, outputDescriptor: CInt) -> EventLoopFuture<Channel> { precondition(inputDescriptor >= 0 && outputDescriptor >= 0 && inputDescriptor != outputDescriptor, "illegal file descriptor pair. The file descriptors \(inputDescriptor), \(outputDescriptor) " + "must be distinct and both positive integers.") let eventLoop = group.next() do { try self.validateFileDescriptorIsNotAFile(inputDescriptor) try self.validateFileDescriptorIsNotAFile(outputDescriptor) } catch { return eventLoop.makeFailedFuture(error) } let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) } let channel: PipeChannel do { let inputFH = NIOFileHandle(descriptor: inputDescriptor) let outputFH = NIOFileHandle(descriptor: outputDescriptor) channel = try PipeChannel(eventLoop: eventLoop as! SelectableEventLoop, inputPipe: inputFH, outputPipe: outputFH) } catch { return eventLoop.makeFailedFuture(error) } func setupChannel() -> EventLoopFuture<Channel> { eventLoop.assertInEventLoop() return self._channelOptions.applyAllChannelOptions(to: channel).flatMap { channelInitializer(channel) }.flatMap { eventLoop.assertInEventLoop() let promise = eventLoop.makePromise(of: Void.self) channel.registerAlreadyConfigured0(promise: promise) return promise.futureResult }.map { channel }.flatMapError { error in channel.close0(error: error, mode: .all, promise: nil) return channel.eventLoop.makeFailedFuture(error) } } if eventLoop.inEventLoop { return setupChannel() } else { return eventLoop.flatSubmit { setupChannel() } } } } #if swift(>=5.6) @available(*, unavailable) extension NIOPipeBootstrap: Sendable {} #endif
6a008d908b8eedfcad357a1cb9df9a7a
44.379729
269
0.637825
false
false
false
false
xuech/OMS-WH
refs/heads/master
OMS-WH/Classes/TakeOrder/线下处理/View/OMSPlaceholdTextView.swift
mit
1
// // OMSPlaceholdTextView.swift // OMS-WH // // Created by xuech on 2017/10/26. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class OMSPlaceholdTextView: UITextView { fileprivate let placeholderLeftMargin: CGFloat = 4.0 fileprivate let placeholderTopMargin: CGFloat = 8.0 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setup() } convenience init() { self.init(frame: CGRect.zero, textContainer: nil) } convenience init(frame: CGRect) { self.init(frame: frame, textContainer: nil) } deinit { NotificationCenter.default.removeObserver(self) } public override func awakeFromNib() { super.awakeFromNib() setup() } fileprivate func setup() { contentInset = UIEdgeInsetsMake(0, 0, 0, 0); font = UIFont.systemFont(ofSize: 12.0) placeholderLabel.font = self.font placeholderLabel.textColor = placeholderColor placeholderLabel.text = placeholder placeholderSizeToFit() addSubview(placeholderLabel) self.sendSubview(toBack: placeholderLabel) let center = NotificationCenter.default center.addObserver(self, selector: #selector(OMSPlaceholdTextView.textChanged(_:)), name: .UITextViewTextDidChange, object: nil) textChanged(nil) } @objc func textChanged(_ notification:Notification?) { placeholderLabel.alpha = self.text.isEmpty ? 1.0 : 0.0 } lazy var placeholderLabel: UILabel = { let label = UILabel() label.lineBreakMode = NSLineBreakMode.byWordWrapping label.numberOfLines = 0 label.backgroundColor = UIColor.clear label.alpha = 1.0 return label }() ///占位文字的颜色 public var placeholderColor: UIColor = UIColor.lightGray { didSet { placeholderLabel.textColor = placeholderColor } } ///占位文字 public var placeholder: String = "" { didSet { placeholderLabel.text = placeholder placeholderSizeToFit() } } override public var text: String! { didSet { textChanged(nil) } } override public var font: UIFont? { didSet { placeholderLabel.font = font placeholderSizeToFit() } } } extension OMSPlaceholdTextView { fileprivate func placeholderSizeToFit() { placeholderLabel.frame = CGRect(x: placeholderLeftMargin, y: placeholderTopMargin, width: frame.width - placeholderLeftMargin * 2, height: 0.0) placeholderLabel.sizeToFit() } }
a7d7e718d1867f1592e81cd52dadf1e4
25.071429
151
0.611986
false
false
false
false
Where2Go/swiftsina
refs/heads/master
GZWeibo05/Class/Tool/CZNetworkTools.swift
apache-2.0
2
// // CZNetworkTools.swift // GZWeibo05 // // Created by zhangping on 15/10/28. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit import AFNetworking // MARK: - 网络错误枚举 enum CZNetworkError: Int { case emptyToken = -1 case emptyUid = -2 // 枚举里面可以有属性 var description: String { get { // 根据枚举的类型返回对应的错误 switch self { case CZNetworkError.emptyToken: return "accecc token 为空" case CZNetworkError.emptyUid: return "uid 为空" } } } // 枚举可以定义方法 func error() -> NSError { return NSError(domain: "cn.itcast.error.network", code: rawValue, userInfo: ["errorDescription" : description]) } } class CZNetworkTools: NSObject { // 属性 private var afnManager: AFHTTPSessionManager // 创建单例 static let sharedInstance: CZNetworkTools = CZNetworkTools() override init() { let urlString = "https://api.weibo.com/" afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString)) afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain") } // 创建单例 // static let sharedInstance: CZNetworkTools = { // let urlString = "https://api.weibo.com/" // // let tool = CZNetworkTools(baseURL: NSURL(string: urlString)) //// Set // tool.responseSerializer.acceptableContentTypes?.insert("text/plain") // // return tool // }() // MARK: - OAtuh授权 /// 申请应用时分配的AppKey private let client_id = "3769988269" /// 申请应用时分配的AppSecret private let client_secret = "8c30d1e7d3754eca9076689b91531c6a" /// 请求的类型,填写authorization_code private let grant_type = "authorization_code" /// 回调地址 let redirect_uri = "http://www.baidu.com/" // OAtuhURL地址 func oauthRUL() -> NSURL { let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)" return NSURL(string: urlString)! } // 使用闭包回调 // MARK: - 加载AccessToken /// 加载AccessToken func loadAccessToken(code: String, finshed: NetworkFinishedCallback) { // url let urlString = "oauth2/access_token" // NSObject // AnyObject, 任何 class // 参数 let parameters = [ "client_id": client_id, "client_secret": client_secret, "grant_type": grant_type, "code": code, "redirect_uri": redirect_uri ] // 测试返回结果类型 // responseSerializer = AFHTTPResponseSerializer() // result: 请求结果 afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in // let data = String(data: result as! NSData, encoding: NSUTF8StringEncoding) // print("data: \(data)") finshed(result: result as? [String: AnyObject], error: nil) }) { (_, error: NSError) -> Void in finshed(result: nil, error: error) } } // MARK: - 获取用户信息 func loadUserInfo(finshed: NetworkFinishedCallback) { // 守卫,和可选绑定相反 // parameters 代码块里面和外面都能使用 guard var parameters = tokenDict() else { // 能到这里来表示 parameters 没有值 print("没有accessToken") let error = CZNetworkError.emptyToken.error() // 告诉调用者 finshed(result: nil, error: error) return } // 判断uid if CZUserAccount.loadAccount()?.uid == nil { print("没有uid") let error = CZNetworkError.emptyUid.error() // 告诉调用者 finshed(result: nil, error: error) return } // url let urlString = "https://api.weibo.com/2/users/show.json" // 添加元素 parameters["uid"] = CZUserAccount.loadAccount()!.uid! requestGET(urlString, parameters: parameters, finshed: finshed) } /// 判断access token是否有值,没有值返回nil,如果有值生成一个字典 func tokenDict() -> [String: AnyObject]? { if CZUserAccount.loadAccount()?.access_token == nil { return nil } return ["access_token": CZUserAccount.loadAccount()!.access_token!] } // MARK: - 获取微博数据 /** 加载微博数据 - parameter since_id: 若指定此参数,则返回ID比since_id大的微博,默认为0 - parameter max_id: 若指定此参数,则返回ID小于或等于max_id的微博,默认为0 - parameter finished: 回调 */ func loadStatus(since_id: Int, max_id: Int, finished: NetworkFinishedCallback) { guard var parameters = tokenDict() else { // 能到这里来说明token没有值 // 告诉调用者 finished(result: nil, error: CZNetworkError.emptyToken.error()) return } // 添加参数 since_id和max_id // 判断是否有传since_id,max_id if since_id > 0 { parameters["since_id"] = since_id } else if max_id > 0 { parameters["max_id"] = max_id - 1 } // access token 有值 let urlString = "2/statuses/home_timeline.json" // 网络不给力,加载本地数据 if true { requestGET(urlString, parameters: parameters, finshed: finished) } else { loadLocalStatus(finished) } } /// 加载本地微博数据 private func loadLocalStatus(finished: NetworkFinishedCallback) { // 获取路径 let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json") // 加载文件数据 let data = NSData(contentsOfFile: path!) // 转成json do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) // 有数据 finished(result: json as? [String : AnyObject], error: nil) } catch { // 如果do里面的代码出错了,不会崩溃,会走这里 print("出异常了") } // 强制try 如果这句代码有错误,程序立即停止运行 // let statusesJson = try! NSJSONSerialization.JSONObjectWithData(nsData, options: NSJSONReadingOptions(rawValue: 0)) } // MARK: - 发布微博 /** 发布微博 - parameter image: 微博图片,可能有可能没有 - parameter status: 微博文本内容 - parameter finished: 回调闭包 */ func sendStatus(image: UIImage?, status: String, finished: NetworkFinishedCallback) { // 判断token guard var parameters = tokenDict() else { // 能到这里来说明token没有值 // 告诉调用者 finished(result: nil, error: CZNetworkError.emptyToken.error()) return } // token有值, 拼接参数 parameters["status"] = status // 判断是否有图片 if let im = image { // 有图片,发送带图片的微博 let urlString = "https://upload.api.weibo.com/2/statuses/upload.json" afnManager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in let data = UIImagePNGRepresentation(im)! // data: 上传图片的2进制 // name: api 上面写的传递参数名称 "pic" // fileName: 上传到服务器后,保存的名称,没有指定可以随便写 // mimeType: 资源类型: // image/png // image/jpeg // image/gif formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png") }, success: { (_, result) -> Void in finished(result: result as? [String: AnyObject], error: nil) }, failure: { (_, error) -> Void in finished(result: nil, error: error) }) } else { // url let urlString = "2/statuses/update.json" // 没有图片 afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in finished(result: result as? [String: AnyObject], error: nil) }) { (_, error) -> Void in finished(result: nil, error: error) } } } // 类型别名 = typedefined typealias NetworkFinishedCallback = (result: [String: AnyObject]?, error: NSError?) -> () // MARK: - 封装AFN.GET func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) { afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in finshed(result: result as? [String: AnyObject], error: nil) }) { (_, error) -> Void in finshed(result: nil, error: error) } } }
e8a1c514b448c872dfeba17d95ceee36
30.255396
125
0.54264
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TargetSelectionPage/Models/TargetSelectionPageSectionModel.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxDataSources enum TargetSelectionPageSectionModel { case source(header: TargetSelectionHeaderBuilder, items: [Item]) case destination(header: TargetSelectionHeaderBuilder, items: [Item]) } extension TargetSelectionPageSectionModel: AnimatableSectionModelType { typealias Item = TargetSelectionPageCellItem var items: [Item] { switch self { case .source(_, let items): return items case .destination(_, let items): return items } } var header: TargetSelectionHeaderBuilder { switch self { case .source(let header, _): return header case .destination(let header, _): return header } } var identity: String { switch self { case .source(let header, _), .destination(let header, _): return header.headerType.id } } init(original: TargetSelectionPageSectionModel, items: [Item]) { switch original { case .source(let header, _): self = .source(header: header, items: items) case .destination(let header, _): self = .destination(header: header, items: items) } } } extension TargetSelectionPageSectionModel: Equatable { static func == (lhs: TargetSelectionPageSectionModel, rhs: TargetSelectionPageSectionModel) -> Bool { switch (lhs, rhs) { case (.source(header: _, items: let left), .source(header: _, items: let right)): return left == right case (.destination(header: _, items: let left), .destination(header: _, items: let right)): return left == right default: return false } } }
e547c6936bfe67c071bf67ffada657f8
29.033333
105
0.606548
false
false
false
false
acalvomartinez/RandomUser
refs/heads/master
RandomUser/APIClientError.swift
apache-2.0
1
// // APIClientError.swift // RandomUser // // Created by Antonio Calvo on 29/06/2017. // Copyright © 2017 Antonio Calvo. All rights reserved. // import Foundation import Result enum APIClientError: Error { case networkError case couldNotDecodeJSON case badStatus(status: Int) case internalServerDrama case unknown(error: Error) } extension APIClientError: Equatable { static func ==(lhs: APIClientError, rhs: APIClientError) -> Bool { return (lhs._domain == rhs._domain) && (lhs._code == rhs._code) } } extension APIClientError { static func build(error: Error) -> APIClientError { switch error._code { case 500: return .internalServerDrama case NSURLErrorNetworkConnectionLost: return .networkError default: return .unknown(error: error) } } }
2316ae1912657d87ca8298ea26f0d522
21
68
0.69656
false
false
false
false
proxpero/Matasano
refs/heads/master
Matasano/Conversions.swift
mit
1
// // Conversions.swift // Cryptopals // // Created by Todd Olsen on 2/13/16. // Copyright © 2016 Todd Olsen. All rights reserved. // import Foundation private let base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".characters.map { String($0) } extension String { /// returns an Unicode code point public var unicodeScalarCodePoint: UInt32 { let scalars = self.unicodeScalars return scalars[scalars.startIndex].value } /// converts a string of ascii text and /// returns an array of bytes /// - precondition: `self` is ascii text (0..<128) public var asciiToBytes: [UInt8] { return unicodeScalars.map { UInt8(ascii: $0) } } /// returns an array of bytes /// - precondition: `self` is hexadecimal text public var hexToBytes: [UInt8] { var items = lowercaseString.characters.map { String($0) } var bytes = [UInt8]() for i in items.startIndex.stride(to: items.endIndex, by: 2) { guard let byte = UInt8(items[i] + (i+1==items.endIndex ? "" : items[i+1]), radix: 16) else { fatalError() } bytes.append(byte) } return bytes } /// returns an array of bytes /// - precondition: `self` is base-64 text public var base64ToBytes: [UInt8] { return characters.map { String($0) }.filter { $0 != "=" }.map { UInt8(base64Chars.indexOf($0)!) }.sextetArrayToBytes } public var asciiToBase64: String { return self.asciiToBytes.base64Representation } public var base64ToAscii: String { return self.base64ToBytes.asciiRepresentation } public var hexToBase64: String { return self.hexToBytes.base64Representation } public var base64ToHex: String { return self.hexToBytes.hexRepresentation } } extension CollectionType where Generator.Element == UInt8, Index == Int { /// return the ascii representation of `self` /// complexity: O(N) public var asciiRepresentation: String { if let result = String(bytes: self, encoding: NSUTF8StringEncoding) { return result } return String(bytes: self, encoding: NSUnicodeStringEncoding)! } /// returns the hexidecimal representation of `self` /// complexity: O(N) public var hexRepresentation: String { var output = "" for byte in self { output += String(byte, radix: 16) } return output } /// returns the base64 representation of `self` /// complexity: O(N) public var base64Representation: String { var output = "" for sixbitInt in (self.bytesToSextetArray.map { Int($0) }) { output += base64Chars[sixbitInt] } while output.characters.count % 4 != 0 { output += "=" } return output } /// private var bytesToSextetArray: [UInt8] { var sixes = [UInt8]() for i in startIndex.stride(to: endIndex, by: 3) { sixes.append(self[i] >> 2) // if there are two missing characters, pad the result with '==' guard i+1 < endIndex else { sixes.appendContentsOf([(self[i] << 6) >> 2]) return sixes } sixes.append((self[i] << 6) >> 2 | self[i+1] >> 4) // if there is one missing character, pad the result with '=' guard i+2 < endIndex else { sixes.append((self[i+1] << 4) >> 2) return sixes } sixes.append((self[i+1] << 4) >> 2 | self[i+2] >> 6) sixes.append((self[i+2] << 2) >> 2) } return sixes } private var sextetArrayToBytes: [UInt8] { var bytes: [UInt8] = [] for i in startIndex.stride(to: endIndex, by: 4) { bytes.append(self[i+0]<<2 | self[i+1]>>4) guard i+2 < endIndex else { return bytes } bytes.append(self[i+1]<<4 | self[i+2]>>2) guard i+3 < endIndex else { return bytes } bytes.append(self[i+2]<<6 | self[i+3]>>0) } return bytes } } // MARK: TESTS func testConversions() { let hobbes = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure." func testUnicodeScalarCodePoint() { assert(" ".unicodeScalarCodePoint == UInt32(32)) // lower bound assert("0".unicodeScalarCodePoint == UInt32(48)) assert("C".unicodeScalarCodePoint == UInt32(67)) assert("a".unicodeScalarCodePoint == UInt32(97)) assert("t".unicodeScalarCodePoint == UInt32(116)) assert("~".unicodeScalarCodePoint == UInt32(126)) // upper bound print("\(#function) passed.") } func testAsciiConversions() { let bytes = [UInt8(77), UInt8(97), UInt8(110)] let text = "Man" assert(text.asciiToBytes == bytes) assert(bytes.asciiRepresentation == text) assert(hobbes.asciiToBytes.asciiRepresentation == hobbes) print("\(#function) passed.") } func testHexConversions() { let text = "deadbeef" assert(text.hexToBytes.hexRepresentation == text) let t1 = "f79" assert(t1.hexToBytes.hexRepresentation == t1) print("\(#function) passed.") } func testBase64Conversions() { let sixes: [UInt8] = [19, 22, 5, 46] let eights: [UInt8] = [77, 97, 110] assert(sixes.sextetArrayToBytes == eights) assert(eights.bytesToSextetArray == sixes) let t1 = "Man" let e1 = "TWFu" assert(t1.asciiToBytes.base64Representation == e1) assert(e1.base64ToBytes.asciiRepresentation == t1) assert(t1.asciiToBase64 == e1) assert(e1.base64ToAscii == t1) assert(t1.asciiToBytes == e1.base64ToBytes) let t2 = "any carnal pleasure." let e2 = "YW55IGNhcm5hbCBwbGVhc3VyZS4=" assert(t2.asciiToBytes.base64Representation == e2) assert(e2.base64ToBytes.asciiRepresentation == t2) assert(t2.asciiToBase64 == e2) assert(e2.base64ToAscii == t2) assert(t2.asciiToBytes == e2.base64ToBytes) let t3 = "any carnal pleasure" let e3 = "YW55IGNhcm5hbCBwbGVhc3VyZQ==" assert(t3.asciiToBytes.base64Representation == e3) assert(e3.base64ToBytes.asciiRepresentation == t3) assert(t3.asciiToBase64 == e3) assert(e3.base64ToAscii == t3) assert(t3.asciiToBytes == e3.base64ToBytes) let t4 = "any carnal pleasur" let e4 = "YW55IGNhcm5hbCBwbGVhc3Vy" assert(t4.asciiToBytes.base64Representation == e4) assert(e4.base64ToBytes.asciiRepresentation == t4) assert(t4.asciiToBase64 == e4) assert(e4.base64ToAscii == t4) assert(t4.asciiToBytes == e4.base64ToBytes) let t5 = "any carnal pleasu" let e5 = "YW55IGNhcm5hbCBwbGVhc3U=" assert(t5.asciiToBytes.base64Representation == e5) assert(e5.base64ToBytes.asciiRepresentation == t5) assert(t5.asciiToBase64 == e5) assert(e5.base64ToAscii == t5) assert(t5.asciiToBytes == e5.base64ToBytes) let t6 = "any carnal pleas" let e6 = "YW55IGNhcm5hbCBwbGVhcw==" assert(t6.asciiToBytes.base64Representation == e6) assert(e6.base64ToBytes.asciiRepresentation == t6) assert(t6.asciiToBase64 == e6) assert(e6.base64ToAscii == t6) assert(t6.asciiToBytes == e6.base64ToBytes) let t7 = "pleasure." let e7 = "cGxlYXN1cmUu" assert(t7.asciiToBytes.base64Representation == e7) assert(e7.base64ToBytes.asciiRepresentation == t7) assert(t7.asciiToBase64 == e7) assert(e7.base64ToAscii == t7) assert(t7.asciiToBytes == e7.base64ToBytes) let t8 = "leasure." let e8 = "bGVhc3VyZS4=" assert(t8.asciiToBytes.base64Representation == e8) assert(e8.base64ToBytes.asciiRepresentation == t8) assert(t8.asciiToBase64 == e8) assert(e8.base64ToAscii == t8) assert(t8.asciiToBytes == e8.base64ToBytes) let t9 = "easure." let e9 = "ZWFzdXJlLg==" assert(t9.asciiToBytes.base64Representation == e9) assert(e9.base64ToBytes.asciiRepresentation == t9) assert(t9.asciiToBase64 == e9) assert(e9.base64ToAscii == t9) assert(t9.asciiToBytes == e9.base64ToBytes) let t10 = "asure." let e10 = "YXN1cmUu" assert(t10.asciiToBytes.base64Representation == e10) assert(e10.base64ToBytes.asciiRepresentation == t10) assert(t10.asciiToBase64 == e10) assert(e10.base64ToAscii == t10) assert(t10.asciiToBytes == e10.base64ToBytes) let t11 = "sure." let e11 = "c3VyZS4=" assert(t11.asciiToBytes.base64Representation == e11) assert(e11.base64ToBytes.asciiRepresentation == t11) assert(t11.asciiToBase64 == e11) assert(e11.base64ToAscii == t11) assert(t11.asciiToBytes == e11.base64ToBytes) let encoded = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" assert(hobbes.asciiToBytes.base64Representation == encoded) assert(hobbes.asciiToBase64 == encoded) let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" assert(input.hexToBytes.base64Representation == output) assert(input.hexToBase64 == output) print("\(#function) passed.") } testUnicodeScalarCodePoint() testAsciiConversions() testHexConversions() testBase64Conversions() print("\(#function) passed.") }
27a0b92a3470e762f630332b4755f677
32.501558
384
0.60173
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Controllers/Payments/View/ReceiptLineView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 final class ReceiptLineView: UIStackView { private lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.font = Theme.preferredRegular() titleLabel.textColor = Theme.lightGreyTextColor titleLabel.adjustsFontForContentSizeCategory = true return titleLabel }() private lazy var amountLabel: UILabel = { let amountLabel = UILabel() amountLabel.numberOfLines = 0 amountLabel.font = Theme.preferredRegular() amountLabel.textColor = Theme.darkTextColor amountLabel.adjustsFontForContentSizeCategory = true amountLabel.textAlignment = .right return amountLabel }() override init(frame: CGRect) { super.init(frame: frame) axis = .horizontal addArrangedSubview(titleLabel) addArrangedSubview(amountLabel) amountLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTitle(_ title: String) { titleLabel.text = title } func setValue(_ value: String) { amountLabel.text = value } }
c8f086b3882262cbe73999e86217f02d
30.444444
91
0.69258
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
File Management/Saving Objects to File/Saving Objects to File/Person.swift
mit
1
// // Person.swift // Saving Objects to File // // Created by Domenico on 27/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import Foundation class Person: NSObject, NSCoding{ public func encode(with aCoder: NSCoder) { } var firstName: String var lastName: String struct SerializationKey{ static let firstName = "firstName" static let lastName = "lastName" } init(firstName: String, lastName: String){ self.firstName = firstName self.lastName = lastName super.init() } convenience override init(){ self.init(firstName: "Vandad", lastName: "Nahavandipoor") } required init(coder aDecoder: NSCoder) { self.firstName = aDecoder.decodeObject(forKey: SerializationKey.firstName) as! String self.lastName = aDecoder.decodeObject(forKey: SerializationKey.lastName) as! String } func encodewithWithCoder(_ aCoder: NSCoder) { aCoder.encode(self.firstName, forKey: SerializationKey.firstName) aCoder.encode(self.lastName, forKey: SerializationKey.lastName) } } func == (lhs: Person, rhs: Person) -> Bool{ return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName ? true : false }
8a75c86e0ef1b1271fcfca71d57cfbd5
24.5
82
0.631222
false
false
false
false
mzp/OctoEye
refs/heads/master
Tests/Unit/Store/JsonCacheSpec.swift
mit
1
// // JsonCacheSpec.swift // Tests // // Created by mzp on 2017/09/03. // Copyright © 2017 mzp. All rights reserved. // import Nimble import Quick // swiftlint:disable function_body_length, force_try internal class JsonCacheSpec: QuickSpec { override func spec() { var cache: JsonCache<String>! describe("save and fetch") { beforeEach { JsonCache<String>.clearAll() cache = JsonCache<String>(name: "quick") } it("store root entries") { try! cache.store(parent: [], entries: [ "tmp": "temp dir", "etc": "etc dir" ]) expect(cache[["tmp"]]) == "temp dir" expect(cache[["etc"]]) == "etc dir" } it("store sub entries") { try! cache.store(parent: [], entries: [ "tmp": "temp dir" ]) try! cache.store(parent: ["tmp"], entries: [ "a": "file a" ]) expect(cache[["tmp", "a"]]) == "file a" } it("store sub sub entries") { try! cache.store(parent: ["tmp"], entries: [ "a": "file a" ]) expect(cache[["tmp", "a"]]) == "file a" } } } }
c24f7b9af8c2f88048d20f92a1e14dc5
25.711538
60
0.421886
false
false
false
false
WenkyYuan/SwiftDemo
refs/heads/master
SwiftDemo/Controllers/ViewController.swift
mit
1
// // ViewController.swift // SwiftDemo // // Created by wenky on 15/11/19. // Copyright (c) 2015年 wenky. All rights reserved. // import UIKit class ViewController: UIViewController, CustomTableViewCellDelegate { @IBOutlet weak var tableView: UITableView! var tableData = [String]() //定义一个存放String类型元素的数组,并初始化 let kCustomTableViewCell = "CustomTableViewCell" deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() title = "Swift" setup() observeNotification() } //MARK: private methods func setup() { tableView.registerNib(UINib(nibName: kCustomTableViewCell, bundle: nil), forCellReuseIdentifier: kCustomTableViewCell) } func observeNotification() { NSNotificationCenter.defaultCenter().addObserver(self, selector:"didReceiveNotifiction:", name: "kNotificationName", object: nil) } func didReceiveNotifiction(notifiction: NSNotification) { NSLog("didReceiveNotifiction") //TODO:someting let alert: UIAlertView = UIAlertView(title: "提示", message: "收到通知", delegate: nil, cancelButtonTitle: "确定") alert.show() } //MARK: UITableViewDataSource & UITableViewDelegate func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:CustomTableViewCell! = tableView.dequeueReusableCellWithIdentifier(kCustomTableViewCell, forIndexPath: indexPath) as! CustomTableViewCell cell.leftTitleLabel.text = NSString(format: "%zd.2015.11.13巴黎发生暴恐", indexPath.row) as String cell.iconImageView.image = UIImage(named: "neighbourhood_carpooling") cell.delegate = self cell.tapBlock = { (cell: CustomTableViewCell) ->Void in NSLog("tapBlock%zd", cell.tag) } cell.tag = indexPath.row return cell; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView .deselectRowAtIndexPath(indexPath, animated: true) let vc = NextViewController(nibName: "NextViewController", bundle: nil) vc.bgColor = UIColor.purpleColor() navigationController?.pushViewController(vc, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.min } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.min } //MARK: CustomTableViewCellDelegate func customTableViewCellDidTapIamgeView(cell: CustomTableViewCell) { NSLog("didTapImageViewAtIndex:%zd", cell.tag) } }
34e3485349911bf68fa333953d5f2107
33.077778
154
0.678187
false
false
false
false
0xPr0xy/CoreML
refs/heads/master
ARScanner/Vision/Vision.swift
mit
1
import UIKit import Vision import CoreMedia import AVFoundation typealias Prediction = (String, Double) final class Vision { private let model = MobileNet() private let semaphore = DispatchSemaphore(value: 2) private var camera: Camera! private var request: VNCoreMLRequest! private var startTimes: [CFTimeInterval] = [] private var framesDone = 0 private var frameCapturingStartTime = CACurrentMediaTime() public weak var delegate: VisionOutput? init() { self.setUpCamera() self.setUpVision() } private func setUpCamera() { camera = Camera() camera.delegate = self camera.fps = 50 camera.setUp { success in if success { if let visual = self.camera.previewLayer { self.delegate?.addVideoLayer(visual) } self.camera.start() } } } private func setUpVision() { guard let visionModel = try? VNCoreMLModel(for: model.model) else { print("Error: could not create Vision model") return } request = VNCoreMLRequest(model: visionModel, completionHandler: requestDidComplete) request.imageCropAndScaleOption = .centerCrop } private func predict(pixelBuffer: CVPixelBuffer) { // Measure how long it takes to predict a single video frame. Note that // predict() can be called on the next frame while the previous one is // still being processed. Hence the need to queue up the start times. startTimes.append(CACurrentMediaTime()) let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer) try? handler.perform([request]) } private func requestDidComplete(request: VNRequest, error: Error?) { if let observations = request.results as? [VNClassificationObservation] { // The observations appear to be sorted by confidence already, so we // take the top 5 and map them to an array of (String, Double) tuples. let top5 = observations.prefix(through: 4) .map { ($0.identifier.chopPrefix(9), Double($0.confidence)) } DispatchQueue.main.async { self.show(results: top5) self.semaphore.signal() } } } private func show(results: [Prediction]) { var strings: [String] = [] for (count, pred) in results.enumerated() { strings.append(String(format: "%d: %@ (%3.2f%%)", count + 1, pred.0, pred.1 * 100)) } let predictionLabelText = strings.joined(separator: "\n\n") delegate?.setPredictionLabelText(predictionLabelText) let latency = CACurrentMediaTime() - startTimes.remove(at: 0) let fps = self.measureFPS() let timeLabelText = String(format: "%.2f FPS (latency %.5f seconds)", fps, latency) delegate?.setTimeLabelText(timeLabelText) } private func measureFPS() -> Double { // Measure how many frames were actually delivered per second. framesDone += 1 let frameCapturingElapsed = CACurrentMediaTime() - frameCapturingStartTime let currentFPSDelivered = Double(framesDone) / frameCapturingElapsed if frameCapturingElapsed > 1 { framesDone = 0 frameCapturingStartTime = CACurrentMediaTime() } return currentFPSDelivered } } extension Vision: VisionInput { public func videoCapture(_ capture: Camera, didCaptureVideoFrame pixelBuffer: CVPixelBuffer?, timestamp: CMTime) { if let pixelBuffer = pixelBuffer { // For better throughput, perform the prediction on a background queue // instead of on the VideoCapture queue. We use the semaphore to block // the capture queue and drop frames when Core ML can't keep up. semaphore.wait() DispatchQueue.global().async { self.predict(pixelBuffer: pixelBuffer) } } } }
e31ede1870598b699081602512c6c324
33.905172
118
0.627315
false
false
false
false
nextcloud/ios
refs/heads/master
iOSClient/Account Request/NCAccountRequest.swift
gpl-3.0
1
// // NCAccountRequest.swift // Nextcloud // // Created by Marino Faggiana on 26/02/21. // Copyright © 2021 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // 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 UIKit import NextcloudKit public protocol NCAccountRequestDelegate: AnyObject { func accountRequestAddAccount() func accountRequestChangeAccount(account: String) } // optional func public extension NCAccountRequestDelegate { func accountRequestAddAccount() {} func accountRequestChangeAccount(account: String) {} } class NCAccountRequest: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var progressView: UIProgressView! public var accounts: [tableAccount] = [] public var activeAccount: tableAccount? public let heightCell: CGFloat = 60 public var enableTimerProgress: Bool = true public var enableAddAccount: Bool = false public var dismissDidEnterBackground: Bool = false public weak var delegate: NCAccountRequestDelegate? private var timer: Timer? private var time: Float = 0 private let secondsAutoDismiss: Float = 3 // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() titleLabel.text = NSLocalizedString("_account_select_", comment: "") closeButton.setImage(NCUtility.shared.loadImage(named: "xmark", color: .label), for: .normal) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)) tableView.separatorStyle = UITableViewCell.SeparatorStyle.none view.backgroundColor = .secondarySystemBackground tableView.backgroundColor = .secondarySystemBackground progressView.trackTintColor = .clear progressView.progress = 1 if enableTimerProgress { progressView.isHidden = false } else { progressView.isHidden = true } NotificationCenter.default.addObserver(self, selector: #selector(startTimer), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let visibleCells = tableView.visibleCells var numAccounts = accounts.count if enableAddAccount { numAccounts += 1 } if visibleCells.count == numAccounts { tableView.isScrollEnabled = false } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() } // MARK: - Action @IBAction func actionClose(_ sender: UIButton) { dismiss(animated: true) } // MARK: - NotificationCenter @objc func applicationDidEnterBackground() { if dismissDidEnterBackground { dismiss(animated: false) } } // MARK: - Progress @objc func startTimer() { if enableTimerProgress { time = 0 timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true) progressView.isHidden = false } else { progressView.isHidden = true } } @objc func updateProgress() { time += 0.1 if time >= secondsAutoDismiss { dismiss(animated: true) } else { progressView.progress = 1 - (time / secondsAutoDismiss) } } } extension NCAccountRequest: UITableViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { timer?.invalidate() progressView.progress = 0 } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { // startTimer() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // startTimer() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return heightCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == accounts.count { dismiss(animated: true) delegate?.accountRequestAddAccount() } else { let account = accounts[indexPath.row] if account.account != activeAccount?.account { dismiss(animated: true) { self.delegate?.accountRequestChangeAccount(account: account.account) } } else { dismiss(animated: true) } } } } extension NCAccountRequest: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if enableAddAccount { return accounts.count + 1 } else { return accounts.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.backgroundColor = tableView.backgroundColor let avatarImage = cell.viewWithTag(10) as? UIImageView let userLabel = cell.viewWithTag(20) as? UILabel let urlLabel = cell.viewWithTag(30) as? UILabel let activeImage = cell.viewWithTag(40) as? UIImageView userLabel?.text = "" urlLabel?.text = "" if indexPath.row == accounts.count { avatarImage?.image = NCUtility.shared.loadImage(named: "plus").image(color: .systemBlue, size: 15) avatarImage?.contentMode = .center userLabel?.text = NSLocalizedString("_add_account_", comment: "") userLabel?.textColor = .systemBlue userLabel?.font = UIFont.systemFont(ofSize: 15) } else { let account = accounts[indexPath.row] avatarImage?.image = NCUtility.shared.loadUserImage( for: account.user, displayName: account.displayName, userBaseUrl: account) if account.alias.isEmpty { userLabel?.text = account.user.uppercased() urlLabel?.text = (URL(string: account.urlBase)?.host ?? "") } else { userLabel?.text = account.alias.uppercased() } if account.active { activeImage?.image = NCUtility.shared.loadImage(named: "checkmark").image(color: .systemBlue, size: 30) } else { activeImage?.image = nil } } return cell } }
5a4b47313a514ee451faa78476a3d921
30.906122
219
0.647563
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/String+Match.swift
apache-2.0
1
// // String+Match.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2020-09-02. // // --------------------------------------------------------------------------- // // © 2020-2022 1024jp // // 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 // // https://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. // extension String { typealias AbbreviatedMatchResult = (ranges: [Range<String.Index>], score: Int) /// Search ranges of the characters contains in the `searchString` in the `searchString` order. /// /// - Parameter searchString: The string to search. /// - Returns: The array of matched character ranges or `nil` if not matched. func abbreviatedMatch(with searchString: String) -> AbbreviatedMatchResult? { guard !searchString.isEmpty, !self.isEmpty else { return nil } let ranges: [Range<String.Index>] = searchString.reduce(into: []) { (ranges, character) in let index = ranges.last?.upperBound ?? self.startIndex guard let range = self.range(of: String(character), options: .caseInsensitive, range: index..<self.endIndex) else { return } ranges.append(range) } guard ranges.count == searchString.count else { return nil } // just simply caluculate the length... let score = self.distance(from: ranges.first!.lowerBound, to: ranges.last!.upperBound) return (ranges, score) } }
8dbff95f75f6e460383245c2df39b8c3
34.909091
136
0.622278
false
false
false
false
timd/ProiOSTableCollectionViews
refs/heads/master
Ch12/DragAndDrop/Final state/DragAndDrop/DragAndDrop/CollectionViewController.swift
mit
1
// // CollectionViewController.swift // DragAndDrop // // Created by Tim on 20/07/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit private let reuseIdentifier = "ReuseIdentifier" class CollectionViewController: UICollectionViewController { private let reuseIdentifier = "ReuseIdentifier" private var dataArray = [String]() private var selectedCell: UICollectionViewCell? override func viewDidLoad() { super.viewDidLoad() // Allow drag-and-drop interaction self.installsStandardGestureForInteractiveMovement = true // Set up data for index in 0...100 { dataArray.append("\(index)") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) collectionView?.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) // Configure the cell let label: UILabel = cell.viewWithTag(1000) as! UILabel label.text = "Cell \(dataArray[indexPath.row])" cell.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor cell.contentView.layer.borderWidth = 2.0 return cell } // MARK: - // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool { // Highlight the cell selectedCell = collectionView.cellForItemAtIndexPath(indexPath) selectedCell?.contentView.layer.borderColor = UIColor.redColor().CGColor return true } override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { // Find object to move let thingToMove = dataArray[sourceIndexPath.row] // Remove old object dataArray.removeAtIndex(sourceIndexPath.row) // insert new copy of thing to move dataArray.insert(thingToMove, atIndex: destinationIndexPath.row) // Set the cell's background to the original light grey selectedCell?.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor // Reload the data collectionView.reloadData() } }
9f728a477efe6713062d720eb958ae6d
29.969697
165
0.673516
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Macie/Macie_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Macie public struct MacieErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case internalException = "InternalException" case invalidInputException = "InvalidInputException" case limitExceededException = "LimitExceededException" } private let error: Code public let context: AWSErrorContext? /// initialize Macie public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// You do not have required permissions to access the requested resource. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// Internal server error. public static var internalException: Self { .init(.internalException) } /// The request was rejected because an invalid or out-of-range value was supplied for an input parameter. public static var invalidInputException: Self { .init(.invalidInputException) } /// The request was rejected because it attempted to create resources beyond the current AWS account limits. The error code describes the limit exceeded. public static var limitExceededException: Self { .init(.limitExceededException) } } extension MacieErrorType: Equatable { public static func == (lhs: MacieErrorType, rhs: MacieErrorType) -> Bool { lhs.error == rhs.error } } extension MacieErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
dbca91a0866573ea60590ad2b9c990df
36.363636
157
0.663423
false
false
false
false
RamonGilabert/Prodam
refs/heads/master
Prodam/Prodam/BreakWindowController.swift
mit
1
import Cocoa class BreakWindowController: NSWindowController { let breakViewController = BreakViewController() var popoverManager: PopoverManager? // MARK: View lifecycle override func loadWindow() { self.window = BreakWindow(contentRect: self.breakViewController.view.frame, styleMask: NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false) self.window?.contentView = RoundedCornerView(frame: self.breakViewController.view.frame) self.window?.center() self.window?.animationBehavior = NSWindowAnimationBehavior.AlertPanel self.window?.display() self.window?.makeKeyWindow() self.window?.makeMainWindow() NSApp.activateIgnoringOtherApps(true) self.window?.makeKeyAndOrderFront(true) self.breakViewController.popoverManager = self.popoverManager self.popoverManager?.breakController = self (self.window?.contentView as! RoundedCornerView).visualEffectView.addSubview(self.breakViewController.view) } }
e9f9c6df843b98254eb516507bf4c6bc
41.04
170
0.736441
false
false
false
false
timd/ProiOSTableCollectionViews
refs/heads/master
Ch11/NamesApp/NamesApp/ViewController.swift
mit
1
// // ViewController.swift // NamesApp // // Created by Tim on 25/10/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class ViewController: UIViewController { var collation = UILocalizedIndexedCollation.currentCollation() var tableData: [String]! var sections: Array<Array<String>> = [] //var sections: [[String]] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. parsePlist() configureSectionData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Name for the letter \(collation.sectionTitles[section])" } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return collation.sectionTitles } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) let innerData = sections[indexPath.section] cell.textLabel!.text = innerData[indexPath.row] return cell } // MARK: - // MARK: Header and footer methods func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerFrame = CGRectMake(0, 0, tableView.frame.size.width, 100.0) let headerView = UIView(frame: headerFrame) headerView.backgroundColor = UIColor(red: 0.5, green: 0.2, blue: 0.57, alpha: 1.0) let labelFrame = CGRectMake(15.0, 80.0, view.frame.size.width, 15.0) let headerLabel = UILabel(frame: labelFrame) headerLabel.text = "Section Header" headerLabel.font = UIFont(name: "Courier-Bold", size: 18.0) headerLabel.textColor = UIColor.whiteColor() headerView.addSubview(headerLabel) return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerFrame = CGRectMake(0, 0, tableView.frame.size.width, 50.0) let footerView = UIView(frame: footerFrame) footerView.backgroundColor = UIColor(red: 1.0, green: 0.7, blue: 0.57, alpha: 1.0) let labelFrame = CGRectMake(15.0, 10.0, view.frame.size.width, 15.0) let footerLabel = UILabel(frame: labelFrame) footerLabel.text = "Section Footer" footerLabel.font = UIFont(name: "Times-New-Roman", size: 12.0) footerLabel.textColor = UIColor.blueColor() footerView.addSubview(footerLabel) return footerView } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50.0 } } extension ViewController { func parsePlist() { let bundle = NSBundle.mainBundle() if let plistPath = bundle.pathForResource("Names", ofType: "plist"), let namesDictionary = NSDictionary(contentsOfFile: plistPath), let names = namesDictionary["Names"] { tableData = names as! [String] } } func configureSectionData() { let selector: Selector = "lowercaseString" sections = Array(count: collation.sectionTitles.count, repeatedValue: []) let sortedObjects = collation.sortedArrayFromArray(tableData, collationStringSelector: selector) for object in sortedObjects { let sectionNumber = collation.sectionForObject(object, collationStringSelector: selector) sections[sectionNumber].append(object as! String) } } }
a2ea60f69f299fa572801d5413b059f4
30.553191
109
0.640513
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
IntegrationTests/Tests/IntegrationTests/BasicTests.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCBasic import TSCTestSupport final class BasicTests: XCTestCase { func testVersion() throws { XCTAssertMatch(try sh(swift, "--version").stdout, .contains("Swift version")) } func testExamplePackageDealer() throws { try XCTSkipIf(isSelfHosted, "These packages don't use the latest runtime library, which doesn't work with self-hosted builds.") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "dealer") try sh("git", "clone", "https://github.com/apple/example-package-dealer", packagePath) let build1Output = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertMatch(build1Output, .contains("Build complete")) // Verify that the app works. let dealerOutput = try sh(AbsolutePath(".build/debug/dealer", relativeTo: packagePath), "10").stdout XCTAssertEqual(dealerOutput.filter(\.isPlayingCardSuit).count, 10) // Verify that the 'git status' is clean after a build. try localFileSystem.changeCurrentWorkingDirectory(to: packagePath) let gitOutput = try sh("git", "status").stdout XCTAssertMatch(gitOutput, .contains("nothing to commit, working tree clean")) // Verify that another 'swift build' does nothing. let build2Output = try sh(swiftBuild, "--package-path", packagePath).stdout XCTAssertMatch(build2Output, .contains("Build complete")) XCTAssertNoMatch(build2Output, .contains("Compiling")) } } func testSwiftBuild() throws { try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "tool") try localFileSystem.createDirectory(packagePath) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:4.2 import PackageDescription let package = Package( name: "tool", targets: [ .target(name: "tool", path: "./"), ] ) """)) try localFileSystem.writeFileContents( packagePath.appending(component: "main.swift"), bytes: ByteString(encodingAsUTF8: #"print("HI")"#)) // Check the build. let buildOutput = try sh(swiftBuild, "--package-path", packagePath, "-v").stdout XCTAssertMatch(buildOutput, .regex("swiftc.* -module-name tool")) // Verify that the tool exists and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "tool")).stdout XCTAssertEqual(toolOutput, "HI\n") } } func testSwiftCompiler() throws { try withTemporaryDirectory { tempDir in let helloSourcePath = tempDir.appending(component: "hello.swift") try localFileSystem.writeFileContents( helloSourcePath, bytes: ByteString(encodingAsUTF8: #"print("hello")"#)) let helloBinaryPath = tempDir.appending(component: "hello") try sh(swiftc, helloSourcePath, "-o", helloBinaryPath) // Check the file exists. XCTAssert(localFileSystem.exists(helloBinaryPath)) // Check the file runs. let helloOutput = try sh(helloBinaryPath).stdout XCTAssertEqual(helloOutput, "hello\n") } } func testSwiftPackageInitExec() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") let buildOutput = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertContents(buildOutput) { checker in checker.check(.regex("Compiling .*Project.*")) checker.check(.regex("Linking .*Project")) checker.check(.contains("Build complete")) } // Verify that the tool was built and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "Project")).stdout XCTAssertMatch(toolOutput.lowercased(), .contains("hello, world!")) // Check there were no compile errors or warnings. XCTAssertNoMatch(buildOutput, .contains("error")) XCTAssertNoMatch(buildOutput, .contains("warning")) } } func testSwiftPackageInitExecTests() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") let testOutput = try sh(swiftTest, "--package-path", packagePath).stdout // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.regex("Compiling .*ProjectTests.*")) checker.check("Test Suite 'All tests' passed") checker.checkNext("Executed 1 test") } // Check there were no compile errors or warnings. XCTAssertNoMatch(testOutput, .contains("error")) XCTAssertNoMatch(testOutput, .contains("warning")) } } func testSwiftPackageInitLib() throws { try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") let buildOutput = try sh(swiftBuild, "--package-path", packagePath).stdout // Check the build log. XCTAssertMatch(buildOutput, .regex("Compiling .*Project.*")) XCTAssertMatch(buildOutput, .contains("Build complete")) // Check there were no compile errors or warnings. XCTAssertNoMatch(buildOutput, .contains("error")) XCTAssertNoMatch(buildOutput, .contains("warning")) } } func testSwiftPackageLibsTests() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in // Create a new package with an executable target. let packagePath = tempDir.appending(component: "Project") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") let testOutput = try sh(swiftTest, "--package-path", packagePath).stdout // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.regex("Compiling .*ProjectTests.*")) checker.check("Test Suite 'All tests' passed") checker.checkNext("Executed 1 test") } // Check there were no compile errors or warnings. XCTAssertNoMatch(testOutput, .contains("error")) XCTAssertNoMatch(testOutput, .contains("warning")) } } func testSwiftPackageWithSpaces() throws { try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(components: "more spaces", "special tool") try localFileSystem.createDirectory(packagePath, recursive: true) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:4.2 import PackageDescription let package = Package( name: "special tool", targets: [ .target(name: "special tool", path: "./"), ] ) """)) try localFileSystem.writeFileContents( packagePath.appending(component: "main.swift"), bytes: ByteString(encodingAsUTF8: #"foo()"#)) try localFileSystem.writeFileContents( packagePath.appending(component: "some file.swift"), bytes: ByteString(encodingAsUTF8: #"func foo() { print("HI") }"#)) // Check the build. let buildOutput = try sh(swiftBuild, "--package-path", packagePath, "-v").stdout XCTAssertMatch(buildOutput, .regex(#"swiftc.* -module-name special_tool .* ".*/more spaces/special tool/some file.swift""#)) XCTAssertMatch(buildOutput, .contains("Build complete")) // Verify that the tool exists and works. let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "special tool")).stdout XCTAssertEqual(toolOutput, "HI\n") } } func testSwiftRun() throws { #if swift(<5.5) try XCTSkipIf(true, "skipping because host compiler doesn't support '-entry-point-function-name'") #endif try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "secho") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "executable") // delete any files generated for entry in try localFileSystem.getDirectoryContents(packagePath.appending(components: "Sources", "secho")) { try localFileSystem.removeFileTree(packagePath.appending(components: "Sources", "secho", entry)) } try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "secho", "main.swift"), bytes: ByteString(encodingAsUTF8: """ import Foundation print(CommandLine.arguments.dropFirst().joined(separator: " ")) """)) let (runOutput, runError) = try sh(swiftRun, "--package-path", packagePath, "secho", "1", #""two""#) // Check the run log. XCTAssertContents(runError) { checker in checker.check(.regex("Compiling .*secho.*")) checker.check(.regex("Linking .*secho")) checker.check(.contains("Build complete")) } XCTAssertEqual(runOutput, "1 \"two\"\n") } } func testSwiftTest() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "swiftTest") try localFileSystem.createDirectory(packagePath) try sh(swiftPackage, "--package-path", packagePath, "init", "--type", "library") try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "swiftTestTests", "MyTests.swift"), bytes: ByteString(encodingAsUTF8: """ import XCTest final class MyTests: XCTestCase { func testFoo() { XCTAssertTrue(1 == 1) } func testBar() { XCTAssertFalse(1 == 2) } func testBaz() { } } """)) let testOutput = try sh(swiftTest, "--package-path", packagePath, "--filter", "MyTests.*", "--skip", "testBaz").stderr // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.contains("Test Suite 'MyTests' started")) checker.check(.contains("Test Suite 'MyTests' passed")) checker.check(.contains("Executed 2 tests, with 0 failures")) } } } func testSwiftTestWithResources() throws { try XCTSkip("FIXME: swift-test invocations are timing out in Xcode and self-hosted CI") try withTemporaryDirectory { tempDir in let packagePath = tempDir.appending(component: "swiftTestResources") try localFileSystem.createDirectory(packagePath) try localFileSystem.writeFileContents( packagePath.appending(component: "Package.swift"), bytes: ByteString(encodingAsUTF8: """ // swift-tools-version:5.3 import PackageDescription let package = Package( name: "AwesomeResources", targets: [ .target(name: "AwesomeResources", resources: [.copy("hello.txt")]), .testTarget(name: "AwesomeResourcesTest", dependencies: ["AwesomeResources"], resources: [.copy("world.txt")]) ] ) """) ) try localFileSystem.createDirectory(packagePath.appending(component: "Sources")) try localFileSystem.createDirectory(packagePath.appending(components: "Sources", "AwesomeResources")) try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "AwesomeResources", "AwesomeResource.swift"), bytes: ByteString(encodingAsUTF8: """ import Foundation public struct AwesomeResource { public init() {} public let hello = try! String(contentsOf: Bundle.module.url(forResource: "hello", withExtension: "txt")!) } """) ) try localFileSystem.writeFileContents( packagePath.appending(components: "Sources", "AwesomeResources", "hello.txt"), bytes: ByteString(encodingAsUTF8: "hello") ) try localFileSystem.createDirectory(packagePath.appending(component: "Tests")) try localFileSystem.createDirectory(packagePath.appending(components: "Tests", "AwesomeResourcesTest")) try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "AwesomeResourcesTest", "world.txt"), bytes: ByteString(encodingAsUTF8: "world") ) try localFileSystem.writeFileContents( packagePath.appending(components: "Tests", "AwesomeResourcesTest", "MyTests.swift"), bytes: ByteString(encodingAsUTF8: """ import XCTest import Foundation import AwesomeResources final class MyTests: XCTestCase { func testFoo() { XCTAssertTrue(AwesomeResource().hello == "hello") } func testBar() { let world = try! String(contentsOf: Bundle.module.url(forResource: "world", withExtension: "txt")!) XCTAssertTrue(world == "world") } } """)) let testOutput = try sh(swiftTest, "--package-path", packagePath, "--filter", "MyTests.*").stderr // Check the test log. XCTAssertContents(testOutput) { checker in checker.check(.contains("Test Suite 'MyTests' started")) checker.check(.contains("Test Suite 'MyTests' passed")) checker.check(.contains("Executed 2 tests, with 0 failures")) } } } } private extension Character { var isPlayingCardSuit: Bool { switch self { case "♠︎", "♡", "♢", "♣︎": return true default: return false } } }
6f3bd61f31e81c1ab1a529367ef6c9ce
44.448549
137
0.579623
false
true
false
false
hw3308/Swift3Basics
refs/heads/master
Swift3Basics/Extension/UIImage+Extension.swift
mit
2
// // UIImage+Extension.swift // SwiftBasics // // Created by 侯伟 on 17/1/11. // Copyright © 2017年 侯伟. All rights reserved. // import Foundation import UIKit // MARK: Data extension UIImage { public var data: Data? { switch contentType { case .jpeg: return UIImageJPEGRepresentation(self, 1) case .png: return UIImagePNGRepresentation(self) //case .GIF: //return UIImageAnimatedGIFRepresentation(self) default: return nil } } } // MARK: Content Type extension UIImage { fileprivate struct AssociatedKey { static var contentType: Int = 0 } public enum ContentType: Int { case unknown = 0, png, jpeg, gif, tiff, webp public var mimeType: String { switch self { case .jpeg: return "image/jpeg" case .png: return "image/png" case .gif: return "image/gif" case .tiff: return "image/tiff" case .webp: return "image/webp" default: return "" } } public var extendName: String { switch self { case .jpeg: return ".jpg" case .png: return ".png" case .gif: return ".gif" case .tiff: return ".tiff" case .webp: return ".webp" default: return "" } } public static func contentType(mimeType: String?) -> ContentType { guard let mime = mimeType else { return .unknown } switch mime { case "image/jpeg": return .jpeg case "image/png": return .png case "image/gif": return .gif case "image/tiff": return .tiff case "image/webp": return .webp default: return .unknown } } public static func contentTypeWithImageData(_ imageData: Data?) -> ContentType { guard let data = imageData else { return .unknown } var c = [UInt32](repeating: 0, count: 1) (data as NSData).getBytes(&c, length: 1) switch (c[0]) { case 0xFF: return .jpeg case 0x89: return .png case 0x47: return .gif case 0x49, 0x4D: return .tiff case 0x52: // R as RIFF for WEBP if data.count >= 12 { if let type = String(data: data.subdata(in: data.startIndex..<data.startIndex.advanced(by: 12)), encoding: String.Encoding.ascii) { if type.hasPrefix("RIFF") && type.hasSuffix("WEBP") { return .webp } } } default: break } return .unknown } } public var contentType: ContentType { get { let value = objc_getAssociatedObject(self, &AssociatedKey.contentType) as? Int ?? 0 if value == 0 { var result: ContentType //if let _ = UIImageAnimatedGIFRepresentation(self) { //result = .GIF //} else if let _ = UIImageJPEGRepresentation(self, 1) { result = .jpeg } else if let _ = UIImagePNGRepresentation(self) { result = .png } else { result = .unknown } objc_setAssociatedObject(self, &AssociatedKey.contentType, result.rawValue, .OBJC_ASSOCIATION_RETAIN) return result } return ContentType(rawValue: value) ?? .unknown } set { objc_setAssociatedObject(self, &AssociatedKey.contentType, newValue.rawValue, .OBJC_ASSOCIATION_RETAIN) } } convenience init?(data: Data, contentType: ContentType) { self.init(data: data) self.contentType = contentType } }
209e22dd9edbe9518437def6097fd461
29.865672
151
0.488878
false
false
false
false
stevewight/DetectorKit
refs/heads/master
DetectorKit/Views/PulseView.swift
mit
1
// // PulseView.swift // DetectorKit // // Created by Steve on 4/12/17. // Copyright © 2017 Steve Wight. All rights reserved. // import UIKit class PulseView: BaseFrameView { var circles = [CAShapeLayer]() override internal func setUp() { setUpCircle() setUpAnimations() } private func setUpCircle() { let baseLayer = createCircle() baseLayer.path = createPath(baseLayer,0) layer.addSublayer(baseLayer) circles.insert(baseLayer, at:0) } private func setUpAnimations() { pulse(circles[0]) } private func pulse(_ circle:CAShapeLayer) { let animation = CirclePulseAnimate(circle) animation.pulse() } private func createCircle()->CAShapeLayer { let circle = CAShapeLayer() circle.frame = layer.bounds circle.fillColor = lineColor circle.strokeColor = lineColor circle.lineWidth = CGFloat(lineWidth) return circle } private func createPath(_ circle:CAShapeLayer,_ index:Int)->CGPath { let size = circle.bounds.size let radius = size.width/2 let rectPath = CGRect( x: 0.0, y: 0.0, width: size.width, height: size.height ) return UIBezierPath( roundedRect: rectPath, cornerRadius: radius ).cgPath } }
3a0f32ebcb206fa7827715524bc78705
22.491803
72
0.578507
false
false
false
false
AlexandreCassagne/RuffLife-iOS
refs/heads/master
RuffLife/FoundViewController.swift
mit
1
// // FoundViewController.swift // RuffLife // // Created by Alexandre Cassagne on 21/10/2017. // Copyright © 2017 Cassagne. All rights reserved. // import UIKit import AWSDynamoDB import CoreLocation class FoundViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate { var locationCoordinate: CLLocationCoordinate2D? func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let l = locations[0] locationCoordinate = l.coordinate location.text = "\(locationCoordinate!.latitude, locationCoordinate!.latitude)" } var url: String? var uploadImage: UploadImage? var imagePicker = UIImagePickerController() func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } private func startAzure() { let a = Azure() print("Starting azure...") a.request(url: self.url!) { predictions in print("Got callback.") let top = predictions[0] as! [String: Any] print(top) let p = top["Probability"] as! Double let breed = top["Tag"] as! String if (p > 0.08) { OperationQueue.main.addOperation({ self.breed.text = breed }) } } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } pictureView.image = image uploadImage = UploadImage(image: image) print("Starting upload...") uploadImage?.post { print("Returned: \(self.uploadImage?.publicURL)") self.url = self.uploadImage?.publicURL?.absoluteString self.startAzure() } picker.dismiss(animated: true, completion: nil) } @IBOutlet weak var location: UITextField! @IBOutlet weak var breed: UITextField! // @IBOutlet weak var color: UITextField! @IBOutlet weak var firstName: UITextField! @IBOutlet weak var number: UITextField! @IBOutlet weak var pictureView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.delegate = self // Do any additional setup after loading the view. } @IBAction func submit(_ sender: Any) { guard let coordinate = self.locationCoordinate, let name = firstName.text, let phoneNumber = number.text else { let alert = UIAlertController(title: "Incomplete Form", message: "Please ensure the form is completely filled out before proceeding.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) return } let db = AWSDynamoDBObjectMapper.default() let newPet = RuffLife()! newPet.FirstName = name // newPet.LastName = "Empty" newPet.PhoneNumber = phoneNumber newPet.Breed = breed.text // newPet.Color = color.text newPet.ImageURL = url! newPet.lat = coordinate.latitude as NSNumber newPet.lon = coordinate.longitude as NSNumber newPet.PetID = NSNumber(integerLiteral: Int(arc4random())) db.save(newPet).continueWith(block: { (task:AWSTask<AnyObject>!) -> Any? in DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert) if let error = task.error as NSError? { alert.title = "Failure" alert.message = "The request failed. Error: \(error)" alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } else { // Do something with task.result or perform other operations. alert.title = "Success" alert.message = "Successfully published to location of this pet!" alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { _ in self.navigationController!.popViewController(animated: true) })) self.present(alert, animated: true, completion: nil) } } return nil }) } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Warning", message: "You don't have a camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func openGallary() { imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } @IBAction func autofill(_ sender: Any) { let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openCamera() })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.openGallary() })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) locationManager.distanceFilter = kCLDistanceFilterNone; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.startUpdatingLocation() self.present(alert, animated: true, completion: nil) // self.show(picker, sender: self) present(imagePicker, animated: true, completion: nil) } let locationManager = CLLocationManager() @IBOutlet weak var autofill: UIButton! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33337430c0982c7a5dbbd5867ef251d5
32.344086
161
0.722025
false
false
false
false
gurenupet/hah-auth-ios-swift
refs/heads/master
hah-auth-ios-swift/hah-auth-ios-swift/AppDelegate.swift
mit
1
// // AppDelegate.swift // hah-auth-ios-swift // // Created by Anton Antonov on 06.07.17. // Copyright © 2017 KRIT. All rights reserved. // import UIKit import Mixpanel @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { configureMixpanel() configureNavigationBar() return true } //MARK: - Mixpanel func configureMixpanel() { let device = UIDevice.current.identifierForVendor?.uuidString Mixpanel.initialize(token: Parameters.MixpanelToken.rawValue) Mixpanel.mainInstance().identify(distinctId: device!) } //MARK: - Interface func configureNavigationBar() { //Title let titleFont = UIFont(name: Fonts.Medium.rawValue, size: 17.0)! let titleColor = UIColor.colorFrom(hex: "333333") UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : titleFont, NSForegroundColorAttributeName : titleColor] //Кастомизация стрелки назад let backArrow = UIImage(named: "Navigation Bar Back Arrow")! UINavigationBar.appearance().backIndicatorImage = backArrow UINavigationBar.appearance().backIndicatorTransitionMaskImage = backArrow //Трюк для скрытия текста в кнопке назад UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clear], for: .normal) UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clear], for: .highlighted) //Тень под панелью UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UINavigationBar.appearance().shadowImage = UIImage(named: "Navigation Bar Shadow") } }
b0a81d434c8042afb0dfff28dc135900
34.509091
144
0.693804
false
true
false
false
renshu16/DouyuSwift
refs/heads/master
DouyuSwift/DouyuSwift/Classes/Home/View/AmuseMenuView.swift
mit
1
// // AmuseMenuView.swift // DouyuSwift // // Created by ToothBond on 16/12/5. // Copyright © 2016年 ToothBond. All rights reserved. // import UIKit private let kMenuViewCellID : String = "MenuViewCellID" class AmuseMenuView: UIView { @IBOutlet weak var collectionView: UICollectionView! var groups : [AnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuViewCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension AmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let pageNum = (groups!.count - 1)/8 + 1 pageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuViewCellID, for: indexPath) as! AmuseMenuViewCell setupCellDataWithCell(cell: cell, indexPath: indexPath) return cell } func setupCellDataWithCell(cell:AmuseMenuViewCell,indexPath:IndexPath) { let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } cell.groups = Array(groups![startIndex...endIndex]) } } extension AmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = Int(scrollView.contentOffset.x / scrollView.bounds.width) print("pageIndex = \(pageIndex)") pageControl.currentPage = pageIndex } } extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView; } }
e8f2fd8ec3ba2d94b0156c34257de2df
28.554217
129
0.660823
false
false
false
false
philipgreat/b2b-swift-app
refs/heads/master
B2BSimpleApp/B2BSimpleApp/Footer.swift
mit
1
//Domain B2B/Footer/ import Foundation import ObjectMapper //Use this to generate Object import SwiftyJSON //Use this to verify the JSON Object struct Footer{ var id : String? var page : HomePage? var image : String? var action : String? var version : Int? init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } static var CLASS_VERSION = "1" //This value is for serializer like message pack to identify the versions match between //local and remote object. } extension Footer: Mappable{ //Confirming to the protocol Mappable of ObjectMapper //Reference on https://github.com/Hearst-DD/ObjectMapper/ init?(_ map: Map){ } mutating func mapping(map: Map) { //Map each field to json fields id <- map["id"] page <- map["page"] image <- map["image"] action <- map["action"] version <- map["version"] } } extension Footer:CustomStringConvertible{ //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). var result = "footer{"; if id != nil { result += "\tid='\(id!)'" } if page != nil { result += "\tpage='\(page!)'" } if image != nil { result += "\timage='\(image!)'" } if action != nil { result += "\taction='\(action!)'" } if version != nil { result += "\tversion='\(version!)'" } result += "}" return result } }
0a979c70cd29a621ac695a74370bf3f0
20.843373
100
0.547468
false
false
false
false
wpuricz/vapor-database-sample
refs/heads/master
Sources/App/Controllers/ApplicationController.swift
mit
1
import Vapor import HTTP extension Vapor.KeyAccessible where Key == HeaderKey, Value == String { var contentType: String? { get { return self["Content-Type"] } set { self["Content-Type"] = newValue } } var authorization: String? { get { return self["Authorization"] } set { self["Authorization"] = newValue } } } public enum ContentType: String { case html = "text/html" case json = "application/json" } open class ApplicationController { private var resourcefulName: String { let className = String(describing: type(of: self)) return className.replacingOccurrences(of: "Controller", with: "").lowercased() } public func respond(to request: Request, with response: [ContentType : ResponseRepresentable]) -> ResponseRepresentable { let contentTypeValue = request.headers.contentType ?? ContentType.html.rawValue let contentType = ContentType(rawValue: contentTypeValue) ?? ContentType.html return response[contentType] ?? Response(status: .notFound) } public func render(_ path: String, _ context: NodeRepresentable? = nil) throws -> View { return try drop.view.make("\(resourcefulName)/\(path)", context ?? Node.null) } public func render(_ path: String, _ context: [String : NodeRepresentable]?) throws -> View { return try render(path, context?.makeNode()) } } extension Resource { public convenience init( index: Multiple? = nil, show: Item? = nil, create: Multiple? = nil, replace: Item? = nil, update: Item? = nil, destroy: Item? = nil, clear: Multiple? = nil, aboutItem: Item? = nil, aboutMultiple: Multiple? = nil) { self.init( index: index, store: create, show: show, replace: replace, modify: update, destroy: destroy, clear: clear, aboutItem: aboutItem, aboutMultiple: aboutMultiple ) } }
40750eb9a8df547a5b3d7037779c0c84
27.194805
125
0.576693
false
false
false
false
CNKCQ/oschina
refs/heads/master
OSCHINA/Models/Discover/DiscoverModel.swift
mit
1
// // DiscoverModel.swift // OSCHINA // // Created by KingCQ on 2017/1/15. // Copyright © 2017年 KingCQ. All rights reserved. // import Foundation import ObjectMapper class ArticleEntity: Mappable { var who: String? var id: String? var desc: String? var publishedAt: Date? var used: Int? var createdAt: Date? var url: String? var type: String? // MARK: Mappable func mapping(map: Map) { who <- map["who"] id <- map["_id"] desc <- map["desc"] publishedAt <- (map["publishedAt"], CustomDateFormatTransform(formatString: DateUtil.dateFormatter)) used <- map["used"] createdAt <- (map["createdAt"], CustomDateFormatTransform(formatString: DateUtil.dateFormatter)) url <- map["url"] type <- map["type"] } required init?(map _: Map) { } } public class DateUtil { static let dateFormatter = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" public static func stringToNSDate(dateString: String, formatter: String = dateFormatter) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = formatter return dateFormatter.date(from: dateString)! } public static func nsDateToString(date: Date, formatter: String = "yyyy-MM-dd HH:mm:ss") -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = formatter return dateFormatter.string(from: date) } public static func areDatesSameDay(dateOne _: Date, dateTwo _: Date) -> Bool { return true } }
9ab88da662c4ac7c545cefb9763a2f13
25.827586
108
0.634961
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/Alert.swift
mit
1
// // Alert.swift // MEGameTracker // // Created by Emily Ivie on 4/14/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit /// Helper for showing alerts. public struct Alert { // MARK: Types public typealias ActionButtonType = (title: String, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)) // MARK: Properties public var title: String public var description: String public var actions: [ActionButtonType] = [] // MARK: Change Listeners And Change Status Flags public static var onSignal = Signal<(Alert)>() // MARK: Initialization public init(title: String?, description: String) { self.title = title ?? "" self.description = description } } // MARK: Basic Actions extension Alert { /// Pops up an alert in the specified controller. public func show(fromController controller: UIViewController, sender: UIView? = nil) { let alert = UIAlertController(title: title, message: description, preferredStyle: .alert) if actions.isEmpty { alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { _ in })) } else { for action in actions { alert.addAction(UIAlertAction(title: action.title, style: action.style, handler: action.handler)) } } alert.popoverPresentationController?.sourceView = sender ?? controller.view alert.modalPresentationStyle = .popover // Alert default button defaults to window tintColor (red), // Which is too similar to destructive button (red), // And I can't change it in Styles using appearance(), // So I have to do it here, which pisses me off. alert.view.tintColor = UIColor.systemBlue // Styles.colors.altTint if let bounds = sender?.bounds { alert.popoverPresentationController?.sourceRect = bounds } controller.present(alert, animated: true, completion: nil) } }
86d28705497d73ce6e80672899d8f164
27.968254
116
0.716164
false
false
false
false
jkolb/midnightbacon
refs/heads/master
MidnightBacon/Modules/Common/Services/Logger.swift
mit
1
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.net // // 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 protocol LogFormatter { func format(record: LogRecord) -> String } public protocol LogHandler { func publish(record: LogRecord) } public class LogRecord { public let timestamp: NSDate public let level: LogLevel public let processName: String public let threadID: UInt64 public let fileName: String public let lineNumber: Int public let message: String public init(timestamp: NSDate, level: LogLevel, processName: String, threadID: UInt64, fileName: String, lineNumber: Int, message: String) { self.timestamp = timestamp self.level = level self.processName = processName self.threadID = threadID self.fileName = fileName self.lineNumber = lineNumber self.message = message } } public enum LogLevel : UInt8, Comparable { case None case Error case Warn case Info case Debug public var formatted: String { switch self { case .Error: fallthrough case .Debug: return "\(self)".uppercaseString default: return "\(self)".uppercaseString + " " } } } public class LogStringFormatter : LogFormatter { private let dateFormatter: NSDateFormatter public init() { self.dateFormatter = NSDateFormatter() self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" } public init(dateFormatter: NSDateFormatter) { self.dateFormatter = dateFormatter } public func format(record: LogRecord) -> String { return "\(dateFormatter.stringFromDate(record.timestamp)) \(record.level.formatted) \(record.processName)[\(record.threadID)] \(record.fileName):\(record.lineNumber) \(record.message)" } } public class LogConsoleHandler : LogHandler { private let formatter: LogFormatter public init(formatter: LogFormatter = LogStringFormatter()) { self.formatter = formatter } public func publish(record: LogRecord) { print(formatter.format(record)) } } public class LogCompositeHandler : LogHandler { private let handlers: [LogHandler] public init(handlers: [LogHandler]) { self.handlers = handlers } public func publish(record: LogRecord) { for handler in handlers { handler.publish(record) } } } public class Logger { public let level: LogLevel private let handler: LogHandler private let processName = NSProcessInfo.processInfo().processName private static let queue = dispatch_queue_create("net.franticapparatus.Logger", DISPATCH_QUEUE_SERIAL) public init(level: LogLevel, handler: LogHandler = LogConsoleHandler()) { self.level = level self.handler = handler } private var threadID: UInt64 { var ID: __uint64_t = 0 pthread_threadid_np(nil, &ID) return ID } private func log(@autoclosure message: () -> String, level: LogLevel, fileName: String = __FILE__, lineNumber: Int = __LINE__) { if level > self.level { return } let record = LogRecord( timestamp: NSDate(), level: level, processName: processName, threadID: self.threadID, fileName: NSString(string: fileName).lastPathComponent, lineNumber: lineNumber, message: message() ) let handler = self.handler dispatch_async(Logger.queue) { handler.publish(record) } } public func error(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Error, fileName: fileName, lineNumber: lineNumber) } public func error(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Error, fileName: fileName, lineNumber: lineNumber) } public func warn(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Warn, fileName: fileName, lineNumber: lineNumber) } public func warn(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Warn, fileName: fileName, lineNumber: lineNumber) } public func info(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Info, fileName: fileName, lineNumber: lineNumber) } public func info(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Info, fileName: fileName, lineNumber: lineNumber) } public func debug(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Debug, fileName: fileName, lineNumber: lineNumber) } public func debug(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Debug, fileName: fileName, lineNumber: lineNumber) } } public func < (lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
aa36e343a9cd484543312cf886a213b7
33.805405
192
0.648703
false
false
false
false
benwwchen/sysujwxt-ios
refs/heads/master
SYSUJwxt/LocalNotification.swift
bsd-3-clause
1
// // LocalNotification.swift // SYSUJwxt // // Created by benwwchen on 2017/8/25. // // reference: mourodrigo // https://stackoverflow.com/questions/42688760/local-and-push-notifications-in-ios-9-and-10-using-swift3 // import UIKit import UserNotifications class LocalNotification: NSObject, UNUserNotificationCenterDelegate { class func registerForLocalNotification(on application:UIApplication, currentViewController: UIViewController) { if (UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:)))) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in if granted { print("用户允许") } else { // Alert fail and navigate user to settings currentViewController.alert(title: AlertTitles.PermissionDenied, message: AlertTitles.NotificationPermissionRequest, titleDefault: AlertTitles.Settings, titleCancel: AlertTitles.Cancel, handler: { (action) in DispatchQueue.main.async { switch action.style { case .default: // go to settings UIApplication.shared.open(URL(string: "App-prefs:root=com.bencww.SYSUJwxt")!, completionHandler: { (success) in currentViewController.dismiss(animated: true, completion: nil) }) break case .cancel: currentViewController.dismiss(animated: true, completion: nil) break default: break } } }) } } } else { let notificationCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory() notificationCategory.identifier = "NOTIFICATION_CATEGORY" //registerting for the notification. application.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound, .alert, .badge], categories: nil)) // check if the notification setting is on let notificationType = UIApplication.shared.currentUserNotificationSettings?.types if notificationType?.rawValue == 0 { currentViewController.alert(title: AlertTitles.PermissionDenied, message: AlertTitles.NotificationPermissionRequest, titleDefault: AlertTitles.Settings, titleCancel: AlertTitles.Cancel, handler: { (action) in DispatchQueue.main.async { switch action.style { case .default: // go to settings UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) break case .cancel: currentViewController.dismiss(animated: true, completion: nil) break default: break } } }) } } } } class func dispatchlocalNotification(with title: String, body: String, userInfo: [AnyHashable: Any]? = nil, at timeInterval: TimeInterval) { let date = Date(timeIntervalSinceNow: timeInterval) if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = title content.body = body content.categoryIdentifier = "update" if let info = userInfo { content.userInfo = info } content.sound = UNNotificationSound.default() let comp = Calendar.current.dateComponents([.hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) } else { let notification = UILocalNotification() notification.fireDate = date notification.alertTitle = title notification.alertBody = body if let info = userInfo { notification.userInfo = info } notification.soundName = UILocalNotificationDefaultSoundName UIApplication.shared.scheduleLocalNotification(notification) } print("WILL DISPATCH LOCAL NOTIFICATION AT ", date) } }
a01a0329b205b8993e29f9cde94ba56f
42.777778
232
0.505983
false
false
false
false
luckymore0520/leetcode
refs/heads/master
Rotate Image.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //You are given an n x n 2D matrix representing an image. // //Rotate the image by 90 degrees (clockwise). // //Follow up: //Could you do this in-place? class Solution { func rotate(_ matrix: inout [[Int]]) { let n = matrix.count if (n <= 1) { return } for k in 0...n/2-1 { for i in k...n-2-k { (matrix[k][i],matrix[i][n-1-k],matrix[n-1-k][n-i-1],matrix[n-i-1][k]) = (matrix[n-i-1][k],matrix[k][i],matrix[i][n-1-k],matrix[n-1-k][n-i-1]) } } } } //1 2 3 4 //5 6 7 8 //9 10 11 12 //13 14 15 16 let solution = Solution() var matric = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] solution.rotate(&matric) print(matric)
c5d3737114bab21122ad83c6fc5559b7
20.621622
157
0.52816
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/GenericExtensions/ExtensionUIFont.swift
mit
2
import UIKit extension UIFont { static let kFontLight:String = "HelveticaNeue-Thin" static let kFontRegular:String = "HelveticaNeue" static let kFontMedium:String = "HelveticaNeue-Medium" static let kFontBold:String = "HelveticaNeue-Bold" class func light(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontLight, size:size)! return font } class func regular(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontRegular, size:size)! return font } class func medium(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontMedium, size:size)! return font } class func bold(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontBold, size:size)! return font } }
3e97395cb02325e8d9a8b150537afce2
22.621622
63
0.601831
false
false
false
false
hollance/swift-algorithm-club
refs/heads/master
Dijkstra Algorithm/VisualizedDijkstra.playground/Sources/Graph.swift
mit
4
import Foundation import UIKit public enum GraphState { case initial case autoVisualization case interactiveVisualization case parsing case completed } public class Graph { private var verticesCount: UInt private var _vertices: Set<Vertex> = Set() public weak var delegate: GraphDelegate? public var nextVertices: [Vertex] = [] public var state: GraphState = .initial public var pauseVisualization = false public var stopVisualization = false public var startVertex: Vertex? public var interactiveNeighborCheckAnimationDuration: Double = 1.8 { didSet { _interactiveOneSleepDuration = UInt32(interactiveNeighborCheckAnimationDuration * 1000000.0 / 3.0) } } private var _interactiveOneSleepDuration: UInt32 = 600000 public var visualizationNeighborCheckAnimationDuration: Double = 2.25 { didSet { _visualizationOneSleepDuration = UInt32(visualizationNeighborCheckAnimationDuration * 1000000.0 / 3.0) } } private var _visualizationOneSleepDuration: UInt32 = 750000 public var vertices: Set<Vertex> { return _vertices } public init(verticesCount: UInt) { self.verticesCount = verticesCount } public func removeGraph() { _vertices.removeAll() startVertex = nil } public func createNewGraph() { guard _vertices.isEmpty, startVertex == nil else { assertionFailure("Clear graph before creating new one") return } createNotConnectedVertices() setupConnections() let offset = Int(arc4random_uniform(UInt32(_vertices.count))) let index = _vertices.index(_vertices.startIndex, offsetBy: offset) startVertex = _vertices[index] setVertexLevels() } private func clearCache() { _vertices.forEach { $0.clearCache() } } public func reset() { for vertex in _vertices { vertex.clearCache() } } private func createNotConnectedVertices() { for i in 0..<verticesCount { let vertex = Vertex(identifier: "\(i)") _vertices.insert(vertex) } } private func setupConnections() { for vertex in _vertices { let randomEdgesCount = arc4random_uniform(4) + 1 for _ in 0..<randomEdgesCount { let randomWeight = Double(arc4random_uniform(10)) let neighbor = randomVertex(except: vertex) let edge1 = Edge(vertex: neighbor, weight: randomWeight) if vertex.edges.contains(where: { $0.neighbor == neighbor }) { continue } let edge2 = Edge(vertex: vertex, weight: randomWeight) vertex.edges.append(edge1) neighbor.edges.append(edge2) } } } private func randomVertex(except vertex: Vertex) -> Vertex { var newSet = _vertices newSet.remove(vertex) let offset = Int(arc4random_uniform(UInt32(newSet.count))) let index = newSet.index(newSet.startIndex, offsetBy: offset) return newSet[index] } private func setVertexLevels() { _vertices.forEach { $0.clearLevelInfo() } guard let startVertex = startVertex else { assertionFailure() return } var queue: [Vertex] = [startVertex] startVertex.levelChecked = true //BFS while !queue.isEmpty { let currentVertex = queue.first! for edge in currentVertex.edges { let neighbor = edge.neighbor if !neighbor.levelChecked { neighbor.levelChecked = true neighbor.level = currentVertex.level + 1 queue.append(neighbor) } } queue.removeFirst() } } public func findShortestPathsWithVisualization(completion: () -> Void) { guard let startVertex = self.startVertex else { assertionFailure("start vertex is nil") return } clearCache() startVertex.pathLengthFromStart = 0 startVertex.pathVerticesFromStart.append(startVertex) var currentVertex: Vertex? = startVertex var totalVertices = _vertices breakableLoop: while let vertex = currentVertex { totalVertices.remove(vertex) while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } DispatchQueue.main.async { vertex.setVisitedColor() } usleep(750000) vertex.visited = true let filteredEdges = vertex.edges.filter { !$0.neighbor.visited } for edge in filteredEdges { let neighbor = edge.neighbor let weight = edge.weight let edgeRepresentation = edge.edgeRepresentation while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } DispatchQueue.main.async { edgeRepresentation?.setCheckingColor() neighbor.setCheckingPathColor() self.delegate?.willCompareVertices(startVertexPathLength: vertex.pathLengthFromStart, edgePathLength: weight, endVertexPathLength: neighbor.pathLengthFromStart) } usleep(_visualizationOneSleepDuration) let theoreticNewWeight = vertex.pathLengthFromStart + weight if theoreticNewWeight < neighbor.pathLengthFromStart { while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } neighbor.pathLengthFromStart = theoreticNewWeight neighbor.pathVerticesFromStart = vertex.pathVerticesFromStart neighbor.pathVerticesFromStart.append(neighbor) } usleep(_visualizationOneSleepDuration) DispatchQueue.main.async { self.delegate?.didFinishCompare() edge.edgeRepresentation?.setDefaultColor() edge.neighbor.setDefaultColor() } usleep(_visualizationOneSleepDuration) } if totalVertices.isEmpty { currentVertex = nil break } currentVertex = totalVertices.min { $0.pathLengthFromStart < $1.pathLengthFromStart } } if stopVisualization == true { DispatchQueue.main.async { self.delegate?.didStop() } } else { completion() } } public func parseNeighborsFor(vertex: Vertex, completion: @escaping () -> ()) { DispatchQueue.main.async { vertex.setVisitedColor() } DispatchQueue.global(qos: .background).async { vertex.visited = true let nonVisitedVertices = self._vertices.filter { $0.visited == false } if nonVisitedVertices.isEmpty { self.state = .completed DispatchQueue.main.async { self.delegate?.didCompleteGraphParsing() } return } let filteredEdges = vertex.edges.filter { !$0.neighbor.visited } breakableLoop: for edge in filteredEdges { while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } let weight = edge.weight let neighbor = edge.neighbor DispatchQueue.main.async { edge.neighbor.setCheckingPathColor() edge.edgeRepresentation?.setCheckingColor() self.delegate?.willCompareVertices(startVertexPathLength: vertex.pathLengthFromStart, edgePathLength: weight, endVertexPathLength: neighbor.pathLengthFromStart) } usleep(self._interactiveOneSleepDuration) let theoreticNewWeight = vertex.pathLengthFromStart + weight if theoreticNewWeight < neighbor.pathLengthFromStart { while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } neighbor.pathLengthFromStart = theoreticNewWeight neighbor.pathVerticesFromStart = vertex.pathVerticesFromStart neighbor.pathVerticesFromStart.append(neighbor) } usleep(self._interactiveOneSleepDuration) while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } DispatchQueue.main.async { self.delegate?.didFinishCompare() edge.neighbor.setDefaultColor() edge.edgeRepresentation?.setDefaultColor() } usleep(self._interactiveOneSleepDuration) } if self.stopVisualization == true { DispatchQueue.main.async { self.delegate?.didStop() } } else { let nextVertexPathLength = nonVisitedVertices.sorted { $0.pathLengthFromStart < $1.pathLengthFromStart }.first!.pathLengthFromStart self.nextVertices = nonVisitedVertices.filter { $0.pathLengthFromStart == nextVertexPathLength } completion() } } } public func didTapVertex(vertex: Vertex) { if nextVertices.contains(vertex) { delegate?.willStartVertexNeighborsChecking() state = .parsing parseNeighborsFor(vertex: vertex) { self.state = .interactiveVisualization self.delegate?.didFinishVertexNeighborsChecking() } } else { self.delegate?.didTapWrongVertex() } } }
22236069ff52f0ee613740fdf2bec5b2
35.877419
147
0.540238
false
false
false
false
nalck/Barliman
refs/heads/master
cocoa/Barliman/AppDelegate.swift
mit
1
// // AppDelegate.swift // Barliman // // Created by William Byrd on 5/14/16. // Copyright © 2016 William E. Byrd. // Released under MIT License (see LICENSE file) import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var semanticsWindowController: SemanticsWindowController? var editorWindowController: EditorWindowController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Create window controllers with XIB files of the same name let semanticsWindowController = SemanticsWindowController() let editorWindowController = EditorWindowController() semanticsWindowController.editorWindowController = editorWindowController editorWindowController.semanticsWindowController = semanticsWindowController // Put the windows of the controllers on screen semanticsWindowController.showWindow(self) editorWindowController.showWindow(self) // Set the property to point to the window controllers self.semanticsWindowController = semanticsWindowController self.editorWindowController = editorWindowController } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application editorWindowController!.cleanup() semanticsWindowController!.cleanup() } }
9a75fe294e8da9c9a332b1311e604f97
33.634146
84
0.734507
false
false
false
false
futurechallenger/MVVM
refs/heads/master
MVVMTests/ViewModelTest.swift
mit
1
// // ViewModelTest.swift // MVVM // // Created by Bruce Lee on 9/12/14. // Copyright (c) 2014 Dynamic Cell. All rights reserved. // import UIKit import XCTest class ViewModelTest: XCTestCase { var person: Person! override func setUp() { super.setUp() var salutation = "Dr." var firstName = "first" var lastName = "last" var birthDate = NSDate(timeIntervalSince1970: 0) self.person = Person(salutation: salutation, firstName: firstName, lastName: lastName, birthDate: birthDate) } func testUserSalutation(){ var viewModel = PersonViewModel(person: self.person) XCTAssert(viewModel.nameText! == "Dr. first last" , "use salutation available \(viewModel.nameText!)") } func testNoSalutation(){ var localPerson = Person(salutation: nil, firstName: "first", lastName: "last", birthDate: NSDate(timeIntervalSince1970: 0)) var viewModel = PersonViewModel(person: localPerson) XCTAssert(viewModel.nameText! == "first last", "should not use salutation \(viewModel.nameText!)") } func testBirthDateFormat(){ var viewModel = PersonViewModel(person: self.person) XCTAssert(viewModel.birthDateText! == "Thursday January 1, 1970", "date \(viewModel.birthDateText!)") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } }
5727f8df53822d95d0af194693ad7ee2
31.730769
132
0.649824
false
true
false
false
Barry-Wang/iOS-Animation-Guide-Swift
refs/heads/master
Animation-Guide2-GooeySlideMenu/Animation-Guide2-GooeySlideMenu/ViewController.swift
apache-2.0
1
// // ViewController.swift // Animation-Guide2-GooeySlideMenu // // Created by barryclass on 15/11/19. // Copyright © 2015年 barry. All rights reserved. // import UIKit class ViewController: UIViewController { var menu:YMGooeySlideMenu? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.yellowColor() // Do any additional setup after loading the view, typically from a nib. let button = UIButton(type: UIButtonType.Custom) button.frame = CGRectMake(300, 100, 30, 30) button.backgroundColor = UIColor.greenColor() button.setTitle("123", forState: UIControlState.Normal) button.addTarget(self, action: "triiger", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func triiger() { if self.menu == nil { self.menu = YMGooeySlideMenu(titles: ["Hello"]) } self.menu!.triggeredMenu() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
137bb94769331d09dea78906368157c8
22.4
98
0.626068
false
false
false
false