repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
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
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Sawtooth Wave Oscillator Operation.xcplaygroundpage/Contents.swift
mit
1
//: ## Sawtooth Wave Oscillator Operation //: ### Maybe the most annoying sound ever. Sorry. import XCPlayground import AudioKit //: Set up the operations that will be used to make a generator node let generator = AKOperationGenerator() { _ in let freq = AKOperation.jitter(amplitude: 200, minimumFrequency: 1, maximumFrequency: 10) + 200 let amp = AKOperation.randomVertexPulse(minimum: 0, maximum: 0.3, updateFrequency: 1) return AKOperation.sawtoothWave(frequency: freq, amplitude: amp) } AudioKit.output = generator AudioKit.start() generator.start() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
1892213e61bc098aa8e573595711a30e
32.368421
98
0.76183
false
false
false
false
jkolb/midnightbacon
refs/heads/master
MidnightBacon/Modules/Main/MainFlowController.swift
mit
1
// // MainFlowController.swift // MidnightBacon // // Copyright (c) 2015 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 UIKit import Common class MainFlowController : TabFlowController { weak var factory: MainFactory! var debugFlowController: DebugFlowController! var subredditsFlowController: SubredditsFlowController! var accountsFlowController: AccountsFlowController! var messagesFlowController: MessagesFlowController! var tabController: TabBarController! override func loadViewController() { tabController = TabBarController() tabBarController = tabController // Fix this! viewController = tabController } override func viewControllerDidLoad() { tabBarController.delegate = self tabBarController.viewControllers = [ startSubredditsFlow(), startMessagesFlow(), startAccountsFlow(), ] } func startSubredditsFlow() -> UIViewController { subredditsFlowController = factory.subredditsFlowController() let viewController = subredditsFlowController.start() viewController.title = "Subreddits" viewController.tabBarItem = UITabBarItem(title: "Subreddits", image: UIImage(named: "subreddits_unselected"), selectedImage: UIImage(named: "subreddits_selected")) return viewController } func startAccountsFlow() -> UIViewController { accountsFlowController = factory.accountsFlowController() let viewController = accountsFlowController.start() viewController.title = "Accounts" viewController.tabBarItem = UITabBarItem(title: "Accounts", image: UIImage(named: "accounts_unselected"), selectedImage: UIImage(named: "accounts_selected")) return viewController } func startMessagesFlow() -> UIViewController { messagesFlowController = factory.messagesFlowController() let viewController = messagesFlowController.start() viewController.title = "Messages" viewController.tabBarItem = UITabBarItem(title: "Messages", image: UIImage(named: "messages_unselected"), selectedImage: UIImage(named: "messages_selected")) return viewController } } extension MainFlowController : TabBarControllerDelegate { func tabBarControllerDidDetectShake(tabBarController: TabBarController) { if debugFlowController == nil { debugFlowController = DebugFlowController() debugFlowController.factory = factory debugFlowController.delegate = self } if debugFlowController.canStart { presentAndStartFlow(debugFlowController, animated: true, completion: nil) } } } extension MainFlowController : DebugFlowControllerDelegate { func debugFlowControllerDidCancel(debugFlowController: DebugFlowController) { debugFlowController.stopAnimated(true) { [weak self] in self?.debugFlowController = nil } } }
2e4b915ae3e99f860564851bf4be9e08
39.98
171
0.717423
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
refs/heads/master
TheMovieManager-v2/TheMovieManager/TMDBAuthViewController.swift
mit
1
// // TMDBAuthViewController.swift // TheMovieManager // // Created by Jarrod Parkes on 2/11/15. // Copyright (c) 2015 Jarrod Parkes. All rights reserved. // import UIKit // MARK: - TMDBAuthViewController: UIViewController class TMDBAuthViewController: UIViewController { // MARK: Properties var urlRequest: NSURLRequest? = nil var requestToken: String? = nil var completionHandlerForView: ((success: Bool, errorString: String?) -> Void)? = nil // MARK: Outlets @IBOutlet weak var webView: UIWebView! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() webView.delegate = self navigationItem.title = "TheMovieDB Auth" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(cancelAuth)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let urlRequest = urlRequest { webView.loadRequest(urlRequest) } } // MARK: Cancel Auth Flow func cancelAuth() { dismissViewControllerAnimated(true, completion: nil) } } // MARK: - TMDBAuthViewController: UIWebViewDelegate extension TMDBAuthViewController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { if webView.request!.URL!.absoluteString == "\(TMDBClient.Constants.AuthorizationURL)\(requestToken!)/allow" { dismissViewControllerAnimated(true) { self.completionHandlerForView!(success: true, errorString: nil) } } } }
f332cc9efadd66440c6fa2d15401bfe3
25.421875
135
0.640237
false
false
false
false
mperovic/my41
refs/heads/master
my41/Classes/PreferencesMenu.swift
bsd-3-clause
1
// // PreferencesMenu.swift // my41 // // Created by Miroslav Perovic on 11/16/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation import Cocoa class PreferencesMenuViewController: NSViewController { var calculatorView: SelectedPreferencesView? var modsView: SelectedPreferencesView? var preferencesContainerViewController: PreferencesContainerViewController? @IBOutlet weak var menuView: NSView! override func viewWillAppear() { } override func viewDidLayout() { if calculatorView != nil { calculatorView?.removeFromSuperview() } calculatorView = SelectedPreferencesView( frame: CGRect( x: 0.0, y: self.menuView.frame.height - 38.0, width: 184.0, height: 24.0 ) ) calculatorView?.text = "Calculator" calculatorView?.selected = true self.menuView.addSubview(calculatorView!) if modsView != nil { modsView?.removeFromSuperview() } modsView = SelectedPreferencesView( frame: CGRect( x: 0.0, y: self.menuView.frame.height - 65.0, width: 184.0, height: 24.0 ) ) modsView?.text = "MODs" modsView?.selected = false self.menuView.addSubview(modsView!) } // MARK: Actions @IBAction func selectCalculatorAction(sender: AnyObject) { calculatorView?.selected = true modsView?.selected = false calculatorView!.setNeedsDisplay(calculatorView!.bounds) modsView!.setNeedsDisplay(modsView!.bounds) preferencesContainerViewController?.loadPreferencesCalculatorViewController() } @IBAction func selectModAction(sender: AnyObject) { calculatorView?.selected = false modsView?.selected = true calculatorView!.setNeedsDisplay(calculatorView!.bounds) modsView!.setNeedsDisplay(modsView!.bounds) preferencesContainerViewController?.loadPreferencesModsViewController() } } class PreferencesMenuView: NSView { override func awakeFromNib() { let viewLayer: CALayer = CALayer() viewLayer.backgroundColor = CGColor(red: 0.9843, green: 0.9804, blue: 0.9725, alpha: 1.0) self.wantsLayer = true self.layer = viewLayer } } //MARK: - class PreferencesMenuLabelView: NSView { override func awakeFromNib() { let viewLayer: CALayer = CALayer() viewLayer.backgroundColor = CGColor(red: 0.8843, green: 0.8804, blue: 0.8725, alpha: 1.0) self.wantsLayer = true self.layer = viewLayer } } class SelectedPreferencesView: NSView { var text: NSString? var selected: Bool? override func draw(_ dirtyRect: NSRect) { //// Color Declarations let backColor = NSColor(calibratedRed: 0.1569, green: 0.6157, blue: 0.8902, alpha: 0.95) let textColor = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 1) let font = NSFont(name: "Helvetica Bold", size: 14.0) let textRect: NSRect = NSMakeRect(5, 3, 125, 18) let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle textStyle.alignment = .left if selected! { //// Rectangle Drawing let rectangleCornerRadius: CGFloat = 5 let rectangleRect = NSMakeRect(0, 0, 184, 24) let rectangleInnerRect = NSInsetRect(rectangleRect, rectangleCornerRadius, rectangleCornerRadius) let rectanglePath = NSBezierPath() rectanglePath.move(to: NSMakePoint(NSMinX(rectangleRect), NSMinY(rectangleRect))) rectanglePath.appendArc( withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMinY(rectangleInnerRect)), radius: rectangleCornerRadius, startAngle: 270, endAngle: 360 ) rectanglePath.appendArc( withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMaxY(rectangleInnerRect)), radius: rectangleCornerRadius, startAngle: 0, endAngle: 90 ) rectanglePath.line(to: NSMakePoint(NSMinX(rectangleRect), NSMaxY(rectangleRect))) rectanglePath.close() backColor.setFill() rectanglePath.fill() if let actualFont = font { let textFontAttributes = [ NSAttributedString.Key.font: actualFont, NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.paragraphStyle: textStyle ] text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes) } } else { if let actualFont = font { let textFontAttributes = [ NSAttributedString.Key.font: actualFont, NSAttributedString.Key.foregroundColor: backColor, NSAttributedString.Key.paragraphStyle: textStyle ] text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes) } } } }
483dd94fdba062d819f89515d2fe5a3c
27.538462
100
0.728212
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/Foundation/Foundation.swift
apache-2.0
27
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import CoreGraphics //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // These conformances should be located in the `ObjectiveC` module, but they can't // be placed there because string bridging is not available there. extension NSObject : CustomStringConvertible {} extension NSObject : CustomDebugStringConvertible {} public let NSNotFound: Int = .max //===----------------------------------------------------------------------===// // NSLocalizedString //===----------------------------------------------------------------------===// /// Returns a localized string, using the main bundle if one is not specified. public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value:value, table:tableName) } //===----------------------------------------------------------------------===// // NSLog //===----------------------------------------------------------------------===// public func NSLog(_ format: String, _ args: CVarArg...) { withVaList(args) { NSLogv(format, $0) } } //===----------------------------------------------------------------------===// // AnyHashable //===----------------------------------------------------------------------===// extension AnyHashable : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSObject { // This is unprincipled, but pretty much any object we'll encounter in // Swift is NSObject-conforming enough to have -hash and -isEqual:. return unsafeBitCast(base as AnyObject, to: NSObject.self) } public static func _forceBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) { result = AnyHashable(x) } public static func _conditionallyBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSObject? ) -> AnyHashable { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty string. if _slowPath(source == nil) { return AnyHashable(String()) } return AnyHashable(source!) } } //===----------------------------------------------------------------------===// // CVarArg for bridged types //===----------------------------------------------------------------------===// extension CVarArg where Self: _ObjectiveCBridgeable { /// Default implementation for bridgeable types. public var _cVarArgEncoding: [Int] { let object = self._bridgeToObjectiveC() _autorelease(object) return _encodeBitsAsWords(object) } }
7d067f0e2da0cffdfa1198aa41bb328e
35.391753
82
0.504816
false
false
false
false
L3-DANT/findme-app
refs/heads/master
findme/Service/JsonSerializer.swift
mit
1
// // JsonSerializer.swift // findme // // Created by Maxime Signoret on 29/05/16. // Copyright © 2016 Maxime Signoret. All rights reserved. // import Foundation /// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries. public class JSONSerializer { /** Errors that indicates failures of JSONSerialization - JsonIsNotDictionary: - - JsonIsNotArray: - - JsonIsNotValid: - */ public enum JSONSerializerError: ErrorType { case JsonIsNotDictionary case JsonIsNotArray case JsonIsNotValid } //http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary /** Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"]. - parameter jsonString: JSON string to be converted to a NSDictionary. - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects. - returns: A NSDictionary representation of the JSON string. */ public static func toDictionary(jsonString: String) throws -> NSDictionary { if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary { return dictionary } else { throw JSONSerializerError.JsonIsNotDictionary } } /** Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary. - parameter jsonString: The JSON string to be converted to an NSArray - throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object. - returns: NSArray representation of the JSON objects. */ public static func toArray(jsonString: String) throws -> NSArray { if let array = try jsonToAnyObject(jsonString) as? NSArray { return array } else { throw JSONSerializerError.JsonIsNotArray } } /** Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray. - parameter jsonString: JSON string to be converted to AnyObject - throws: Throws error of type JSONSerializerError. - returns: Returns the JSON string as AnyObject */ private static func jsonToAnyObject(jsonString: String) throws -> AnyObject? { var any: AnyObject? if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) { do { any = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch let error as NSError { let sError = String(error) NSLog(sError) throw JSONSerializerError.JsonIsNotValid } } return any } /** Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented. - parameter object: The instantiation of any custom class to be represented as JSON. - returns: A string JSON representation of the object. */ public static func toJson(object: Any) -> String { var json = "{" let mirror = Mirror(reflecting: object) var children = [(label: String?, value: Any)]() let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)! children += mirrorChildrenCollection var currentMirror = mirror while let superclassChildren = currentMirror.superclassMirror()?.children { let randomCollection = AnyRandomAccessCollection(superclassChildren)! children += randomCollection currentMirror = currentMirror.superclassMirror()! } var filteredChildren = [(label: String?, value: Any)]() for (optionalPropertyName, value) in children { if !optionalPropertyName!.containsString("notMapped_") { filteredChildren += [(optionalPropertyName, value)] } } let size = filteredChildren.count var index = 0 for (optionalPropertyName, value) in filteredChildren { /*let type = value.dynamicType let typeString = String(type) print("SELF: \(type)")*/ let propertyName = optionalPropertyName! let property = Mirror(reflecting: value) var handledValue = String() if value is Int || value is Double || value is Float || value is Bool { handledValue = String(value ?? "null") } else if let array = value as? [Int?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Double?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Float?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [Bool?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? String(value!) : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String?] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += value != nil ? "\"\(value!)\"" : "null" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? [String] { handledValue += "[" for (index, value) in array.enumerate() { handledValue += "\"\(value)\"" handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if let array = value as? NSArray { handledValue += "[" for (index, value) in array.enumerate() { if !(value is Int) && !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) { handledValue += toJson(value) } else { handledValue += "\(value)" } handledValue += (index < array.count-1 ? ", " : "") } handledValue += "]" } else if property.displayStyle == Mirror.DisplayStyle.Class { handledValue = toJson(value) } else if property.displayStyle == Mirror.DisplayStyle.Optional { let str = String(value) if str != "nil" { handledValue = String(str).substringWithRange(str.startIndex.advancedBy(9)..<str.endIndex.advancedBy(-1)) } else { handledValue = "null" } } else { handledValue = String(value) != "nil" ? "\"\(value)\"" : "null" } json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "") index += 1 } json += "}" return json } }
1eef7a487adf400c1b83fe32386c9339
41.253731
193
0.543099
false
false
false
false
safx/IIJMioKit
refs/heads/swift-2.0
IIJMioKitSample/PacketLogCell.swift
mit
1
// // PacketLogCell.swift // IIJMioKit // // Created by Safx Developer on 2015/05/16. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import UIKit import IIJMioKit class PacketLogCell: UITableViewCell { @IBOutlet weak var date: UILabel! @IBOutlet weak var withCoupon: UILabel! @IBOutlet weak var withoutCoupon: UILabel! private let dateFormatter = NSDateFormatter() var model: MIOPacketLog? { didSet { modelDidSet() } } private func modelDidSet() { dateFormatter.dateFormat = "YYYY-MM-dd" date!.text = dateFormatter.stringFromDate(model!.date) let f = NSByteCountFormatter() f.allowsNonnumericFormatting = false f.allowedUnits = [.UseMB, .UseGB] withCoupon!.text = f.stringFromByteCount(Int64(model!.withCoupon * 1000 * 1000)) withoutCoupon!.text = f.stringFromByteCount(Int64(model!.withoutCoupon * 1000 * 1000)) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
95314a97a1864da43fc003f080fbe3be
26.266667
94
0.667482
false
false
false
false
zxwWei/SwfitZeng
refs/heads/master
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/NewFeature(新特性)/Controller/XWWelcomeVC.swift
apache-2.0
1
// // XWWelcomeVC.swift // XWWeibo // // Created by apple on 15/10/30. // Copyright © 2015年 ZXW. All rights reserved. // import UIKit import SDWebImage class XWWelcomeVC: UIViewController { // 定义底部约束 private var iconBottomConstriant: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() prepareUI() // 有值时进入 if let urlStr = XWUserAccount.loadAccount()?.avatar_large{ // MARK: - 未完成 从网上下载图片 从网络上获取图片资源 iconView.sd_setImageWithURL(NSURL(string: urlStr), placeholderImage: UIImage(named: "avatar_default_big")) } } // MARK: - 当界面出现时,出现动画 override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) iconBottomConstriant?.constant = -(UIScreen.mainScreen().bounds.height - 160) // 有弹簧效果的动画 // usingSpringWithDamping: 值越小弹簧效果越明显 0 - 1 // initialSpringVelocity: 初速度 UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.view.layoutIfNeeded() }, completion: { (_) -> Void in UIView.animateWithDuration(1, animations: { () -> Void in self.welcomeLabel.alpha = 1 }, completion: { (_) -> Void in // MARK: - 当显示完成时做的事 进入访客视图 ((UIApplication.sharedApplication().delegate) as! AppDelegate).switchRootController(true) }) }) } // MARK: - 布局UI private func prepareUI() { // 添加子控件 view.addSubview(bgView) view.addSubview(iconView) view.addSubview(welcomeLabel) bgView.translatesAutoresizingMaskIntoConstraints = false iconView.translatesAutoresizingMaskIntoConstraints = false welcomeLabel.translatesAutoresizingMaskIntoConstraints = false // 添加约束 这是数组 view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : bgView])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : bgView])) // 头像 view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85)) view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85)) // 垂直 底部160 iconBottomConstriant = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160) view.addConstraint(iconBottomConstriant!) // 欢迎归来 // H view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) } // MARK: 准备界面元素 /// 背景图片 private lazy var bgView: UIImageView = UIImageView(image: UIImage(named: "ad_background")) /// 欢迎归来 private lazy var welcomeLabel: UILabel = { let welcomeLabel = UILabel() welcomeLabel.text = "欢迎归来" welcomeLabel.alpha = 0 return welcomeLabel }() /// 头像 private lazy var iconView: UIImageView = { let iconView = UIImageView(image: UIImage(named: "avatar_default_big")) iconView.layer.cornerRadius = 42.5 iconView.clipsToBounds = true return iconView }() }
d94f46472dd989e588f0a8c6f4e7c97a
34.414815
223
0.618072
false
false
false
false
Magiic/FireMock
refs/heads/master
FireMock/FireMockDebug.swift
mit
1
// // FireMockDebug.swift // FireMock // // Created by Haithem Ben harzallah on 08/02/2017. // Copyright © 2017 haithembenharzallah. All rights reserved. // import Foundation /// Quantity information debug. public enum FireMockDebugLevel { case low case high } struct FireMockDebug { static var prefix: String? static var level: FireMockDebugLevel = .high static func debug(message: String, level: FireMockDebugLevel) { if FireMock.debugIsEnabled, (self.level == level || self.level == .high) { print("\(prefix ?? "FireMock ") - \(message)") } } }
2cc69f655f9c72a402e39698f587de65
22.384615
82
0.657895
false
false
false
false
FoodForTech/Handy-Man
refs/heads/1.0.0
HandyMan/HandyMan/HandyManCore/Spring/LoadingView.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit open class LoadingView: UIView { @IBOutlet open weak var indicatorView: SpringView! override open func awakeFromNib() { let animation = CABasicAnimation() animation.keyPath = "transform.rotation.z" animation.fromValue = degreesToRadians(0) animation.toValue = degreesToRadians(360) animation.duration = 0.9 animation.repeatCount = HUGE indicatorView.layer.add(animation, forKey: "") } class func designCodeLoadingView() -> UIView { return Bundle(for: self).loadNibNamed("LoadingView", owner: self, options: nil)![0] as! UIView } } public extension UIView { struct LoadingViewConstants { static let Tag = 1000 } public func showLoading() { if self.viewWithTag(LoadingViewConstants.Tag) != nil { return } // If loading view is already found in current view hierachy, do nothing let loadingXibView = LoadingView.designCodeLoadingView() loadingXibView.frame = self.bounds loadingXibView.tag = LoadingViewConstants.Tag self.addSubview(loadingXibView) loadingXibView.alpha = 0 spring(0.7, animations: { loadingXibView.alpha = 1 }) } public func hideLoading() { if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) { loadingXibView.alpha = 1 springWithCompletion(0.7, animations: { loadingXibView.alpha = 0 //loadingXibView.transform = CGAffineTransformMakeScale(3, 3) }, completion: { (completed) -> Void in loadingXibView.removeFromSuperview() }) } } }
9191d9efbb47eabc9926d5d3f2af830a
35.974026
145
0.686688
false
false
false
false
jriehn/moody-ios-client
refs/heads/master
Moody/Pods/Socket.IO-Client-Swift/SocketIOClientSwift/SocketIOClient.swift
mit
1
// // SocketIOClient.swift // Socket.IO-Swift // // Created by Erik Little on 11/23/14. // // 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 final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient { private var anyHandler:((SocketAnyEvent) -> Void)? private var _closed = false private var _connected = false private var _connecting = false private var currentReconnectAttempt = 0 private var handlers = ContiguousArray<SocketEventHandler>() private var connectParams:[String: AnyObject]? private var _secure = false private var _sid:String? private var _reconnecting = false private var reconnectTimer:NSTimer? let reconnectAttempts:Int! let logType = "SocketClient" var ackHandlers = SocketAckManager() var currentAck = -1 var log = false var waitingData = ContiguousArray<SocketPacket>() var sessionDelegate:NSURLSessionDelegate? public let socketURL:String public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL) public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL) public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL) public var closed:Bool { return _closed } public var connected:Bool { return _connected } public var connecting:Bool { return _connecting } public var engine:SocketEngine? public var nsp = "/" public var opts:[String: AnyObject]? public var reconnects = true public var reconnecting:Bool { return _reconnecting } public var reconnectWait = 10 public var secure:Bool { return _secure } public var sid:String? { return _sid } /** Create a new SocketIOClient. opts can be omitted */ public init(var socketURL:String, opts:[String: AnyObject]? = nil) { if socketURL["https://"].matches().count != 0 { self._secure = true } socketURL = socketURL["http://"] ~= "" socketURL = socketURL["https://"] ~= "" self.socketURL = socketURL self.opts = opts // Set options if let sessionDelegate = opts?["sessionDelegate"] as? NSURLSessionDelegate { self.sessionDelegate = sessionDelegate } if let connectParams = opts?["connectParams"] as? [String: AnyObject] { self.connectParams = connectParams } if let log = opts?["log"] as? Bool { self.log = log } if var nsp = opts?["nsp"] as? String { if nsp != "/" && nsp.hasPrefix("/") { nsp.removeAtIndex(nsp.startIndex) } self.nsp = nsp } if let reconnects = opts?["reconnects"] as? Bool { self.reconnects = reconnects } if let reconnectAttempts = opts?["reconnectAttempts"] as? Int { self.reconnectAttempts = reconnectAttempts } else { self.reconnectAttempts = -1 } if let reconnectWait = opts?["reconnectWait"] as? Int { self.reconnectWait = abs(reconnectWait) } super.init() } public convenience init(socketURL:String, options:[String: AnyObject]?) { self.init(socketURL: socketURL, opts: options) } deinit { SocketLogger.log("Client is being deinit", client: self) engine?.close(fast: true) } private func addEngine() { SocketLogger.log("Adding engine", client: self) engine = SocketEngine(client: self, opts: opts) } /** Closes the socket. Only reopen the same socket if you know what you're doing. Will turn off automatic reconnects. Pass true to fast if you're closing from a background task */ public func close(#fast:Bool) { SocketLogger.log("Closing socket", client: self) reconnects = false _connecting = false _connected = false _reconnecting = false engine?.close(fast: fast) engine = nil } /** Connect to the server. */ public func connect() { connect(timeoutAfter: 0, withTimeoutHandler: nil) } /** Connect to the server. If we aren't connected after timeoutAfter, call handler */ public func connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) { if closed { SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self) _closed = false } else if connected { return } addEngine() engine?.open(opts: connectParams) if timeoutAfter == 0 { return } let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) {[weak self] in if let this = self where !this.connected { this._closed = true this._connecting = false this.engine?.close(fast: true) handler?() } } } private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback { return {[weak self, ack = ++currentAck] timeout, callback in if let this = self { this.ackHandlers.addAck(ack, callback: callback) dispatch_async(this.emitQueue) {[weak this] in this?._emit(event, items, ack: ack) } if timeout != 0 { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) {[weak this] in this?.ackHandlers.timeoutAck(ack) } } } } } func didConnect() { SocketLogger.log("Socket connected", client: self) _closed = false _connected = true _connecting = false _reconnecting = false currentReconnectAttempt = 0 reconnectTimer?.invalidate() reconnectTimer = nil _sid = engine?.sid // Don't handle as internal because something crazy could happen where // we disconnect before it's handled handleEvent("connect", data: nil, isInternalMessage: false) } func didDisconnect(reason:String) { if closed { return } SocketLogger.log("Disconnected: %@", client: self, args: reason) _closed = true _connected = false reconnects = false _connecting = false _reconnecting = false // Make sure the engine is actually dead. engine?.close(fast: true) handleEvent("disconnect", data: [reason], isInternalMessage: true) } /// error public func didError(reason:AnyObject) { SocketLogger.err("%@", client: self, args: reason) handleEvent("error", data: reason as? [AnyObject] ?? [reason], isInternalMessage: true) } /** Same as close */ public func disconnect(#fast:Bool) { close(fast: fast) } /** Send a message to the server */ public func emit(event:String, _ items:AnyObject...) { if !connected { return } dispatch_async(emitQueue) {[weak self] in self?._emit(event, items) } } /** Same as emit, but meant for Objective-C */ public func emit(event:String, withItems items:[AnyObject]) { if !connected { return } dispatch_async(emitQueue) {[weak self] in self?._emit(event, items) } } /** Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add an ack. */ public func emitWithAck(event:String, _ items:AnyObject...) -> OnAckCallback { if !connected { return createOnAck(event, items: items) } return createOnAck(event, items: items) } /** Same as emitWithAck, but for Objective-C */ public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback { if !connected { return createOnAck(event, items: items) } return createOnAck(event, items: items) } private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) { if !connected { return } let packet = SocketPacket(type: nil, data: args, nsp: nsp, id: ack) let str:String SocketParser.parseForEmit(packet) str = packet.createMessageForEvent(event) SocketLogger.log("Emitting: %@", client: self, args: str) if packet.type == SocketPacket.PacketType.BINARY_EVENT { engine?.send(str, withData: packet.binary) } else { engine?.send(str, withData: nil) } } // If the server wants to know that the client received data func emitAck(ack:Int, withData args:[AnyObject]) { dispatch_async(emitQueue) {[weak self] in if let this = self where this.connected { let packet = SocketPacket(type: nil, data: args, nsp: this.nsp, id: ack) let str:String SocketParser.parseForEmit(packet) str = packet.createAck() SocketLogger.log("Emitting Ack: %@", client: this, args: str) if packet.type == SocketPacket.PacketType.BINARY_ACK { this.engine?.send(str, withData: packet.binary) } else { this.engine?.send(str, withData: nil) } } } } public func engineDidClose(reason:String) { _connected = false _connecting = false if closed || !reconnects { didDisconnect(reason) } else if !reconnecting { handleEvent("reconnect", data: [reason], isInternalMessage: true) tryReconnect() } } // Called when the socket gets an ack for something it sent func handleAck(ack:Int, data:AnyObject?) { SocketLogger.log("Handling ack: %@ with data: %@", client: self, args: ack, data ?? "") ackHandlers.executeAck(ack, items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil)) } /** Causes an event to be handled. Only use if you know what you're doing. */ public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false, wantsAck ack:Int? = nil) { // println("Should do event: \(event) with data: \(data)") if !connected && !isInternalMessage { return } SocketLogger.log("Handling event: %@ with data: %@", client: self, args: event, data ?? "") if anyHandler != nil { dispatch_async(dispatch_get_main_queue()) {[weak self] in self?.anyHandler?(SocketAnyEvent(event: event, items: data)) } } for handler in handlers { if handler.event == event { if ack != nil { handler.executeCallback(data, withAck: ack!, withSocket: self) } else { handler.executeCallback(data) } } } } /** Leaves nsp and goes back to / */ public func leaveNamespace() { if nsp != "/" { engine?.send("1/\(nsp)", withData: nil) nsp = "/" } } /** Joins nsp if it is not / */ public func joinNamespace() { SocketLogger.log("Joining namespace", client: self) if nsp != "/" { engine?.send("0/\(nsp)", withData: nil) } } /** Removes handler(s) */ public func off(event:String) { SocketLogger.log("Removing handler for event: %@", client: self, args: event) handlers = handlers.filter {$0.event == event ? false : true} } /** Adds a handler for an event. */ public func on(event:String, callback:NormalCallback) { SocketLogger.log("Adding handler for event: %@", client: self, args: event) let handler = SocketEventHandler(event: event, callback: callback) handlers.append(handler) } /** Adds a handler that will be called on every event. */ public func onAny(handler:(SocketAnyEvent) -> Void) { anyHandler = handler } /** Same as connect */ public func open() { connect() } public func parseSocketMessage(msg:String) { SocketParser.parseSocketMessage(msg, socket: self) } public func parseBinaryData(data:NSData) { SocketParser.parseBinaryData(data, socket: self) } /** Trieds to reconnect to the server. */ public func reconnect() { _connected = false _connecting = false _reconnecting = false engine?.stopPolling() tryReconnect() } // We lost connection and should attempt to reestablish @objc private func tryReconnect() { if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts { didDisconnect("Reconnect Failed") return } else if connected { _connecting = false _reconnecting = false return } if reconnectTimer == nil { SocketLogger.log("Starting reconnect", client: self) _reconnecting = true dispatch_async(dispatch_get_main_queue()) {[weak self] in if let this = self { this.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(this.reconnectWait), target: this, selector: "tryReconnect", userInfo: nil, repeats: true) } } } SocketLogger.log("Trying to reconnect", client: self) handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt], isInternalMessage: true) currentReconnectAttempt++ connect() } }
ae7f5ab07626d2359f6c783c716709fd
30.231518
114
0.556531
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/Person.swift
mit
1
import Foundation public class Person: Thing { /// An additional name for a Person, can be used for a middle name. public var additionalName: String? /// Physical address of the item. public var address: PostalAddressOrText? /// An organization that this person is affiliated with. For example, a /// school/university, a club, or a team. public var affiliation: Organization? /// An organization that the person is an alumni of. /// - **Inverse property**: _alumni_ public var alumniOf: EducationalOrganizationOrOrganization? /// An award won by or for this item. public var awards: [String]? /// Date of birth. public var birthDate: DateOnly? /// The place where the person was born. public var birthPlace: Place? /// The brand(s) associated with a product or service, or the brand(s) /// maintained by an organization or business person. public var brands: [BrandOrOrganization]? /// A child of the person. public var children: [Person]? /// A colleague of the person. public var colleagues: [PersonOrURL]? /// A contact point for a person or organization. public var contactPoints: [ContactPoint]? /// Date of death. public var deathDate: DateOnly? /// The place where the person died. public var deathPlace: Place? /// The Dun & Bradstreet DUNS number for identifying an organization or /// business person. public var duns: String? /// Email address. public var email: String? /// Family name. In the U.S., the last name of an Person. This can be used /// along with givenName instead of the name property. public var familyName: String? /// The fax number. public var faxNumber: String? /// The most generic uni-directional social relation. public var follows: [Person]? /// A person or organization that supports (sponsors) something through some /// kind of financial contribution. public var funder: OrganizationOrPerson? /// Gender of the person. While http://schema.org/Male and /// http://schema.org/Female may be used, text strings are also acceptable /// for people who do not identify as a binary gender. public var gender: GenderOrText? /// Given name. In the U.S., the first name of a Person. This can be used /// along with familyName instead of the name property. public var givenName: String? /// The Global Location Number (GLN, sometimes also referred to as /// International Location Number or ILN) of the respective organization, /// person, or place. The GLN is a 13-digit number used to identify parties /// and physical locations. public var globalLocationNumber: String? /// Indicates an OfferCatalog listing for this Organization, Person, or /// Service. public var offerCatalog: OfferCatalog? /// Points-of-Sales operated by the organization or person. public var pointsOfSales: [Place]? /// The height of the item. public var height: DistanceOrQuantitativeValue? /// A contact location for a person's residence. public var homeLocation: ContactPointOrPlace? /// An honorific prefix preceding a Person's name such as Dr/Mrs/Mr. public var honorificPrefix: String? /// An honorific suffix preceding a Person's name such as M.D. /PhD/MSCSW. public var honorificSuffix: String? /// The International Standard of Industrial Classification of All Economic /// Activities (ISIC), Revision 4 code for a particular organization, /// business person, or place. public var isicV4: String? /// The job title of the person (for example, Financial Manager). public var jobTitle: String? /// The most generic bi-directional social/work relation. public var knows: [Person]? /// A pointer to products or services offered by the organization or person. /// - **Inverse property**: _offeredBy_ public var makesOffer: [Offer]? /// An Organization (or ProgramMembership) to which this Person or /// Organization belongs. /// - **Inverse property**: _member_ public var memberOf: [OrganizationOrProgramMembership]? /// The North American Industry Classification System (NAICS) code for a /// particular organization or business person. public var naics: String? /// Nationality of the person. public var nationality: Country? /// The total financial value of the person as calculated by subtracting /// assets from liabilities. public var netWorth: MonetaryAmountOrPriceSpecification? /// The Person's occupation. For past professions, use Role for expressing /// dates. public var occupation: Occupation? /// Products owned by the organization or person. public var owns: [ProductOrService]? /// A parent of this person. public var parents: [Person]? /// Event that this person is a performer or participant in. public var performerIn: Event? /// The publishingPrinciples property indicates (typically via URL) a /// document describing the editorial principles of an Organization (or /// individual e.g. a Person writing a blog) that relate to their activities /// as a publisher, e.g. ethics or diversity policies. When applied to a /// CreativeWork (e.g. NewsArticle) the principles are those of the party /// primarily responsible for the creation of the CreativeWork. /// While such policies are most typically expressed in natural language, /// sometimes related information (e.g. indicating a funder) can be /// expressed using schema.org terminology. public var publishingPrinciples: CreativeWorkOrURL? /// The most generic familial relation. public var relatedTo: [Person]? /// A pointer to products or services sought by the organization or person /// (demand). public var seeks: [Demand]? /// A sibling of the person. public var siblings: [Person]? /// A person or organization that supports a thing through a pledge, /// promise, or financial contribution. e.g. a sponsor of a Medical Study or /// a corporate sponsor of an event. public var sponsor: OrganizationOrPerson? /// The person's spouse. public var spouse: Person? /// The Tax / Fiscal ID of the organization or person, e.g. the TIN in the /// US or the CIF/NIF in Spain. public var taxID: String? /// The telephone number. public var telephone: String? /// The Value-added Tax ID of the organization or person. public var vatID: String? /// The weight of the product or person. public var weight: QuantitativeValue? /// A contact location for a person's place of work. public var workLocation: ContactPointOrPlace? /// Organizations that the person works for. public var worksFor: [Organization]? internal enum PersonCodingKeys: String, CodingKey { case additionalName case address case affiliation case alumniOf case awards = "award" case birthDate case birthPlace case brands = "brand" case children case colleagues = "colleague" case contactPoints = "contactPoint" case deathDate case deathPlace case duns case email case familyName case faxNumber case follows case funder case gender case givenName case globalLocationNumber case offerCatalog = "hasOfferCatalog" case pointsOfSales = "hasPOS" case height case homeLocation case honorificPrefix case honorificSuffix case isicV4 case jobTitle case knows case makesOffer case memberOf case naics case nationality case netWorth case occupation = "hasOccupation" case owns case parents = "parent" case performerIn case publishingPrinciples case relatedTo case seeks case siblings = "sibling" case sponsor case spouse case taxID case telephone case vatID case weight case workLocation case worksFor } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: PersonCodingKeys.self) additionalName = try container.decodeIfPresent(String.self, forKey: .additionalName) address = try container.decodeIfPresent(PostalAddressOrText.self, forKey: .address) affiliation = try container.decodeIfPresent(Organization.self, forKey: .affiliation) alumniOf = try container.decodeIfPresent(EducationalOrganizationOrOrganization.self, forKey: .alumniOf) awards = try container.decodeIfPresent([String].self, forKey: .awards) birthDate = try container.decodeIfPresent(DateOnly.self, forKey: .birthDate) birthPlace = try container.decodeIfPresent(Place.self, forKey: .birthPlace) brands = try container.decodeIfPresent([BrandOrOrganization].self, forKey: .brands) children = try container.decodeIfPresent([Person].self, forKey: .children) colleagues = try container.decodeIfPresent([PersonOrURL].self, forKey: .colleagues) contactPoints = try container.decodeIfPresent([ContactPoint].self, forKey: .contactPoints) deathDate = try container.decodeIfPresent(DateOnly.self, forKey: .deathDate) deathPlace = try container.decodeIfPresent(Place.self, forKey: .deathPlace) duns = try container.decodeIfPresent(String.self, forKey: .duns) email = try container.decodeIfPresent(String.self, forKey: .email) familyName = try container.decodeIfPresent(String.self, forKey: .familyName) faxNumber = try container.decodeIfPresent(String.self, forKey: .faxNumber) follows = try container.decodeIfPresent([Person].self, forKey: .follows) funder = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .funder) gender = try container.decodeIfPresent(GenderOrText.self, forKey: .gender) givenName = try container.decodeIfPresent(String.self, forKey: .givenName) globalLocationNumber = try container.decodeIfPresent(String.self, forKey: .globalLocationNumber) offerCatalog = try container.decodeIfPresent(OfferCatalog.self, forKey: .offerCatalog) pointsOfSales = try container.decodeIfPresent([Place].self, forKey: .pointsOfSales) height = try container.decodeIfPresent(DistanceOrQuantitativeValue.self, forKey: .height) homeLocation = try container.decodeIfPresent(ContactPointOrPlace.self, forKey: .homeLocation) honorificPrefix = try container.decodeIfPresent(String.self, forKey: .honorificPrefix) honorificSuffix = try container.decodeIfPresent(String.self, forKey: .honorificSuffix) isicV4 = try container.decodeIfPresent(String.self, forKey: .isicV4) jobTitle = try container.decodeIfPresent(String.self, forKey: .jobTitle) knows = try container.decodeIfPresent([Person].self, forKey: .knows) makesOffer = try container.decodeIfPresent([Offer].self, forKey: .makesOffer) memberOf = try container.decodeIfPresent([OrganizationOrProgramMembership].self, forKey: .memberOf) naics = try container.decodeIfPresent(String.self, forKey: .naics) nationality = try container.decodeIfPresent(Country.self, forKey: .nationality) netWorth = try container.decodeIfPresent(MonetaryAmountOrPriceSpecification.self, forKey: .netWorth) occupation = try container.decodeIfPresent(Occupation.self, forKey: .occupation) owns = try container.decodeIfPresent([ProductOrService].self, forKey: .owns) parents = try container.decodeIfPresent([Person].self, forKey: .parents) performerIn = try container.decodeIfPresent(Event.self, forKey: .performerIn) publishingPrinciples = try container.decodeIfPresent(CreativeWorkOrURL.self, forKey: .publishingPrinciples) relatedTo = try container.decodeIfPresent([Person].self, forKey: .relatedTo) seeks = try container.decodeIfPresent([Demand].self, forKey: .seeks) siblings = try container.decodeIfPresent([Person].self, forKey: .siblings) sponsor = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .sponsor) spouse = try container.decodeIfPresent(Person.self, forKey: .spouse) taxID = try container.decodeIfPresent(String.self, forKey: .taxID) telephone = try container.decodeIfPresent(String.self, forKey: .telephone) vatID = try container.decodeIfPresent(String.self, forKey: .vatID) weight = try container.decodeIfPresent(QuantitativeValue.self, forKey: .weight) workLocation = try container.decodeIfPresent(ContactPointOrPlace.self, forKey: .workLocation) worksFor = try container.decodeIfPresent([Organization].self, forKey: .worksFor) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PersonCodingKeys.self) try container.encodeIfPresent(additionalName, forKey: .additionalName) try container.encodeIfPresent(address, forKey: .address) try container.encodeIfPresent(affiliation, forKey: .affiliation) try container.encodeIfPresent(alumniOf, forKey: .alumniOf) try container.encodeIfPresent(awards, forKey: .awards) try container.encodeIfPresent(birthDate, forKey: .birthDate) try container.encodeIfPresent(birthPlace, forKey: .birthPlace) try container.encodeIfPresent(brands, forKey: .brands) try container.encodeIfPresent(children, forKey: .children) try container.encodeIfPresent(colleagues, forKey: .colleagues) try container.encodeIfPresent(contactPoints, forKey: .contactPoints) try container.encodeIfPresent(deathDate, forKey: .deathDate) try container.encodeIfPresent(deathPlace, forKey: .deathPlace) try container.encodeIfPresent(duns, forKey: .duns) try container.encodeIfPresent(email, forKey: .email) try container.encodeIfPresent(familyName, forKey: .familyName) try container.encodeIfPresent(faxNumber, forKey: .faxNumber) try container.encodeIfPresent(follows, forKey: .follows) try container.encodeIfPresent(funder, forKey: .funder) try container.encodeIfPresent(gender, forKey: .gender) try container.encodeIfPresent(givenName, forKey: .givenName) try container.encodeIfPresent(globalLocationNumber, forKey: .globalLocationNumber) try container.encodeIfPresent(offerCatalog, forKey: .offerCatalog) try container.encodeIfPresent(pointsOfSales, forKey: .pointsOfSales) try container.encodeIfPresent(height, forKey: .height) try container.encodeIfPresent(homeLocation, forKey: .homeLocation) try container.encodeIfPresent(honorificPrefix, forKey: .honorificPrefix) try container.encodeIfPresent(honorificSuffix, forKey: .honorificSuffix) try container.encodeIfPresent(isicV4, forKey: .isicV4) try container.encodeIfPresent(jobTitle, forKey: .jobTitle) try container.encodeIfPresent(knows, forKey: .knows) try container.encodeIfPresent(makesOffer, forKey: .makesOffer) try container.encodeIfPresent(memberOf, forKey: .memberOf) try container.encodeIfPresent(naics, forKey: .naics) try container.encodeIfPresent(nationality, forKey: .nationality) try container.encodeIfPresent(netWorth, forKey: .netWorth) try container.encodeIfPresent(occupation, forKey: .occupation) try container.encodeIfPresent(owns, forKey: .owns) try container.encodeIfPresent(parents, forKey: .parents) try container.encodeIfPresent(performerIn, forKey: .performerIn) try container.encodeIfPresent(publishingPrinciples, forKey: .publishingPrinciples) try container.encodeIfPresent(relatedTo, forKey: .relatedTo) try container.encodeIfPresent(seeks, forKey: .seeks) try container.encodeIfPresent(siblings, forKey: .siblings) try container.encodeIfPresent(sponsor, forKey: .sponsor) try container.encodeIfPresent(spouse, forKey: .spouse) try container.encodeIfPresent(taxID, forKey: .taxID) try container.encodeIfPresent(telephone, forKey: .telephone) try container.encodeIfPresent(vatID, forKey: .vatID) try container.encodeIfPresent(weight, forKey: .weight) try container.encodeIfPresent(workLocation, forKey: .workLocation) try container.encodeIfPresent(worksFor, forKey: .worksFor) try super.encode(to: encoder) } }
05d8ae043c0370a20b9e2774e7ea128a
45.248649
115
0.695185
false
false
false
false
sunkanmi-akintoye/todayjournal
refs/heads/master
weather-journal/Controllers/CreatePostViewController.swift
mit
1
// // CreatePostViewController.swift // weather-journal // // Created by Luke Geiger on 6/29/15. // Copyright (c) 2015 Luke J Geiger. All rights reserved. // import UIKit class CreatePostViewController: UIViewController,UITextViewDelegate { var post:Post! private var textView:UITextView! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.setupInterface() } private func setupInterface(){ self.view.backgroundColor = UIColor.whiteColor() if (self.post == nil){ self.post = Post() self.post.creationDate = NSDate() self.post.text = ""; } else{ self.navigationItem.title = self.post.displayTitle() } self.fetchWeather(){ (result: WeatherCondition?) in self.post.createdBy = PFUser.currentUser()! if (result != nil){ self.post.temperatureF = result!.feelsLikeF as String self.post.weather = result!.weather as String } else{ self.post.temperatureF = "-" self.post.weather = "Unknown" } } self.textView = UITextView(frame: CGRectMake(0, 0, self.view.width, self.view.height-216)) self.textView?.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth self.textView?.delegate = self; self.textView?.tintColor = UIColor.appBlueColor() self.textView.font = UIFont.appFontOfSize(14) self.textView.textColor = UIColor.appDarkGreyColor() self.textView.text = self.post!.text; self.view.addSubview(self.textView!) self.switchToEditingMode(true) } // MARK: - Actions override func viewWillDisappear(animated:Bool) { var length = count(self.textView.text) if (length > 0){ self.post.text = self.textView.text self.dismissKeyboard() self.post.pinInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if (success) { // The object has been saved. } else { // There was a problem, check error.description } super.viewWillDisappear(animated) } self.post.saveEventually(nil) } } private func switchToEditingMode(flag:Bool){ if (flag == true){ self.showKeyboard() } else{ self.dismissKeyboard() } } func dismissKeyboard(){ self.view.endEditing(true) let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 20, 20) button.setImage(UIImage(named:"icon-keyboard-up"), forState: UIControlState.Normal) button.addTarget(self, action: "showKeyboard", forControlEvents: UIControlEvents.TouchUpInside) var rightBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: button) self.navigationItem.rightBarButtonItem = rightBarButtonItem } func showKeyboard(){ self.textView.becomeFirstResponder() let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 20, 20) button.setImage(UIImage(named:"icon-keyboard-down"), forState: UIControlState.Normal) button.addTarget(self, action: "dismissKeyboard", forControlEvents: UIControlEvents.TouchUpInside) var rightBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: button) self.navigationItem.rightBarButtonItem = rightBarButtonItem } // MARK: - Wunderground API private func fetchWeather(completion: (result: WeatherCondition?) -> Void){ PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in let manager = AFHTTPRequestOperationManager() var locationParams:NSDictionary = [ "lat" : NSString(format:"%f", geoPoint!.latitude), "lng" : NSString(format:"%f", geoPoint!.longitude) ] let endPoint = self.weatherUnderGroundGeolookupEndpoint(locationParams) manager.GET(endPoint, parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in let geojsonResult:NSDictionary = responseObject as! NSDictionary if ((geojsonResult.objectForKey("location") != nil)){ let locationDict = geojsonResult.objectForKey("location") as! NSDictionary let weatherRequestURL = locationDict.objectForKey("requesturl") as! String let weatherRequestURLJson = weatherRequestURL.stringByReplacingOccurrencesOfString(".html", withString: ".json", options: NSStringCompareOptions.LiteralSearch, range: nil) let conditionsEndpoint = self.weatherUnderGroundConditionsEndpoint(weatherRequestURLJson) manager.GET(conditionsEndpoint, parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in var conditionjsonResult:NSDictionary = responseObject as! NSDictionary var currentObservationDict = conditionjsonResult.objectForKey("current_observation") as! NSDictionary completion(result: WeatherCondition(jsonDict: currentObservationDict)) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error:" + error.localizedDescription) completion(result: nil) }) } else{ println("Could not get location:") completion(result: nil) } }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error:" + error.localizedDescription) completion(result: nil) }) } } private func weatherUnderGroundRootAPIString()->String{ return "http://api.wunderground.com/api/c8d9b1271b46e705/" } private func weatherUnderGroundConditionsEndpoint(cityEndpoint:String)->String{ return weatherUnderGroundRootAPIString() + "conditions/q/" + cityEndpoint } private func weatherUnderGroundGeolookupEndpoint(locationDict:NSDictionary)->String{ var latString = locationDict.objectForKey("lat") as! String var lngString = locationDict.objectForKey("lng") as! String return self.weatherUnderGroundRootAPIString() + "geolookup/q/" + latString + "," + lngString + ".json" } }
bd0cc4e6e0bf2e5843f22cfb87b32878
38.801075
195
0.574902
false
false
false
false
Ivacker/swift
refs/heads/master
test/SILGen/decls.swift
apache-2.0
10
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s // CHECK-LABEL: sil hidden @_TF5decls11void_returnFT_T_ // CHECK: = tuple // CHECK: return func void_return() { } // CHECK-LABEL: sil hidden @_TF5decls14typealias_declFT_T_ func typealias_decl() { typealias a = Int } // CHECK-LABEL: sil hidden @_TF5decls15simple_patternsFT_T_ func simple_patterns() { _ = 4 var _ : Int } // CHECK-LABEL: sil hidden @_TF5decls13named_patternFT_Si func named_pattern() -> Int { var local_var : Int = 4 var defaulted_var : Int // Defaults to zero initialization return local_var + defaulted_var } func MRV() -> (Int, Float, (), Double) {} // CHECK-LABEL: sil hidden @_TF5decls14tuple_patternsFT_T_ func tuple_patterns() { var (a, b) : (Int, Float) // CHECK: [[AADDR1:%[0-9]+]] = alloc_box $Int // CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[AADDR1]]#1 // CHECK: [[BADDR1:%[0-9]+]] = alloc_box $Float // CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[BADDR1]]#1 var (c, d) = (a, b) // CHECK: [[CADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[DADDR:%[0-9]+]] = alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[CADDR]]#1 // CHECK: copy_addr [[BADDR]] to [initialization] [[DADDR]]#1 // CHECK: [[EADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[FADDR:%[0-9]+]] = alloc_box $Float // CHECK: [[GADDR:%[0-9]+]] = alloc_box $() // CHECK: [[HADDR:%[0-9]+]] = alloc_box $Double // CHECK: [[EFGH:%[0-9]+]] = apply // CHECK: [[E:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[F:%[0-9]+]] = tuple_extract {{.*}}, 1 // CHECK: [[G:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: [[H:%[0-9]+]] = tuple_extract {{.*}}, 3 // CHECK: store [[E]] to [[EADDR]] // CHECK: store [[F]] to [[FADDR]] // CHECK: store [[H]] to [[HADDR]] var (e,f,g,h) : (Int, Float, (), Double) = MRV() // CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[IADDR]]#1 // CHECK: [[B:%[0-9]+]] = load [[BADDR]] // CHECK-NOT: store [[B]] var (i,_) = (a, b) // CHECK: [[JADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: [[KADDR:%[0-9]+]] = alloc_box $() // CHECK-NOT: alloc_box $Double // CHECK: [[J_K_:%[0-9]+]] = apply // CHECK: [[J:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[K:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: store [[J]] to [[JADDR]] var (j,_,k,_) : (Int, Float, (), Double) = MRV() } // CHECK-LABEL: sil hidden @_TF5decls16simple_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[X]] // CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[Y]] func simple_arguments(x: Int, y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden @_TF5decls17curried_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[X]] // CHECK: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[Y]] func curried_arguments(x: Int)(y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden @_TF5decls14tuple_argument // CHECK: bb0(%0 : $Int, %1 : $Float): // CHECK: [[UNIT:%[0-9]+]] = tuple () // CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $()) // CHECK: [[XADDR:%[0-9]+]] = alloc_box $(Int, Float, ()) func tuple_argument(x: (Int, Float, ())) { var x = x } // CHECK-LABEL: sil hidden @_TF5decls14inout_argument // CHECK: bb0(%0 : $*Int, %1 : $Int): // CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box $Int // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: copy_addr [[YADDR]]#1 to [[X_LOCAL]]#1 func inout_argument(inout x: Int, y: Int) { var y = y x = y } var global = 42 // CHECK-LABEL: sil hidden @_TF5decls16load_from_global func load_from_global() -> Int { return global // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: [[VALUE:%[0-9]+]] = load [[ADDR]] // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden @_TF5decls15store_to_global func store_to_global(x: Int) { var x = x global = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: copy_addr [[XADDR]]#1 to [[ADDR]] // CHECK: return } struct S { var x:Int // CHECK-LABEL: sil hidden @_TFV5decls1SCf init() { x = 219 } init(a:Int, b:Int) { x = a + b } } // CHECK-LABEL: StructWithStaticVar.init // rdar://15821990 - Don't emit default value for static var in instance init() struct StructWithStaticVar { static var a : String = "" var b : String = "" init() { } } // <rdar://problem/17405715> lazy property crashes silgen of implicit memberwise initializer // CHECK-LABEL: // decls.StructWithLazyField.init // CHECK-NEXT: sil hidden @_TFV5decls19StructWithLazyFieldC{{.*}} : $@convention(thin) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField { struct StructWithLazyField { lazy var once : Int = 42 let someProp = "Some value" } // <rdar://problem/21057425> Crash while compiling attached test-app. // CHECK-LABEL: // decls.test21057425 func test21057425() { var x = 0, y: Int = 0 } func useImplicitDecls() { _ = StructWithLazyField(once: 55) }
3a14c01d494fcd560f5de9e791003197
29.163043
166
0.574595
false
false
false
false
diiingdong/InnerShadowTest
refs/heads/master
InnerShadowTest/UIViewExtension.swift
mit
1
import UIKit extension UIView { // different inner shadow styles public enum innerShadowSide { case all, left, right, top, bottom, topAndLeft, topAndRight, bottomAndLeft, bottomAndRight, exceptLeft, exceptRight, exceptTop, exceptBottom } // define function to add inner shadow public func addInnerShadow(onSide: innerShadowSide, shadowColor: UIColor, shadowSize: CGFloat, cornerRadius: CGFloat = 0.0, shadowOpacity: Float) { // define and set a shaow layer let shadowLayer = CAShapeLayer() shadowLayer.frame = bounds shadowLayer.shadowColor = shadowColor.cgColor shadowLayer.shadowOffset = CGSize(width: 0.0, height: 0.0) shadowLayer.shadowOpacity = shadowOpacity shadowLayer.shadowRadius = shadowSize shadowLayer.fillRule = kCAFillRuleEvenOdd // define shadow path let shadowPath = CGMutablePath() // define outer rectangle to restrict drawing area let insetRect = bounds.insetBy(dx: -shadowSize * 2.0, dy: -shadowSize * 2.0) // define inner rectangle for mask let innerFrame: CGRect = { () -> CGRect in switch onSide { case .all: return CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height) case .left: return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 4.0) case .right: return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 4.0) case .top: return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 4.0, height: frame.size.height + shadowSize * 2.0) case.bottom: return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 4.0, height: frame.size.height + shadowSize * 2.0) case .topAndLeft: return CGRect(x: 0.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0) case .topAndRight: return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0) case .bottomAndLeft: return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0) case .bottomAndRight: return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0) case .exceptLeft: return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height) case .exceptRight: return CGRect(x: 0.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height) case .exceptTop: return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width, height: frame.size.height + shadowSize * 2.0) case .exceptBottom: return CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height + shadowSize * 2.0) } }() // add outer and inner rectangle to shadow path shadowPath.addRect(insetRect) shadowPath.addRect(innerFrame) // set shadow path as show layer's shadowLayer.path = shadowPath // add shadow layer as a sublayer layer.addSublayer(shadowLayer) // hide outside drawing area clipsToBounds = true } }
f295d52fefefd0c7073c51ece0c9b0b1
51.026316
167
0.584977
false
false
false
false
richardxyx/Forecast
refs/heads/master
Forecast/SettingsViewController.swift
mit
1
// // AboutViewController.swift // Forecast // // Created by Kyle Bashour on 11/12/15. // Copyright © 2015 Richard Neitzke. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { var delegate: WeatherViewController? var reloadRequired = false //Dismisses the view and reloads the WeatherViewController in case the unit preference changed @IBAction func dismissPressed(sender: UIBarButtonItem) { if reloadRequired {delegate?.refresh()} dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var unitControl: UISegmentedControl! //Changes the unit preference @IBAction func unitControl(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: defaults.setValue("us", forKey: "unit") case 1: defaults.setValue("si", forKey: "unit") default: defaults.setValue("auto", forKey: "unit") } reloadRequired = true } let defaults = NSUserDefaults.standardUserDefaults() //Marks the current unit preference override func viewWillAppear(animated: Bool) { switch defaults.valueForKey("unit") as? String { case "us"?: unitControl.selectedSegmentIndex = 0 case "si"?: unitControl.selectedSegmentIndex = 1 //Sets the current unit setting to auto in case the unit never changed default: defaults.setValue("auto", forKey: "unit") unitControl.selectedSegmentIndex = 2 } reloadRequired = false } //Makes Navigation Bar Transparent override func viewDidLoad() { let bar:UINavigationBar! = self.navigationController?.navigationBar bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) bar.shadowImage = UIImage() bar.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) bar.barStyle = .BlackTranslucent } //Manages the text color of the headers override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = UIColor.whiteColor() header.alpha = 0.5 } //Opens the right link in Safari if a link is pressed override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath == NSIndexPath(forItem: 1, inSection: 1) { UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/richardxyx")!) } if indexPath == NSIndexPath(forItem: 0, inSection: 2) { UIApplication.sharedApplication().openURL(NSURL(string:"http://forecast.io")!) } if indexPath == NSIndexPath(forItem: 1, inSection: 2) { UIApplication.sharedApplication().openURL(NSURL(string:"http://weathericons.io")!) } if indexPath == NSIndexPath(forItem: 2, inSection: 2) { UIApplication.sharedApplication().openURL(NSURL(string:"https://icons8.com")!) } if indexPath == NSIndexPath(forItem: 0, inSection: 3) { UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/kylebshr")!) } if indexPath == NSIndexPath(forItem: 1, inSection: 3) { UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/lapfelix")!) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
0714af7011f163f0bd92a9422fa5ee1d
38.108696
114
0.663424
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica API Client/Habitica API Client/Models/User/APIUserItems.swift
gpl-3.0
1
// // APIUserItems.swift // Habitica API Client // // Created by Phillip Thelen on 09.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models public class APIUserItems: UserItemsProtocol, Decodable { public var gear: UserGearProtocol? public var currentMount: String? public var currentPet: String? public var ownedQuests: [OwnedItemProtocol] public var ownedFood: [OwnedItemProtocol] public var ownedHatchingPotions: [OwnedItemProtocol] public var ownedEggs: [OwnedItemProtocol] public var ownedSpecialItems: [OwnedItemProtocol] public var ownedPets: [OwnedPetProtocol] public var ownedMounts: [OwnedMountProtocol] enum CodingKeys: String, CodingKey { case gear case currentMount case currentPet case ownedQuests = "quests" case ownedFood = "food" case ownedHatchingPotions = "hatchingPotions" case ownedEggs = "eggs" case ownedSpecialItems = "special" case ownedPets = "pets" case ownedMounts = "mounts" } public required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) gear = try? values.decode(APIUserGear.self, forKey: .gear) currentPet = try? values.decode(String.self, forKey: .currentPet) currentMount = try? values.decode(String.self, forKey: .currentMount) let questsDict = try?values.decode([String: Int].self, forKey: .ownedQuests) ownedQuests = (questsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.quests.rawValue) })) ?? [] let foodDict = try?values.decode([String: Int].self, forKey: .ownedFood) ownedFood = (foodDict?.map({ (key, numberOwned) -> OwnedItemProtocol in return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.food.rawValue) })) ?? [] let hatchingPotionsDict = try?values.decode([String: Int].self, forKey: .ownedHatchingPotions) ownedHatchingPotions = (hatchingPotionsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.hatchingPotions.rawValue) })) ?? [] let eggsDict = try? values.decode([String: Int].self, forKey: .ownedEggs) ownedEggs = (eggsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.eggs.rawValue) })) ?? [] let specialDict = try? values.decode([String: Any].self, forKey: .ownedSpecialItems) ownedSpecialItems = (specialDict?.filter({ (_, value) -> Bool in return (value as? Int) != nil }).map({ (key, numberOwned) -> OwnedItemProtocol in return APIOwnedItem(key: key, numberOwned: numberOwned as? Int ?? 0, itemType: ItemType.special.rawValue) })) ?? [] let petsDict = try?values.decode([String: Int?].self, forKey: .ownedPets) ownedPets = (petsDict?.map({ (key, trained) -> OwnedPetProtocol in return APIOwnedPet(key: key, trained: trained ?? 0) })) ?? [] let mountsDict = try?values.decode([String: Bool?].self, forKey: .ownedMounts) ownedMounts = (mountsDict?.map({ (key, owned) -> APIOwnedMount in return APIOwnedMount(key: key, owned: owned ?? false) })) ?? [] } }
024717ea53d4638ce97dffc63f9ec0de
46.293333
117
0.656893
false
false
false
false
vkaramov/VKSplitViewController
refs/heads/master
SwiftDemo/SwiftDemo/SDDetailViewController.swift
mit
1
// // SDDetailViewController.swift // SwiftDemo // // Created by Viacheslav Karamov on 05.07.15. // Copyright (c) 2015 Viacheslav Karamov. All rights reserved. // import UIKit class SDDetailViewController: UIViewController { static let kNavigationStoryboardId = "DetailNavigationController"; private var splitController : VKSplitViewController?; @IBOutlet private var colorView : UIView?; override func viewDidLoad() { super.viewDidLoad(); splitController = UIApplication.sharedApplication().delegate?.window??.rootViewController as? VKSplitViewController; } func setBackgroundColor(color : UIColor) { colorView?.backgroundColor = color; } @IBAction func menuBarTapped(sender : UIBarButtonItem?) { if let splitController = splitController { let visible = splitController.masterViewControllerVisible; self.navigationItem.leftBarButtonItem?.title? = visible ? "Show" : "Hide"; splitController.masterViewControllerVisible = !visible; } } }
242059050895497b28554fcaeadf29d7
27.307692
124
0.677536
false
false
false
false
XeresRazor/SMeaGOL
refs/heads/master
SmeagolMath/SmeagolMath/Geometry/Vector4.swift
mit
1
// // Vector4.swift // Smeagol // // Created by Green2, David on 10/3/14. // Copyright (c) 2014 Digital Worlds. All rights reserved. // import Foundation // // MARK: - Definition and initializes - // public struct Vector4 { let x: Float let y: Float let z: Float let w: Float public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) { self.x = x self.y = y self.z = z self.w = w } public init(s: Float, t: Float, p: Float, q: Float) { self.x = s self.y = t self.z = p self.w = q } public init(r: Float, g: Float, b: Float, a: Float) { self.x = r self.y = g self.z = b self.w = a } public init(array: [Float]) { assert(array.count == 4, "Vector4 must be instantiated with 4 values.") self.x = array[0] self.y = array[1] self.z = array[2] self.w = array[3] } public init(vector: Vector3, w: Float) { self.x = vector.x self.y = vector.y self.z = vector.z self.w = w } } // // MARK: - Property accessors - // public extension Vector4 { // Property getters // Floatexture coordinate properties public var s: Float { return self.x } public var t: Float { return self.y } public var p: Float { return self.z } public var q: Float { return self.w } // Color properties public var r: Float { return self.x } public var g: Float { return self.y } public var b: Float { return self.z } public var a: Float { return self.w } // Array property public subscript (index: Int) -> Float { assert(index >= 0 && index < 4, "Index must be in the range 0...3") switch index { case 0: return self.x case 1: return self.y case 2: return self.z case 3: return self.w default: fatalError("Index out of bounds accessing Vector4") } } } // // MARK: - Vector methods - // public extension Vector4 { public func normalize() -> Vector4 { return self * self.length() } public func length() -> Float { return sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w) } public func dot(vector: Vector4) -> Float { let x: Float = self.x * vector.x let y: Float = self.y * vector.y let z: Float = self.z * vector.z let w: Float = self.w * vector.w return x + y + z + w } public func cross(vector: Vector4) -> Vector4 { let x: Float = (self.x * vector.z) - (self.z * vector.y) let y: Float = (self.z * vector.x) - (self.x * vector.z) let z: Float = (self.x * vector.y) - (self.y * vector.x) let w: Float = 0.0 return Vector4(x, y, z, w) } public func project(on: Vector4) -> Vector4 { let scale: Float = on.dot(self) / on.dot(self) return on * scale } public func distance(to: Vector4) -> Float { let lengthVec: Vector4 = self - to return lengthVec.length() } } // // MARK: - Operators - // public prefix func - (vector: Vector4) -> Vector4 { return Vector4(-vector.x, -vector.y, -vector.z, -vector.w) } public func + (lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w) } public func += (inout lhs: Vector4, rhs: Vector4) { lhs = Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w) } public func + (lhs: Vector4, rhs: Float) -> Vector4 { return Vector4(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs) } public func += (inout lhs: Vector4, rhs: Float) { lhs = Vector4(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs) } public func - (lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w) } public func -= (inout lhs: Vector4, rhs: Vector4) { lhs = Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w) } public func - (lhs: Vector4, rhs: Float) -> Vector4 { return Vector4(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs) } public func -= (inout lhs: Vector4, rhs: Float) { lhs = Vector4(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs) } public func * (lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w) } public func *= (inout lhs: Vector4, rhs: Vector4) { lhs = Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w) } public func * (lhs: Vector4, rhs: Float) -> Vector4 { return Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs) } public func *= (inout lhs: Vector4, rhs: Float) { lhs = Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs) } public func / (lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w) } public func /= (inout lhs: Vector4, rhs: Vector4) { lhs = Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w) } public func / (lhs: Vector4, rhs: Float) -> Vector4 { return Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs) } public func /= (inout lhs: Vector4, rhs: Float) { lhs = Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs) } public func == (lhs: Vector4, rhs: Vector4) -> Bool { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w) } public func == (lhs: Vector4, rhs: Float) -> Bool { return (lhs.x == rhs && lhs.y == rhs && lhs.z == rhs && lhs.w == rhs) } public func > (lhs: Vector4, rhs: Vector4) -> Bool { return (lhs.x > rhs.x && lhs.y > rhs.y && lhs.z > rhs.z && lhs.w > rhs.w) } public func > (lhs: Vector4, rhs: Float) -> Bool { return (lhs.x > rhs && lhs.y > rhs && lhs.z > rhs && lhs.w > rhs) } public func < (lhs: Vector4, rhs: Vector4) -> Bool { return (lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z && lhs.w < rhs.w) } public func < (lhs: Vector4, rhs: Float) -> Bool { return (lhs.x < rhs && lhs.y < rhs && lhs.z < rhs && lhs.w < rhs) } public func >= (lhs: Vector4, rhs: Vector4) -> Bool { return (lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z && lhs.w >= rhs.w) } public func >= (lhs: Vector4, rhs: Float) -> Bool { return (lhs.x >= rhs && lhs.y >= rhs && lhs.z >= rhs && lhs.w >= rhs) } public func <= (lhs: Vector4, rhs: Vector4) -> Bool { return (lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z && lhs.w <= rhs.w) } public func <= (lhs: Vector4, rhs: Float) -> Bool { return (lhs.x <= rhs && lhs.y <= rhs && lhs.z <= rhs && lhs.w <= rhs) } public func max(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4( lhs.x > rhs.x ? lhs.x : rhs.x, lhs.y > rhs.y ? lhs.y : rhs.y, lhs.z > rhs.z ? lhs.z : rhs.z, lhs.w > rhs.w ? lhs.w : rhs.w) } public func min(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4( lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y, lhs.z < rhs.z ? lhs.z : rhs.z, lhs.w < rhs.w ? lhs.w : rhs.w) } public func lerp(from: Vector4, to: Vector4, t: Float) -> Vector4 { return Vector4( from.x + ((to.x - from.x) * t), from.y + ((to.y - from.y) * t), from.z + ((to.z - from.z) * t), from.w + ((to.w - from.w) * t) ) }
fb85c763c04c995da9c99599eb831523
23.905797
84
0.584958
false
false
false
false
ahoppen/swift
refs/heads/main
test/attr/attr_backDeploy.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -parse-as-library \ // RUN: -define-availability "_myProject 2.0:macOS 12.0" // MARK: - Valid declarations // OK: top level functions @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedTopLevelFunc() {} // OK: internal decls may be back deployed when @usableFromInline @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @usableFromInline internal func backDeployedUsableFromInlineTopLevelFunc() {} // OK: function/property/subscript decls in a struct public struct TopLevelStruct { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var backDeployedComputedProperty: Int { 98 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public subscript(_ index: Int) -> Int { index } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var readWriteProperty: Int { get { 42 } set(newValue) {} } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public subscript(at index: Int) -> Int { get { 42 } set(newValue) {} } public var explicitReadAndModify: Int { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) _read { yield 42 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) _modify {} } } // OK: final function decls in a non-final class public class TopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func backDeployedFinalMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public var backDeployedFinalComputedProperty: Int { 98 } @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public static func backDeployedStaticMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public final class func backDeployedClassMethod() {} } // OK: function decls in a final class final public class FinalTopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public var backDeployedComputedProperty: Int { 98 } } // OK: final function decls on an actor @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) public actor TopLevelActor { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func finalActorMethod() {} // OK: actor methods are effectively final @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func actorMethod() {} } // OK: function decls in extension on public types extension TopLevelStruct { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } extension TopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) final public func backDeployedExtensionMethod() {} } extension FinalTopLevelClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } public protocol TopLevelProtocol {} extension TopLevelProtocol { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedExtensionMethod() {} } // MARK: - Unsupported declaration types @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public class CannotBackDeployClass {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public struct CannotBackDeployStruct { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public var cannotBackDeployStoredProperty: Int = 83 @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public lazy var cannotBackDeployLazyStoredProperty: Int = 15 } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public enum CannotBackDeployEnum { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} case cannotBackDeployEnumCase } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' must not be used on stored properties}} public var cannotBackDeployTopLevelVar = 79 @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} extension TopLevelStruct {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} protocol CannotBackDeployProtocol {} @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' attribute cannot be applied to this declaration}} public actor CannotBackDeployActor {} // MARK: - Function body diagnostics public struct FunctionBodyDiagnostics { public func publicFunc() {} @usableFromInline func usableFromInlineFunc() {} func internalFunc() {} // expected-note {{instance method 'internalFunc()' is not '@usableFromInline' or public}} fileprivate func fileprivateFunc() {} // expected-note {{instance method 'fileprivateFunc()' is not '@usableFromInline' or public}} private func privateFunc() {} // expected-note {{instance method 'privateFunc()' is not '@usableFromInline' or public}} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) public func backDeployedMethod() { struct Nested {} // expected-error {{type 'Nested' cannot be nested inside a '@_backDeploy' function}} publicFunc() usableFromInlineFunc() internalFunc() // expected-error {{instance method 'internalFunc()' is internal and cannot be referenced from a '@_backDeploy' function}} fileprivateFunc() // expected-error {{instance method 'fileprivateFunc()' is fileprivate and cannot be referenced from a '@_backDeploy' function}} privateFunc() // expected-error {{instance method 'privateFunc()' is private and cannot be referenced from a '@_backDeploy' function}} } } // MARK: - Incompatible declarations @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on fileprivate declarations}} fileprivate func filePrivateFunc() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on private declarations}} private func privateFunc() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on internal declarations}} internal func internalFunc() {} private struct PrivateTopLevelStruct { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' may not be used on private declarations}} public func effectivelyPrivateFunc() {} } public class TopLevelClass2 { @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' cannot be applied to a non-final instance method}} public func nonFinalMethod() {} @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' cannot be applied to a non-final class method}} public class func nonFinalClassMethod() {} } @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' requires that 'missingAllAvailabilityFunc()' have explicit availability for macOS}} public func missingAllAvailabilityFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, iOS 15.0) // expected-error {{'@_backDeploy' requires that 'missingiOSAvailabilityFunc()' have explicit availability for iOS}} public func missingiOSAvailabilityFunc() {} @available(macOS 12.0, *) @_backDeploy(before: macOS 12.0) // expected-error {{'@_backDeploy' has no effect because 'availableSameVersionAsBackDeployment()' is not available before macOS 12.0}} public func availableSameVersionAsBackDeployment() {} @available(macOS 12.1, *) @_backDeploy(before: macOS 12.0) // expected-error {{'availableAfterBackDeployment()' is not available before macOS 12.0}} public func availableAfterBackDeployment() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, macOS 13.0) // expected-error {{'@_backDeploy' contains multiple versions for macOS}} public func duplicatePlatformsFunc1() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_backDeploy(before: macOS 13.0) // expected-error {{'@_backDeploy' contains multiple versions for macOS}} public func duplicatePlatformsFunc2() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_alwaysEmitIntoClient // expected-error {{'@_alwaysEmitIntoClient' cannot be applied to a back deployed global function}} public func alwaysEmitIntoClientFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @inlinable // expected-error {{'@inlinable' cannot be applied to a back deployed global function}} public func inlinableFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @_transparent // expected-error {{'@_transparent' cannot be applied to a back deployed global function}} public func transparentFunc() {} // MARK: - Attribute parsing @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, unknownOS 1.0) // expected-warning {{unknown platform 'unknownOS' for attribute '@_backDeploy'}} public func unknownOSFunc() {} @_backDeploy(before: @) // expected-error {{expected platform in '@_backDeploy' attribute}} public func badPlatformFunc1() {} @_backDeploy(before: @ 12.0) // expected-error {{expected platform in '@_backDeploy' attribute}} public func badPlatformFunc2() {} @_backDeploy(before: macOS) // expected-error {{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc1() {} @_backDeploy(before: macOS 12.0, iOS) // expected-error {{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc2() {} @_backDeploy(before: macOS, iOS) // expected-error 2{{expected version number in '@_backDeploy' attribute}} public func missingVersionFunc3() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0, iOS 15.0,) // expected-error {{unexpected ',' separator}} public func unexpectedSeparatorFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0.1) // expected-warning {{'@_backDeploy' only uses major and minor version number}} public func patchVersionFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, * 9.0) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func wildcardWithVersionFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0, *) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func trailingWildcardFunc() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0, *, iOS 15.0) // expected-warning {{* as platform name has no effect in '@_backDeploy' attribute}} public func embeddedWildcardFunc() {} @_backDeploy(before: _myProject 3.0) // expected-error {{reference to undefined version '3.0' for availability macro '_myProject'}} public func macroVersioned() {} @_backDeploy(before: _myProject) // expected-error {{reference to undefined version '0' for availability macro '_myProject'}} public func missingMacroVersion() {} // Fall back to the default diagnostic when the macro is unknown. @_backDeploy(before: _unknownMacro) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} // expected-error@-1 {{expected version number in '@_backDeploy' attribute}} public func unknownMacroMissingVersion() {} @_backDeploy(before: _unknownMacro 1.0) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func unknownMacroVersioned() {} @available(macOS 11.0, *) @_backDeploy(before: _unknownMacro 1.0, _myProject 2.0) // expected-warning {{unknown platform '_unknownMacro' for attribute '@_backDeploy'}} public func knownAndUnknownMacroVersioned() {} @_backDeploy() // expected-error {{expected 'before:' in '@_backDeploy' attribute}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func emptyAttributeFunc() {} @available(macOS 11.0, *) @_backDeploy(macOS 12.0) // expected-error {{expected 'before:' in '@_backDeploy' attribute}} {{14-14=before:}} public func missingBeforeFunc() {} @_backDeploy(before) // expected-error {{expected ':' after 'before' in '@_backDeploy' attribute}} {{20-20=:}} // expected-error@-1 {{expected at least one platform version in '@_backDeploy' attribute}} public func missingColonAfterBeforeFunc() {} @available(macOS 11.0, *) @_backDeploy(before macOS 12.0) // expected-error {{expected ':' after 'before' in '@_backDeploy' attribute}} {{20-20=:}} public func missingColonBetweenBeforeAndPlatformFunc() {} @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0,) // expected-error {{unexpected ',' separator}} {{32-33=}} public func unexpectedTrailingCommaFunc() {} @available(macOS 11.0, iOS 14.0, *) @_backDeploy(before: macOS 12.0,, iOS 15.0) // expected-error {{unexpected ',' separator}} {{33-34=}} public func extraCommaFunc() {} @_backDeploy(before:) // expected-error {{expected at least one platform version in '@_backDeploy' attribute}} public func emptyPlatformVersionsFunc() {} @_backDeploy // expected-error {{expected '(' in '@_backDeploy' attribute}} public func expectedLeftParenFunc() {} @_backDeploy(before: macOS 12.0 // expected-note {{to match this opening '('}} public func expectedRightParenFunc() {} // expected-error {{expected ')' in '@_backDeploy' argument list}}
b1a6b3fc6b64790ebb2e917aacc44623
39.901493
167
0.725442
false
false
false
false
inkyfox/SwiftySQL
refs/heads/master
Tests/JoinTests.swift
mit
1
// // JoinTests.swift // SwiftySQLTests // // Created by Yongha Yoo (inkyfox) on 2016. 10. 27.. // Copyright © 2016년 Gen X Hippies Company. All rights reserved. // import XCTest @testable import SwiftySQL class JoinTests: XCTestCase { override func setUp() { super.setUp() student = Student() teature = Teature() lecture = Lecture() attending = Attending() } override func tearDown() { super.tearDown() student = nil teature = nil lecture = nil attending = nil } func testJoin() { XCTAssertSQL(student.join(attending), "student AS stu JOIN user.attending AS atd") XCTAssertSQL(student.join(attending, on: student.id == attending.studentID), "student AS stu JOIN user.attending AS atd ON stu.id = atd.student_id") } func testLeftJoin() { XCTAssertSQL(student.leftJoin(attending), "student AS stu LEFT JOIN user.attending AS atd") XCTAssertSQL(student.leftJoin(attending, on: student.id == attending.studentID), "student AS stu LEFT JOIN user.attending AS atd ON stu.id = atd.student_id") XCTAssertSQL(student.leftOuterJoin(attending), "student AS stu LEFT JOIN user.attending AS atd") XCTAssertSQL(student.leftOuterJoin(attending, on: student.id == attending.studentID), "student AS stu LEFT JOIN user.attending AS atd ON stu.id = atd.student_id") } func testCrossJoin() { XCTAssertSQL(student.crossJoin(attending), "student AS stu CROSS JOIN user.attending AS atd") XCTAssertSQL(student.crossJoin(attending, on: student.id == attending.studentID), "student AS stu CROSS JOIN user.attending AS atd ON stu.id = atd.student_id") } func testNaturalJoin() { XCTAssertSQL(student.naturalJoin(attending), "student AS stu NATURAL JOIN user.attending AS atd") XCTAssertSQL(student.naturalJoin(attending, on: student.id == attending.studentID), "student AS stu NATURAL JOIN user.attending AS atd ON stu.id = atd.student_id") } func testNaturalLeftJoin() { XCTAssertSQL(student.naturalLeftJoin(attending), "student AS stu NATURAL LEFT JOIN user.attending AS atd") XCTAssertSQL(student.naturalLeftJoin(attending, on: student.id == attending.studentID), "student AS stu NATURAL LEFT JOIN user.attending AS atd ON stu.id = atd.student_id") } func testMultipleJoin() { XCTAssertSQL( student .join(attending, on: student.id == attending.studentID) .join(lecture, on: lecture.id == attending.lectureID) , "student AS stu " + "JOIN user.attending AS atd ON stu.id = atd.student_id " + "JOIN lecture AS lec ON lec.id = atd.lecture_id") } }
b8094c323bcc55bd741e9431cd407040
35.717647
105
0.590516
false
true
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/MGPhotosBrowseCell.swift
mit
1
// // MGPhotosBrowseCell.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit class MGPhotosBrowseCell: UICollectionViewCell { // MARK: public /// 显示图片的imageView lazy var mg_imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() /// 单击执行的闭包 var mg_photoBrowerSimpleTapHandle: ((Any) -> Void)? // MARK: private /// 是否已经缩放 fileprivate var isScale = false /// 底部负责缩放的滚动视图 lazy fileprivate var mg_scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.backgroundColor = .black scrollView.minimumZoomScale = CGFloat(self.minScaleZoome) scrollView.maximumZoomScale = CGFloat(self.maxScaleZoome) scrollView.delegate = self return scrollView }() /// 单击手势 lazy fileprivate var mg_simpleTap: UITapGestureRecognizer = { let simpleTap = UITapGestureRecognizer() simpleTap.numberOfTapsRequired = 1 simpleTap.require(toFail: self.mg_doubleTap) //设置响应 simpleTap.action({[weak self] (_) in if let strongSelf = self { if strongSelf.mg_photoBrowerSimpleTapHandle != nil { //执行闭包 strongSelf.mg_photoBrowerSimpleTapHandle?(strongSelf) } } /********** 此处不再返回原始比例,如需此功能,请清除此处注释 2019/7/8 ***********/ /* if strongSelf!.mg_scrollView.zoomScale != 1.0 { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true) } */ /*************************************************************************/ }) return simpleTap }() /// 双击手势 lazy fileprivate var mg_doubleTap: UITapGestureRecognizer = { let doubleTap = UITapGestureRecognizer() doubleTap.numberOfTapsRequired = 2 doubleTap.action({ [weak self](sender) in let strongSelf = self //表示需要缩放成1.0 guard strongSelf!.mg_scrollView.zoomScale == 1.0 else { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true); return } //进行放大 let width = strongSelf!.frame.width let scale = width / CGFloat(strongSelf!.maxScaleZoome) let point = sender.location(in: strongSelf!.mg_imageView) //对点进行处理 let originX = max(0, point.x - width / scale) let originY = max(0, point.y - width / scale) //进行位置的计算 let rect = CGRect(x: originX, y: originY, width: width / scale, height: width / scale) //进行缩放 strongSelf!.mg_scrollView.zoom(to: rect, animated: true) }) return doubleTap }() /// 最小缩放比例 fileprivate let minScaleZoome = 1.0 /// 最大缩放比例 fileprivate let maxScaleZoome = 2.0 override init(frame: CGRect) { super.init(frame: frame) addAndLayoutSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() addAndLayoutSubViews() } fileprivate func addAndLayoutSubViews() { contentView.addSubview(mg_scrollView) mg_scrollView.addSubview(mg_imageView) mg_scrollView.addGestureRecognizer(mg_simpleTap) mg_scrollView.addGestureRecognizer(mg_doubleTap) mg_scrollView.translatesAutoresizingMaskIntoConstraints = false mg_scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true mg_scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true mg_scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true mg_scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true mg_imageView.translatesAutoresizingMaskIntoConstraints = false mg_imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true mg_imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true mg_imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true mg_imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true mg_imageView.widthAnchor.constraint(equalTo: mg_scrollView.widthAnchor).isActive = true mg_imageView.heightAnchor.constraint(equalTo: mg_scrollView.heightAnchor).isActive = true //layout // mg_scrollView.snp.makeConstraints { (make) in // make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)) // } // // mg_imageView.snp.makeConstraints { [weak self](make) in // let strongSelf = self // make.edges.equalToSuperview() // make.width.equalTo(strongSelf!.mg_scrollView.snp.width) // make.height.equalTo(strongSelf!.mg_scrollView.snp.height) // } } } extension MGPhotosBrowseCell: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return mg_imageView } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { scrollView.setZoomScale(scale, animated: true) } }
0664c7bb2fe8f4f6ab9133e1a6e9d35e
29.703911
106
0.621543
false
false
false
false
4faramita/TweeBox
refs/heads/master
TweeBox/TwitterUser.swift
mit
1
// // TwitterUser.swift // TweeBox // // Created by 4faramita on 2017/7/28. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation import SwiftyJSON struct TwitterUser { public var id: String public var location: String? public var name: String // not the @ one, that's the "screen_name" public var screenName: String public var url: URL? // A URL provided by the user in association with their profile. public var createdAt: String public var defaultProfile: Bool // When true, indicates that the user has not altered the theme or background of their user profile. public var defaultProfileImage: Bool public var description: String? public var entities: Entity // Entities which have been parsed out of the url or description fields defined by the user. public var verified: Bool public var favouritesCount: Int public var followRequestSent: Bool? // When true, indicates that the authenticating user has issued a follow request to this protected user account public var following: Bool? public var followersCount: Int public var followingCount: Int // friends_count public var geoEnabled: Bool // When true, indicates that the user has enabled the possibility of geotagging their Tweets. // This field must be true for the current user to attach geographic data when using POST statuses / update . public var isTranslator: Bool // When true, indicates that the user is a participant in Twitter’s translator community . public var lang: String public var listedCount: Int // The number of public lists that this user is a member of. public var notifications: Bool? // Indicates whether the authenticated user has chosen to receive this user’s Tweets by SMS. public var profileBackgroundColor: String // The hexadecimal color chosen by the user for their background. public var profileBackgroundImageURLHTTP: URL? // profile_background_image_url public var profileBackgroundImageURL: URL? // profile_background_image_url_https public var profileBackgroundTile: Bool // When true, indicates that the user’s profile_background_image_url should be tiled when displayed. public var profileBannerURL: URL? // By adding a final path element of the URL, // it is possible to obtain different image sizes optimized for specific displays. public var profileImageURLHTTP: URL? // profile_image_url public var profileImageURL: URL? // profile_image_url_https public var profileUseBackgroundImage: Bool // public var profile_link_color: String // public var profile_sidebar_border_color: String // public var profile_sidebar_fill_color: String // public var profile_text_color: String public var protected: Bool public var status: Tweet? public var statusesCount: Int // The number of Tweets (including retweets) issued by the user. public var timeZone: String? public var utcOffset: Int? // The offset from GMT/UTC in seconds. // public var withheld_in_countries: String? // public var withheld_scope: String? init(with userJSON: JSON) { id = userJSON["id_str"].stringValue location = userJSON["location"].string name = userJSON["name"].stringValue screenName = userJSON["screen_name"].stringValue url = URL(string: userJSON["url"].stringValue) createdAt = userJSON["created_at"].stringValue defaultProfile = userJSON["default_profile"].bool ?? true defaultProfileImage = userJSON["default_profile_image"].bool ?? true description = userJSON["description"].string entities = Entity(with: userJSON["entities"], and: JSON.null) // ((userJSON["entities"].null == nil) ? (Entity(with: userJSON["entities"])) : nil) verified = userJSON["verified"].bool ?? false favouritesCount = userJSON["favourites_count"].int ?? 0 followRequestSent = userJSON["follow_request_sent"].bool following = userJSON["following"].bool followersCount = userJSON["followers_count"].int ?? 0 followingCount = userJSON["friends_count"].int ?? 0 geoEnabled = userJSON["geo_enabled"].bool ?? false isTranslator = userJSON["is_translator"].bool ?? false lang = userJSON["lang"].stringValue listedCount = userJSON["listed_count"].int ?? 0 notifications = userJSON["notifications"].bool profileBackgroundColor = userJSON["profile_background_color"].stringValue profileBackgroundImageURLHTTP = URL(string: userJSON["profile_background_image_url"].stringValue) profileBackgroundImageURL = URL(string: userJSON["profile_background_image_url_https"].stringValue) profileBackgroundTile = userJSON["profile_background_tile"].bool ?? false profileBannerURL = URL(string: userJSON["profile_banner_url"].stringValue) profileImageURLHTTP = URL(string: userJSON["profile_image_url"].stringValue) profileImageURL = URL(string: userJSON["profile_image_url_https"].stringValue, quality: .max) profileUseBackgroundImage = userJSON["profile_use_background_image"].bool ?? true protected = userJSON["protected"].bool ?? false status = ((userJSON["status"].null == nil) ? (Tweet(with: userJSON["status"])) : nil) statusesCount = userJSON["statuses_count"].int ?? 0 timeZone = userJSON["time_zone"].string utcOffset = userJSON["utc_offset"].int } }
446e2cd1197ad88ff0ff41a88720aaf7
47.645669
176
0.62933
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Representables/SharingPicker.swift
mit
1
// // SharingPicker.swift // RedditOs // // Created by Thomas Ricouard on 12/08/2020. // import Foundation import AppKit import SwiftUI struct SharingsPicker: NSViewRepresentable { @Binding var isPresented: Bool var sharingItems: [Any] = [] func makeNSView(context: Context) -> NSView { let view = NSView() return view } func updateNSView(_ nsView: NSView, context: Context) { if isPresented { let picker = NSSharingServicePicker(items: sharingItems) picker.delegate = context.coordinator DispatchQueue.main.async { picker.show(relativeTo: .zero, of: nsView, preferredEdge: .minY) } } } func makeCoordinator() -> Coordinator { Coordinator(owner: self) } class Coordinator: NSObject, NSSharingServicePickerDelegate { let owner: SharingsPicker init(owner: SharingsPicker) { self.owner = owner } func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, didChoose service: NSSharingService?) { sharingServicePicker.delegate = nil self.owner.isPresented = false } } }
2cc55d3256db0461d9a32d95c463091e
25.446809
121
0.613033
false
false
false
false
Camvergence/AssetFlow
refs/heads/master
PhotosPlusTests/PhotosPlusTests.swift
mit
3
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import XCTest @testable import PhotosPlus class PhotosPlusTests: XCTestCase { var cameraNames: [String] = [String]() func testCameras() { let cameraTypes: [CameraModel.Type] = [ Canon10D.self, Canon5D.self, Canon6D.self, CanonEOS1D.self, CanonEOS1DC.self, CanonEOS1DMarkII.self, CanonEOS1DMarkIII.self, CanonEOS1DMarkIIN.self, CanonEOS1DMarkIV.self, CanonEOS1Ds.self, CanonEOS1DsMarkII.self, CanonEOS1DsMarkIII.self, CanonEOS1DX.self, CanonEOS1DXMarkII.self, CanonEOS20D.self, CanonEOS30D.self, CanonEOS40D.self, CanonEOS50D.self, CanonEOS5DMarkII.self, CanonEOS5DMarkIII.self, CanonEOS5DMarkIV.self, CanonEOS5DS.self, CanonEOS5DSR.self, CanonEOS60D.self, CanonEOS70D.self, CanonEOS7D.self, CanonEOS7DMarkII.self, CanonEOS80D.self, CanonEOSD30.self, CanonEOSD60.self, CanonEOSDigitalRebel.self, CanonEOSDigitalRebelXS.self, CanonEOSDigitalRebelXSi.self, CanonEOSDigitalRebelXT.self, CanonEOSDigitalRebelXTi.self, CanonEOSM.self, CanonEOSM10.self, CanonEOSM2.self, CanonEOSM3.self, CanonEOSM5.self, CanonEOSRebelSL1.self, CanonEOSRebelT1i.self, CanonEOSRebelT2i.self, CanonEOSRebelT3.self, CanonEOSRebelT3i.self, CanonEOSRebelT4i.self, CanonEOSRebelT5.self, CanonEOSRebelT5i.self, CanonEOSRebelT6.self, CanonEOSRebelT6i.self, CanonEOSRebelT6s.self, CanonPowerShotG10.self, CanonPowerShotG11.self, CanonPowerShotG12.self, CanonPowerShotG15.self, CanonPowerShotG16.self, CanonPowerShotG1X.self, CanonPowerShotG1XMarkII.self, CanonPowerShotG3X.self, CanonPowerShotG5.self, CanonPowerShotG5X.self, CanonPowerShotG6.self, CanonPowerShotG7X.self, CanonPowerShotG7XMarkII.self, CanonPowerShotG9.self, CanonPowerShotG9X.self, CanonPowerShotPro1.self, CanonPowerShotS100.self, CanonPowerShotS110.self, CanonPowerShotS120.self, CanonPowerShotS60.self, CanonPowerShotS70.self, CanonPowerShotS90.self, CanonPowerShotS95.self, CanonPowerShotSX1IS.self, CanonPowerShotSX50HS.self, CanonPowerShotSX60HS.self, DJIMavicPro.self, DxOOne.self, EpsonRD1.self, EpsonRD1s.self, EpsonRD1x.self, FujifilmFinePixS2Pro.self, FujifilmFinePixS3Pro.self, FujifilmFinePixS5Pro.self, FujifilmFinePixX100.self, FujifilmX100S.self, FujifilmX100t.self, FujifilmX20.self, FujifilmX30.self, FujifilmX70.self, FujifilmXA1.self, FujifilmXA2.self, FujifilmXE1.self, FujifilmXE2.self, FujifilmXE2S.self, FujifilmXM1.self, FujifilmXPro1.self, FujifilmXPro2.self, FujifilmXQ1.self, FujifilmXQ2.self, FujifilmXT1.self, FujifilmXT10.self, FujifilmXT2.self, GooglePixelXL.self, HasselbladCF22.self, HasselbladCF39.self, HasselbladCFV16.self, HasselbladCFV50c.self, HasselbladH3D31.self, HasselbladH3D31II.self, HasselbladH3DII50.self, HasselbladH4D40.self, HasselbladH5D50c.self, HasselbladLunar.self, HasselbladX1D.self, KodakDCSProSLR.self, KodakPixproS1.self, KonicaMinoltaALPHA5DIGITAL.self, KonicaMinoltaALPHA7DIGITAL.self, KonicaMinoltaALPHASWEETDIGITAL.self, KonicaMinoltaDiMAGEA200.self, KonicaMinoltaDYNAX5D.self, KonicaMinoltaDYNAX7D.self, KonicaMinoltaMAXXUM5D.self, KonicaMinoltaMAXXUM7D.self, LeafAFi5.self, LeafAFi6.self, LeafAFi7.self, LeafAFiII6.self, LeafAFiII7.self, LeafAptus17.self, LeafAptus22.self, LeafAptus54S.self, LeafAptus65.self, LeafAptus65S.self, LeafAptus75.self, LeafAptus75s.self, LeafAptusII6.self, LeafAptusII7.self, LeafValeo11.self, LeafValeo17.self, LeafValeo22.self, LeicaCTyp112.self, LeicaDIGILUX2.self, LeicaDIGILUX3.self, LeicaDLuxTyp109.self, LeicaDLux2.self, LeicaDLux3.self, LeicaDLux4.self, LeicaDLux5.self, LeicaDLux6.self, LeicaM.self, LeicaM8dot2.self, LeicaM8.self, LeicaM9.self, LeicaME.self, LeicaMMonochromTyp246.self, LeicaMMonochrom.self, LeicaQ.self, LeicaSTyp007.self, LeicaS2.self, LeicaSLTyp601.self, LeicaVLuxTyp114.self, LeicaVLux1.self, LeicaVLux2.self, LeicaVLux4.self, LeicaXTyp113.self, LeicaX1.self, LeicaX2.self, LeicaXUTyp113.self, LeicaXVarioTyp107.self, MinoltaDiMAGEA1.self, MinoltaDiMAGEA2.self, Nikon1AW1.self, Nikon1J1.self, Nikon1J2.self, Nikon1J3.self, Nikon1J4.self, Nikon1J5.self, Nikon1S1.self, Nikon1S2.self, Nikon1V1.self, Nikon1V2.self, Nikon1V3.self, NikonCOOLPIXA.self, NikonCOOLPIXP330.self, NikonCOOLPIXP340.self, NikonCOOLPIXP6000.self, NikonCOOLPIXP7000.self, NikonCOOLPIXP7100.self, NikonCOOLPIXP7700.self, NikonCOOLPIXP7800.self, NikonD1.self, NikonD100.self, NikonD1H.self, NikonD1X.self, NikonD200.self, NikonD2H.self, NikonD2Hs.self, NikonD2X.self, NikonD2Xs.self, NikonD3.self, NikonD300.self, NikonD3000.self, NikonD300S.self, NikonD3100.self, NikonD3200.self, NikonD3300.self, NikonD3400.self, NikonD3S.self, NikonD3X.self, NikonD4.self, NikonD40.self, NikonD40X.self, NikonD4S.self, NikonD5.self, NikonD50.self, NikonD500.self, NikonD5000.self, NikonD5100.self, NikonD5200.self, NikonD5300.self, NikonD5500.self, NikonD60.self, NikonD600.self, NikonD610.self, NikonD70.self, NikonD700.self, NikonD7000.self, NikonD70s.self, NikonD7100.self, NikonD7200.self, NikonD750.self, NikonD80.self, NikonD800.self, NikonD800E.self, NikonD810.self, NikonD810A.self, NikonD90.self, NikonDf.self, NikonE8400.self, NikonE8700.self, NikonE8800.self, OlympusC7000Z.self, OlympusC7070WZ.self, OlympusC70Z.self, OlympusC8080WZ.self, OlympusE1.self, OlympusE3.self, OlympusE30.self, OlympusE300.self, OlympusE330.self, OlympusE400.self, OlympusE410.self, OlympusE450.self, OlympusE5.self, OlympusE500.self, OlympusE510.self, OlympusE600.self, OlympusE620.self, OlympusEM1.self, OlympusEM1MarkII.self, OlympusEP5.self, OlympusEVOLTE420.self, OlympusEVOLTE520.self, OlympusOMDEM10.self, OlympusOMDEM10MarkII.self, OlympusOMDEM5.self, OlympusOMDEM5MarkII.self, OlympusPENEP1.self, OlympusPENEP2.self, OlympusPENEP3.self, OlympusPENEPL1.self, OlympusPENEPL1s.self, OlympusPENEPL2.self, OlympusPENEPL3.self, OlympusPENEPL5.self, OlympusPENEPL7.self, OlympusPENEPM1.self, OlympusPENEPM2.self, OlympusPENF.self, OlympusPENLiteEPL6.self, OlympusSP570UZ.self, OlympusSTYLUS1.self, OlympusSTYLUSSH2.self, OlympusSTYLUSXZ2.self, OlympusTG4.self, OlympusXZ1.self, PanasonicLUMIXCM1.self, PanasonicLUMIXDMCFZ100.self, PanasonicLUMIXDMCFZ1000.self, PanasonicLUMIXDMCFZ150.self, PanasonicLUMIXDMCFZ200.self, PanasonicLUMIXDMCF25000.self, PanasonicLumixDMCFZ300.self, PanasonicLUMIXDMCFZ330.self, PanasonicLUMIXDMCFZ35.self, PanasonicLUMIXDMCFZ38.self, PanasonicLUMIXDMCFZ50.self, PanasonicLUMIXDMCFZ70.self, PanasonicLUMIXDMCFZ72.self, PanasonicLUMIXDMCG1.self, PanasonicLUMIXDMCG10.self, PanasonicLUMIXDMCG2.self, PanasonicLUMIXDMCG3.self, PanasonicLUMIXDMCG5.self, PanasonicLUMIXDMCG6.self, PanasonicLUMIXDMCG7.self, PanasonicLUMIXDMCGF1.self, PanasonicLUMIXDMCGF2.self, PanasonicLUMIXDMCGF3.self, PanasonicLUMIXDMCGF5.self, PanasonicLUMIXDMCGF6.self, PanasonicLUMIXDMCGF7.self, PanasonicLUMIXDMCGF8.self, PanasonicLUMIXDMCGH1.self, PanasonicLUMIXDMCGH2.self, PanasonicLUMIXDMCGH3.self, PanasonicLUMIXDMCGH4.self, PanasonicLUMIXDMCGM1.self, PanasonicLUMIXDMCGM5.self, PanasonicLUMIXDMCGX1.self, PanasonicLumixDMCGX7.self, PanasonicLumixDMCGX8.self, PanasonicLUMIXDMCL1.self, PanasonicLUMIXDMCLC1.self, PanasonicLUMIXDMCLF1.self, PanasonicLUMIXDMCLX1.self, PanasonicLUMIXDMCLX10.self, PanasonicLUMIXDMCLX100.self, PanasonicLUMIXDMCLX2.self, PanasonicLUMIXDMCLX3.self, PanasonicLUMIXDMCLX5.self, PanasonicLUMIXDMCLX7.self, PanasonicLUMIXDMCTZ60.self, PanasonicLUMIXDMCTZ61.self, PanasonicLUMIXDMCTZ70.self, PanasonicLUMIXDMCTZ71.self, PanasonicLUMIXDMCZS100.self, PanasonicLUMIXDMCZS40.self, PanasonicLUMIXDMCZS50.self, PanasonicLumixG85.self, PanasonicLumixZS60.self, PentaxIstD.self, PentaxIstDL.self, PentaxIstDL2.self, PentaxIstDS.self, PentaxIstDS2.self, Pentax645D.self, Pentax645Z.self, PentaxK1.self, PentaxK100D.self, PentaxK100DSuper.self, PentaxK10D.self, PentaxK110D.self, PentaxK2000.self, PentaxK200D.self, PentaxK20D.self, PentaxK3.self, PentaxK30.self, PentaxK3II.self, PentaxK5.self, PentaxK50.self, PentaxK5II.self, PentaxK5IIs.self, PentaxK7.self, PentaxK70.self, PentaxKm.self, PentaxKr.self, PentaxKS1.self, PentaxKS2.self, PentaxKx.self, PentaxMX1.self, PentaxQ.self, RicohGRII.self, SamsungGalaxyNX.self, SamsungGX10.self, SamsungGX1L.self, SamsungGX1S.self, SamsungGX20.self, SamsungNX1.self, SamsungNX10.self, SamsungNX100.self, SamsungNX1000.self, SamsungNX11.self, SamsungNX1100.self, SamsungNX20.self, SamsungNX200.self, SamsungNX2000.self, SamsungNX210.self, SamsungNX30.self, SamsungNX300.self, SamsungNX5.self, SamsungNX500.self, SonyAlphaDSLRA200.self, SonyAlphaDSLRA230.self, SonyAlphaDSLRA290.self, SonyAlphaDSLRA300.self, SonyAlphaDSLRA330.self, SonyAlphaDSLRA350.self, SonyAlphaDSLRA380.self, SonyAlphaDSLRA390.self, SonyAlphaDSLRA450.self, SonyAlphaDSLRA500.self, SonyAlphaDSLRA550.self, SonyAlphaDSLRA560.self, SonyAlphaDSLRA580.self, SonyAlphaDSLRA850.self, SonyAlphaDSLRA900.self, SonyAlphaILCE3000.self, SonyAlphaILCE5000.self, SonyA5100.self, SonyAlphaILCE6000.self, SonyA6300.self, SonyA6500.self, SonyA7.self, SonyA7II.self, SonyAlphaILCE7R.self, SonyA7rII.self, SonyA7s.self, SonyAlphaILCE7SII.self, SonyAlphaNEX3N.self, SonyAlphaNEX5.self, SonyAlphaNEX5N.self, SonyAlphaNEX5R.self, SonyAlphaNEX5T.self, SonyAlphaNEX6.self, SonyAlphaNEX7.self, SonyAlphaNEXC3.self, SonyAlphaNEXF3.self, SonyAlphaSLTA33.self, SonyAlphaSLTA35.self, SonyAlphaSLTA37.self, SonyAlphaSLTA55.self, SonyAlphaSLTA57.self, SonyAlphaSLTA58.self, SonyAlphaSLTA65.self, SonyAlphaSLTA68.self, SonyAlphaSLTA77.self, SonyAlphaSLTA77II.self, SonyAlphaSLTA99.self, SonyCybershotDSCRX1.self, SonyCybershotDSCRX10.self, SonyCybershotDSCRX100.self, SonyCybershotDSCRX100II.self, SonyCybershotDSCRX100III.self, SonyCybershotDSCRX100IV.self, SonyCybershotDSCRX10II.self, SonyCybershotDSCRX10III.self, SonyCybershotDSCRX1R.self, SonyCybershotRX1RII.self, SonyDSCF828.self, SonyDSCR1.self, SonyDSCV3.self, SonyA100.self, SonyA700.self, SonyNEX3.self, SonyNEXVG20.self, SonyRX100MarkV.self, YIM1.self, ] for cameraType in cameraTypes { assert(check(camera: cameraType.init()), String(describing: cameraType)) } } func check(camera: CameraModel) -> Bool { if cameraNames.contains(camera.name) { return false } else { cameraNames.append(camera.name) } if camera.manufacturer.defaultRawUti == "" { return false } if camera.rawUti == "" { return false } return true } }
8b3f6034602279514d90c7641da21b8a
30.908
84
0.543563
false
false
false
false
ByteriX/BxInputController
refs/heads/master
BxInputController/Sources/Controller/BxInputController+InputAccessoryView.swift
mit
1
/** * @file BxInputController+InputAccessoryView.swift * @namespace BxInputController * * @details Working with panel abouve keyboard in BxInputController * @date 23.01.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Working with panel abouve keyboard in BxInputController extension BxInputController { /// Class of panel abouve keyboard open class InputAccessoryView : UIToolbar { internal(set) public var backNextControl: UISegmentedControl internal(set) public var doneButtonItem: UIBarButtonItem init(parent: BxInputController) { var items : [String] = [] let settings = parent.settings items.append(settings.backButtonTitle) items.append(settings.nextButtonTitle) backNextControl = UISegmentedControl(items: items) backNextControl.frame = CGRect(x: 0, y: 0, width: 140, height: 30) backNextControl.isMomentary = true backNextControl.addTarget(parent, action: #selector(backNextButtonClick), for: .valueChanged) doneButtonItem = UIBarButtonItem(title: settings.doneButtonTitle, style: .done, target: parent, action: #selector(doneButtonClick)) super.init(frame: CGRect(x: 0, y: 0, width: 320, height: 44)) self.barStyle = .blackTranslucent self.items = [UIBarButtonItem(customView: backNextControl), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), doneButtonItem] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /// refresh commonInputAccessoryView for using this as panel as abouve keyboard open func updateInputAccessory() { if isShowingInputAccessoryView { commonInputAccessoryView = InputAccessoryView(parent: self) updateCommonInputAccessory() } else { commonInputAccessoryView = nil } } /// update content of panel as abouve keyboard open func updateCommonInputAccessory() { guard let commonInputAccessoryView = commonInputAccessoryView, let activeRow = activeRow else { return } commonInputAccessoryView.backNextControl.setEnabled(getDecrementRow(from: activeRow) != nil, forSegmentAt: 0) commonInputAccessoryView.backNextControl.setEnabled(getIncrementRow(from: activeRow) != nil, forSegmentAt: 1) } /// set and update panel abouve keyboard for activeControl open func updateInputAccessory(activeControl: UIView?) { if let activeControl = activeControl as? UITextField { activeControl.inputAccessoryView = commonInputAccessoryView } else if let activeControl = activeControl as? UITextView { activeControl.inputAccessoryView = commonInputAccessoryView } updateCommonInputAccessory() } /// event when user click back or next row @objc open func backNextButtonClick(control: UISegmentedControl) { guard let activeRow = activeRow else { activeControl?.resignFirstResponder() return } var row: BxInputRow? = nil if control.selectedSegmentIndex == 0 { row = getDecrementRow(from: activeRow) } else { row = getIncrementRow(from: activeRow) } if let row = row { // DispatchQueue.main.async {[weak self] () in self?.selectRow(row) self?.updateCommonInputAccessory() } } else { activeControl?.resignFirstResponder() } } /// event when user click done @objc open func doneButtonClick() { activeControl?.resignFirstResponder() } /// return true if row can get focus open func checkedForGettingRow(_ row: BxInputRow) -> Bool{ if row is BxInputChildSelectorRow { return false } return row.isEnabled } /// return a row after current row. If not found then return nil open func getIncrementRow(from row: BxInputRow) -> BxInputRow? { if let indexPath = getIndex(for: row) { var sectionIndex = indexPath.section var rowIndex = indexPath.row + 1 while sectionIndex < sections.count { let rowBinders = sections[sectionIndex].rowBinders while rowIndex < rowBinders.count { let result = rowBinders[rowIndex].rowData if checkedForGettingRow(result) { return result } rowIndex = rowIndex + 1 } rowIndex = 0 sectionIndex = sectionIndex + 1 } } return nil } /// return a row before current row. If not found then return nil open func getDecrementRow(from row: BxInputRow) -> BxInputRow? { if let indexPath = getIndex(for: row) { var sectionIndex = indexPath.section var rowIndex = indexPath.row - 1 while sectionIndex > -1 { let rowBinders = sections[sectionIndex].rowBinders while rowIndex > -1 { let result = rowBinders[rowIndex].rowData if checkedForGettingRow(result) { return result } rowIndex = rowIndex - 1 } sectionIndex = sectionIndex - 1 if sectionIndex > -1 { rowIndex = sections[sectionIndex].rowBinders.count - 1 } } } return nil } }
5af2d4a789bf97b1409bf19439112fef
35.792683
167
0.60126
false
false
false
false
lockersoft/Winter2016-iOS
refs/heads/master
BMICalcLecture/Charts/Classes/Charts/CombinedChartView.swift
unlicense
1
// // CombinedChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. public class CombinedChartView: BarLineChartViewBase, LineChartDataProvider, BarChartDataProvider, ScatterChartDataProvider, CandleChartDataProvider, BubbleChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: ChartFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc public enum CombinedChartDrawOrder: Int { case Bar case Bubble case Line case Candle case Scatter } public override func initialize() { super.initialize() self.highlighter = CombinedHighlighter(chart: self) /// WORKAROUND: Swift 2.0 compiler malfunctions when optimizations are enabled, and assigning directly to _fillFormatter causes a crash with a EXC_BAD_ACCESS. See https://github.com/danielgindi/ios-charts/issues/406 let workaroundFormatter = ChartDefaultFillFormatter() _fillFormatter = workaroundFormatter renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } override func calcMinMax() { super.calcMinMax() if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil) { _chartXMin = -0.5 _chartXMax = Double(_data.xVals.count) - 0.5 if (self.bubbleData !== nil) { for set in self.bubbleData?.dataSets as! [IBubbleChartDataSet] { let xmin = set.xMin let xmax = set.xMax if (xmin < chartXMin) { _chartXMin = xmin } if (xmax > chartXMax) { _chartXMax = xmax } } } } _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) if (_deltaX == 0.0 && self.lineData?.yValCount > 0) { _deltaX = 1.0 } } public override var data: ChartData? { get { return super.data } set { super.data = newValue (renderer as! CombinedChartRenderer?)!.createRenderers() } } public var fillFormatter: ChartFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if (_fillFormatter == nil) { _fillFormatter = ChartDefaultFillFormatter() } } } // MARK: - LineChartDataProvider public var lineData: LineChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).lineData } } // MARK: - BarChartDataProvider public var barData: BarChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).barData } } // MARK: - ScatterChartDataProvider public var scatterData: ScatterChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).scatterData } } // MARK: - CandleChartDataProvider public var candleData: CandleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).candleData } } // MARK: - BubbleChartDataProvider public var bubbleData: BubbleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).bubbleData } } // MARK: - Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled } set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is darawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue } } /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! } } } }
d35c8fb002cc5e5a21db658319fd089f
28.9869
223
0.566414
false
false
false
false
Bargetor/beak
refs/heads/master
Beak/Beak/view/UIAnimation.swift
mit
1
// // UIAnimation.swift // Beak // // Created by 马进 on 2017/1/6. // Copyright © 2017年 马进. All rights reserved. // import Foundation // // EAAnimationFuture.swift // // Created by Marin Todorov on 5/26/15. // Copyright (c) 2015-2016 Underplot ltd. 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 /** A class that is used behind the scene to chain and/or delay animations. You do not need to create instances directly - they are created automatically when you use animateWithDuration:animation: and the like. */ public class UIAnimationFuture: Equatable, CustomStringConvertible { /* debug helpers */ private var debug: Bool = false private var debugNumber: Int = 0 static private var debugCount: Int = 0 /* animation properties */ var duration: CFTimeInterval = 0.0 var delay: CFTimeInterval = 0.0 var options: UIView.AnimationOptions = [] var animations: (() -> Void)? var completion: ((Bool) -> Void)? var identifier: String var springDamping: CGFloat = 0.0 var springVelocity: CGFloat = 0.0 private var loopsChain = false private static var cancelCompletions: [String: ()->Void] = [:] /* animation chain links */ var prevDelayedAnimation: UIAnimationFuture? { didSet { if let prev = prevDelayedAnimation { identifier = prev.identifier } } } var nextDelayedAnimation: UIAnimationFuture? //MARK: - Animation lifecycle init() { UIAnimationFuture.debugCount += 1 self.debugNumber = UIAnimationFuture.debugCount if debug { print("animation #\(self.debugNumber)") } self.identifier = UUID().uuidString } deinit { if debug { print("deinit \(self)") } } /** An array of all "root" animations for all currently animating chains. I.e. this array contains the first link in each currently animating chain. Handy if you want to cancel all chains - just loop over `animations` and call `cancelAnimationChain` on each one. */ public static var animations: [UIAnimationFuture] = [] //MARK: Animation methods @discardableResult public func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void) -> UIAnimationFuture { return animate(withDuration: duration, animations: animations, completion: completion) } @discardableResult public func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { return animate(withDuration: duration, delay: delay, options: [], animations: animations, completion: completion) } @discardableResult public func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { return animateAndChain(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion) } @discardableResult public func animate(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { let anim = animateAndChain(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion) self.springDamping = dampingRatio self.springVelocity = velocity return anim } @discardableResult public func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { var options = options if options.contains(.repeat) { options.remove(.repeat) loopsChain = true } self.duration = duration self.delay = delay self.options = options self.animations = animations self.completion = completion nextDelayedAnimation = UIAnimationFuture() nextDelayedAnimation!.prevDelayedAnimation = self return nextDelayedAnimation! } //MARK: - Animation control methods /** A method to cancel the animation chain of the current animation. This method cancels and removes all animations that are chained to each other in one chain. The animations will not stop immediately - the currently running animation will finish and then the complete chain will be stopped and removed. :param: completion completion closure */ public func cancelAnimationChain(_ completion: (()->Void)? = nil) { UIAnimationFuture.cancelCompletions[identifier] = completion var link = self while link.nextDelayedAnimation != nil { link = link.nextDelayedAnimation! } link.detachFromChain() if debug { print("cancelled top animation: \(link)") } } private func detachFromChain() { self.nextDelayedAnimation = nil if let previous = self.prevDelayedAnimation { if debug { print("dettach \(self)") } previous.nextDelayedAnimation = nil previous.detachFromChain() } else { if let index = UIAnimationFuture.animations.index(of: self) { if debug { print("cancel root animation #\(UIAnimationFuture.animations[index])") } UIAnimationFuture.animations.remove(at: index) } } self.prevDelayedAnimation = nil } func run() { if debug { print("run animation #\(debugNumber)") } //TODO: Check if layer-only animations fire a proper completion block if let animations = animations { options.insert(.beginFromCurrentState) let animationDelay = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * self.delay )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: animationDelay) { if self.springDamping > 0.0 { //spring animation UIView.animate(withDuration: self.duration, delay: 0, usingSpringWithDamping: self.springDamping, initialSpringVelocity: self.springVelocity, options: self.options, animations: animations, completion: self.animationCompleted) } else { //basic animation UIView.animate(withDuration: self.duration, delay: 0, options: self.options, animations: animations, completion: self.animationCompleted) } } } } private func animationCompleted(_ finished: Bool) { //animation's own completion self.completion?(finished) //chain has been cancelled if let cancelCompletion = UIAnimationFuture.cancelCompletions[identifier] { if debug { print("run chain cancel completion") } cancelCompletion() detachFromChain() return } //check for .Repeat if finished && self.loopsChain { //find first animation in the chain and run it next var link = self while link.prevDelayedAnimation != nil { link = link.prevDelayedAnimation! } if debug { print("loop to \(link)") } link.run() return } //run next or destroy chain if self.nextDelayedAnimation?.animations != nil { self.nextDelayedAnimation?.run() } else { //last animation in the chain self.detachFromChain() } } public var description: String { get { if debug { return "animation #\(self.debugNumber) [\(self.identifier)] prev: \(self.prevDelayedAnimation?.debugNumber ?? 0) next: \(self.nextDelayedAnimation?.debugNumber ?? 0)" } else { return "<EADelayedAnimation>" } } } } public func == (lhs: UIAnimationFuture , rhs: UIAnimationFuture) -> Bool { return lhs === rhs } extension UIView{ // MARK: chain animations /** Creates and runs an animation which allows other animations to be chained to it and to each other. :param: duration The animation duration in seconds :param: delay The delay before the animation starts :param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info) :param: animations Animation closure :param: completion Completion closure of type (Bool)->Void :returns: The created request. */ public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { let currentAnimation = UIAnimationFuture() currentAnimation.duration = duration currentAnimation.delay = delay currentAnimation.options = options currentAnimation.animations = animations currentAnimation.completion = completion currentAnimation.nextDelayedAnimation = UIAnimationFuture() currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation currentAnimation.run() UIAnimationFuture.animations.append(currentAnimation) return currentAnimation.nextDelayedAnimation! } /** Creates and runs an animation which allows other animations to be chained to it and to each other. :param: duration The animation duration in seconds :param: delay The delay before the animation starts :param: usingSpringWithDamping the spring damping :param: initialSpringVelocity initial velocity of the animation :param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info) :param: animations Animation closure :param: completion Completion closure of type (Bool)->Void :returns: The created request. */ public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture { let currentAnimation = UIAnimationFuture() currentAnimation.duration = duration currentAnimation.delay = delay currentAnimation.options = options currentAnimation.animations = animations currentAnimation.completion = completion currentAnimation.springDamping = dampingRatio currentAnimation.springVelocity = velocity currentAnimation.nextDelayedAnimation = UIAnimationFuture() currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation currentAnimation.run() UIAnimationFuture.animations.append(currentAnimation) return currentAnimation.nextDelayedAnimation! } /** Creates and runs an animation which allows other animations to be chained to it and to each other. :param: duration The animation duration in seconds :param: timing A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info) :param: animations Animation closure :param: completion Completion closure of type (Bool)->Void :returns: The created request. */ public class func animate(withDuration duration: TimeInterval, timingFunction: CAMediaTimingFunction, animations: @escaping () -> Void, completion: (() -> Void)?) -> Void { UIView.beginAnimations(nil, context: nil) CATransaction.begin() CATransaction.setAnimationDuration(duration) CATransaction.setAnimationTimingFunction(timingFunction) CATransaction.setCompletionBlock(completion) animations() CATransaction.commit() UIView.commitAnimations() } }
e8262fcc84d2b63f673cd2c847a77614
38.295455
304
0.655654
false
false
false
false
Ivacker/swift
refs/heads/master
test/Sema/enum_raw_representable_multi_file.swift
apache-2.0
14
// RUN: %target-swift-frontend -parse -verify -primary-file %s %S/Inputs/enum_multi_file_helper.swift var raw1: Int = Foo.A.rawValue var raw2: Bar.RawValue = 0 var cooked1: Foo? = Foo(rawValue: raw1) var cooked2: Bar? = Bar(rawValue: 22) var cooked3: Baz? = Baz(rawValue: 0) var cooked4: Garply? = Garply(rawValue: "A") func consume<T: RawRepresentable>(obj: T) {} func test() { consume(cooked1!) consume(cooked2!) consume(cooked3!) consume(cooked4!) }
1b65519bf206014fe44784559d85b446
27.9375
101
0.697624
false
true
false
false
albinekcom/BitBay-Ticker-iOS
refs/heads/master
Codebase/Common/ReviewController.swift
mit
1
import StoreKit final class ReviewController { private let storeReviewController: SKStoreReviewController.Type private let userDefaults: UserDefaults private let counterMaximum = 10 private let counterKey = "counter" private var counter: Int { get { userDefaults.integer(forKey: counterKey) } set { userDefaults.set(newValue, forKey: counterKey) } } init(storeReviewController: SKStoreReviewController.Type = SKStoreReviewController.self, userDefaults: UserDefaults = .standard) { self.storeReviewController = storeReviewController self.userDefaults = userDefaults } func tryToDisplay(in activeScene: UIWindowScene) { counter += 1 if counter >= counterMaximum { counter = 0 // storeReviewController.requestReview(in: activeScene) // TODO: Uncomment before shipping AnalyticsService.shared.trackReviewRequested() } } }
e95af3a0b2a665ea5b8de8d065d6e287
27.621622
101
0.629839
false
false
false
false
lemberg/obd2-swift-lib
refs/heads/master
OBD2-Swift/Classes/Model/Response.swift
mit
1
// // Response.swift // OBD2Swift // // Created by Max Vitruk on 5/25/17. // Copyright © 2017 Lemberg. All rights reserved. // import Foundation public struct Response : Hashable, Equatable { var timestamp : Date var mode : Mode = .none var pid : UInt8 = 0 var data : Data? var rawData : [UInt8] = [] public var strigDescriptor : String? init() { self.timestamp = Date() } public var hashValue: Int { return Int(mode.rawValue ^ pid) } public static func ==(lhs: Response, rhs: Response) -> Bool { return false } public var hasData : Bool { return data == nil } }
2cb97e896d19ac522082b49ea552d40f
16.942857
63
0.617834
false
false
false
false
joalbright/Gameboard
refs/heads/master
Gameboards.playground/Sources/Boards/Checkers.swift
apache-2.0
1
import UIKit public struct Checkers { public enum PieceType: String { case none = " " case checker1 = "●" case checker2 = "○" case king1 = "◉" case king2 = "◎" } public static var board: Grid { return Grid([ 8 ✕ (EmptyPiece %% "●"), 8 ✕ ("●" %% EmptyPiece), 8 ✕ (EmptyPiece %% "●"), 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ ("○" %% EmptyPiece), 8 ✕ (EmptyPiece %% "○"), 8 ✕ ("○" %% EmptyPiece) ]) } public static let playerPieces = ["●◉","○◎"] public static func validateJump(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) -> Bool { let m1 = s2.0 - s1.0 let m2 = s2.1 - s1.1 let e1 = s1.0 + m1 / 2 let e2 = s1.1 + m2 / 2 guard let jumpedPieceType: PieceType = PieceType(rawValue: grid[e1,e2]), jumpedPieceType != .none else { return false } switch PieceType(rawValue: p1) ?? .none { case .checker1: guard m1 == 2 && abs(m2) == 2 else { return false } guard jumpedPieceType != .checker1, jumpedPieceType != .king1 else { return false } case .checker2: guard m1 == -2 && abs(m2) == 2 else { return false } guard jumpedPieceType != .checker2, jumpedPieceType != .king2 else { return false } case .king1: guard abs(m1) == 2 && abs(m2) == 2 else { return false } guard jumpedPieceType != .checker1, jumpedPieceType != .king1 else { return false } case .king2: guard abs(m1) == 2 && abs(m2) == 2 else { return false } guard jumpedPieceType != .checker2, jumpedPieceType != .king2 else { return false } case .none: return false } guard !hint else { return true } grid[e1,e2] = EmptyPiece // remove other player piece return true } public static func validateMove(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) throws -> Piece? { let m1 = s2.0 - s1.0 let m2 = s2.1 - s1.1 var kingPiece: PieceType? guard p2 == EmptyPiece else { throw MoveError.invalidmove } switch PieceType(rawValue: p1) ?? .none { case .checker1: guard (m1 == 1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove } if s2.c == grid.content.count - 1 { kingPiece = .king1 } case .checker2: guard (m1 == -1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove } if s2.c == 0 { kingPiece = .king2 } case .king1, .king2: guard (abs(m1) == 1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove } case .none: throw MoveError.incorrectpiece } guard !hint else { return nil } let piece = grid[s2.0,s2.1] grid[s2.0,s2.1] = kingPiece?.rawValue ?? p1 // place my piece in target square grid[s1.0,s1.1] = EmptyPiece // remove my piece from original square return piece } } extension Grid { public func checker(_ rect: CGRect, highlights: [Square], selected: Square?) -> UIView { let view = UIView(frame: rect) let w = rect.width / content.count let h = rect.height / content.count view.backgroundColor = colors.background view.layer.cornerRadius = 10 view.layer.masksToBounds = true for (r,row) in content.enumerated() { for (c,item) in row.enumerated() { var piece = "\(item)" let holder = UIView(frame: CGRect(x: c * w, y: r * h, width: w, height: h)) holder.backgroundColor = (c + r) % 2 == 0 ? colors.background : colors.foreground let label = HintLabel(frame: CGRect(x: 0, y: 0, width: w, height: h)) label.backgroundColor = .clear label.textColor = player(piece) == 0 ? colors.player1 : colors.player2 label.highlightColor = colors.highlight if player(piece) == 1 { if let index = playerPieces[1].array().index(of: piece) { piece = playerPieces[0].array()[index] } } if let selected = selected, selected.0 == r && selected.1 == c { label.textColor = colors.selected } for highlight in highlights { label.highlight = label.highlight ? true : highlight.0 == r && highlight.1 == c } label.text = piece label.textAlignment = .center label.font = UIFont(name: "Apple Symbols", size: (w + h) / 2 - 10) holder.addSubview(label) view.addSubview(holder) } } return view } }
1f9d5228ca872a8e2fb02453ebf8731d
30.448864
144
0.475339
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
refs/heads/master
iOS/Healthcare/Views/UICollectionViewFlowLayoutCenterItem.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** Custom collectionViewFlowLayout in order to have paging on the centered cell */ class UICollectionViewFlowLayoutCenterItem: UICollectionViewFlowLayout { /** Init method that sets default properties for collectionViewlayout - parameter viewWidth: width of screen to base paddings off of. - returns: UICollectionViewFlowLayout object */ init(viewWidth: CGFloat) { super.init() let cellSize: CGSize = CGSizeMake(65, 100) let inset = viewWidth/2 - cellSize.width/2 self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset) self.scrollDirection = UICollectionViewScrollDirection.Horizontal self.itemSize = CGSizeMake(cellSize.width, cellSize.height) self.minimumInteritemSpacing = 0 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Obj-C version taken from: https://gist.github.com/mmick66/9812223 // Method ensures a cell is centered when scrolling has ended override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { let width = self.collectionView!.bounds.size.width let proposedContentOffsetCenterX = proposedContentOffset.x + width * CGFloat(0.5) let proposedRect = self.layoutAttributesForElementsInRect(self.collectionView!.bounds)! var candidateAttributes: UICollectionViewLayoutAttributes? for attributes in proposedRect { // this ignores header and footer views if attributes.representedElementCategory != UICollectionElementCategory.Cell { continue } // set initial value first time through loop if (candidateAttributes == nil) { candidateAttributes = attributes continue } // if placement is desired, update candidateAttributes if (fabsf(Float(attributes.center.x) - Float(proposedContentOffsetCenterX)) < fabsf(Float(candidateAttributes!.center.x) - Float(proposedContentOffsetCenterX))) { candidateAttributes = attributes } } return CGPointMake(candidateAttributes!.center.x - width * CGFloat(0.5), proposedContentOffset.y) } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { let oldBounds = self.collectionView!.bounds if CGRectGetWidth(oldBounds) != CGRectGetWidth(newBounds) { return true } return false } }
d129e0a3850f5c41599e13d49aa462c3
35.802632
174
0.661423
false
false
false
false
giangbvnbgit128/AnViet
refs/heads/master
AnViet/Class/ViewControllers/TutorialViewController/AVTutorialViewController.swift
apache-2.0
1
// // AVTutorialViewController.swift // AnViet // // Created by Bui Giang on 5/25/17. // Copyright © 2017 Bui Giang. All rights reserved. // import UIKit class AVTutorialViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var btnRegis: UIButton! @IBOutlet weak var btnLogin: UIButton! @IBOutlet weak var pageControl: UIPageControl! let arrayImage:[String] = ["tutorial1","tutorial1","tutorial2","tutorial3", "tutorial4","tutorial1","tutorial1","tutorial0"] override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.registerNib(AVTutorialCollectionViewCell.self) self.automaticallyAdjustsScrollViewInsets = false self.pageControl.currentPage = 0 self.btnLogin.layer.cornerRadius = 4 self.btnRegis.layer.cornerRadius = 4 self.pageControl.numberOfPages = arrayImage.count navigationController?.navigationBar.isTranslucent = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func movePageControlWithScroll () { let pageWidth = collectionView.frame.width let page = Int(floor((collectionView.contentOffset.x - pageWidth / 2) / pageWidth) + 1) if pageControl.currentPage != page { self.pageControl.currentPage = page } } @IBAction func actionLogin(_ sender: AnyObject) { let logicVC = AVLoginViewController() navigationController?.pushViewController(logicVC, animated: true) } @IBAction func actionRegis(_ sender: AnyObject) { let regisVC = AVRegisterAccountAccountViewController() navigationController?.pushViewController(regisVC, animated: true) } } extension AVTutorialViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.arrayImage.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeue(AVTutorialCollectionViewCell.self, forIndexPath: indexPath) as AVTutorialCollectionViewCell cell.ConfigCell(nameImage: self.arrayImage[indexPath.row]) return cell } } extension AVTutorialViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return UIScreen.main.bounds.size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.1 } } extension AVTutorialViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { movePageControlWithScroll() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { movePageControlWithScroll() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { print("====Scroll \(scrollView.contentOffset.x) prin y = \(scrollView.contentOffset.y)") } }
3cdb13ccf63d110959d7830975c82551
37.548077
133
0.700923
false
false
false
false
Anish-kumar-dev/instagram-swift
refs/heads/master
instagram-swift/instagram-swift/instagram-swift/Login/SLLoginViewController.swift
mit
2
// // SLLoginViewController.swift // instagram-swift // // Created by Dimas Gabriel on 10/21/14. // Copyright (c) 2014 Swift Libs. All rights reserved. // import UIKit protocol SLLoginViewControllerDelegate { func loginViewControllerDidCancel(vc: SLLoginViewController) func loginViewControllerDidLogin(accesToken: String) func loginViewControllerDidError(error : NSError) } class SLLoginViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var mainWebView: UIWebView! var delegate: SLLoginViewControllerDelegate? var redirectURI : String? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: "SLLoginViewController", bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.mainWebView.delegate = self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancelButtonTap(sender: UIBarButtonItem) { self.delegate?.loginViewControllerDidCancel(self) self.dismissViewControllerAnimated(true, completion: nil) } func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool { if (self.redirectURI != nil){ var urlStr = request.URL.absoluteString if (urlStr?.hasPrefix(self.redirectURI!) == true) { urlStr = urlStr!.stringByReplacingOccurrencesOfString("?", withString: "", options:nil, range:nil) urlStr = urlStr!.stringByReplacingOccurrencesOfString("#", withString: "", options:nil, range:nil) let urlResources = urlStr!.componentsSeparatedByString("/") let urlParameters = urlResources.last let parameters = urlParameters?.componentsSeparatedByString("&") if parameters?.count == 1 { let keyValue = parameters![0] let keyValueArray = keyValue.componentsSeparatedByString("=") let key = keyValueArray[0] if key == "access_token" { self.delegate?.loginViewControllerDidLogin(keyValueArray[1]) self.dismissViewControllerAnimated(true, completion: nil) } }else { // We have an error let errorString = "Authorization not granted" let error = NSError(domain: kSLInstagramEngineErrorDomain, code: kSLInstagramEngineErrorCodeAccessNotGranted, userInfo: [NSLocalizedDescriptionKey : errorString]) self.delegate?.loginViewControllerDidError(error) } return false } } return true } }
495628bcf72ceeca6a7522b9495e126c
36.114943
139
0.594302
false
false
false
false
TonyReet/AutoSQLite.swift
refs/heads/development
AutoSQLite.swift/Pods/SQLite.swift/Sources/SQLite/Typed/Coding.swift
apache-2.0
8
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension QueryType { /// Creates an `INSERT` statement by encoding the given object /// This method converts any custom nested types to JSON data and does not handle any sort /// of object relationships. If you want to support relationships between objects you will /// have to provide your own Encodable implementations that encode the correct ids. /// /// - Parameters: /// /// - encodable: An encodable object to insert /// /// - userInfo: User info to be passed to encoder /// /// - otherSetters: Any other setters to include in the insert /// /// - Returns: An `INSERT` statement fort the encodable object public func insert(_ encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Insert { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.insert(encoder.setters + otherSetters) } /// Creates an `UPDATE` statement by encoding the given object /// This method converts any custom nested types to JSON data and does not handle any sort /// of object relationships. If you want to support relationships between objects you will /// have to provide your own Encodable implementations that encode the correct ids. /// /// - Parameters: /// /// - encodable: An encodable object to insert /// /// - userInfo: User info to be passed to encoder /// /// - otherSetters: Any other setters to include in the insert /// /// - Returns: An `UPDATE` statement fort the encodable object public func update(_ encodable: Encodable, userInfo: [CodingUserInfoKey:Any] = [:], otherSetters: [Setter] = []) throws -> Update { let encoder = SQLiteEncoder(userInfo: userInfo) try encodable.encode(to: encoder) return self.update(encoder.setters + otherSetters) } } extension Row { /// Decode an object from this row /// This method expects any custom nested types to be in the form of JSON data and does not handle /// any sort of object relationships. If you want to support relationships between objects you will /// have to provide your own Decodable implementations that decodes the correct columns. /// /// - Parameter: userInfo /// /// - Returns: a decoded object from this row public func decode<V: Decodable>(userInfo: [CodingUserInfoKey: Any] = [:]) throws -> V { return try V(from: self.decoder(userInfo: userInfo)) } public func decoder(userInfo: [CodingUserInfoKey: Any] = [:]) -> Decoder { return SQLiteDecoder(row: self, userInfo: userInfo) } } /// Generates a list of settings for an Encodable object fileprivate class SQLiteEncoder: Encoder { class SQLiteKeyedEncodingContainer<MyKey: CodingKey>: KeyedEncodingContainerProtocol { typealias Key = MyKey let encoder: SQLiteEncoder let codingPath: [CodingKey] = [] init(encoder: SQLiteEncoder) { self.encoder = encoder } func superEncoder() -> Swift.Encoder { fatalError("SQLiteEncoding does not support super encoders") } func superEncoder(forKey key: Key) -> Swift.Encoder { fatalError("SQLiteEncoding does not support super encoders") } func encodeNil(forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer<Key>.Key) throws { self.encoder.setters.append(Expression<String?>(key.stringValue) <- nil) } func encode(_ value: Int, forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer<Key>.Key) throws { self.encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: Bool, forKey key: Key) throws { self.encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: Float, forKey key: Key) throws { self.encoder.setters.append(Expression(key.stringValue) <- Double(value)) } func encode(_ value: Double, forKey key: Key) throws { self.encoder.setters.append(Expression(key.stringValue) <- value) } func encode(_ value: String, forKey key: Key) throws { self.encoder.setters.append(Expression(key.stringValue) <- value) } func encode<T>(_ value: T, forKey key: Key) throws where T : Swift.Encodable { if let data = value as? Data { self.encoder.setters.append(Expression(key.stringValue) <- data) } else { let encoded = try JSONEncoder().encode(value) let string = String(data: encoded, encoding: .utf8) self.encoder.setters.append(Expression(key.stringValue) <- string) } } func encode(_ value: Int8, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int8 is not supported")) } func encode(_ value: Int16, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int16 is not supported")) } func encode(_ value: Int32, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int32 is not supported")) } func encode(_ value: Int64, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an Int64 is not supported")) } func encode(_ value: UInt, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt is not supported")) } func encode(_ value: UInt8, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt8 is not supported")) } func encode(_ value: UInt16, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt16 is not supported")) } func encode(_ value: UInt32, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt32 is not supported")) } func encode(_ value: UInt64, forKey key: Key) throws { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: self.codingPath, debugDescription: "encoding an UInt64 is not supported")) } func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError("encoding a nested container is not supported") } func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { fatalError("encoding nested values is not supported") } } fileprivate var setters: [Setter] = [] let codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey: Any] init(userInfo: [CodingUserInfoKey: Any]) { self.userInfo = userInfo } func singleValueContainer() -> SingleValueEncodingContainer { fatalError("not supported") } func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("not supported") } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { return KeyedEncodingContainer(SQLiteKeyedEncodingContainer(encoder: self)) } } fileprivate class SQLiteDecoder : Decoder { class SQLiteKeyedDecodingContainer<MyKey: CodingKey> : KeyedDecodingContainerProtocol { typealias Key = MyKey let codingPath: [CodingKey] = [] let row: Row init(row: Row) { self.row = row } var allKeys: [Key] { return self.row.columnNames.keys.compactMap({Key(stringValue: $0)}) } func contains(_ key: Key) -> Bool { return self.row.hasValue(for: key.stringValue) } func decodeNil(forKey key: Key) throws -> Bool { return !self.contains(key) } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try self.row.get(Expression(key.stringValue)) } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try self.row.get(Expression(key.stringValue)) } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int8 is not supported")) } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int16 is not supported")) } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an Int32 is not supported")) } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt64 is not supported")) } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt is not supported")) } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt8 is not supported")) } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt16 is not supported")) } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt32 is not supported")) } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an UInt64 is not supported")) } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return Float(try self.row.get(Expression<Double>(key.stringValue))) } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try self.row.get(Expression(key.stringValue)) } func decode(_ type: String.Type, forKey key: Key) throws -> String { return try self.row.get(Expression(key.stringValue)) } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Swift.Decodable { if type == Data.self { let data = try self.row.get(Expression<Data>(key.stringValue)) return data as! T } guard let JSONString = try self.row.get(Expression<String?>(key.stringValue)) else { throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "an unsupported type was found")) } guard let data = JSONString.data(using: .utf8) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "invalid utf8 data found")) } return try JSONDecoder().decode(type, from: data) } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding nested containers is not supported")) } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding unkeyed containers is not supported")) } func superDecoder() throws -> Swift.Decoder { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super encoders containers is not supported")) } func superDecoder(forKey key: Key) throws -> Swift.Decoder { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding super decoders is not supported")) } } let row: Row let codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey: Any] init(row: Row, userInfo: [CodingUserInfoKey: Any]) { self.row = row self.userInfo = userInfo } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { return KeyedDecodingContainer(SQLiteKeyedDecodingContainer(row: self.row)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding an unkeyed container is not supported")) } func singleValueContainer() throws -> SingleValueDecodingContainer { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "decoding a single value container is not supported")) } }
a8d4fa123cb6547367fac233d2fc4d65
44.820588
170
0.672444
false
false
false
false
lanit-tercom-school/grouplock
refs/heads/master
GroupLockiOS/GroupLock/Scenes/Home_Stack/ProvideKeyScene/ProvideKeyRouter.swift
apache-2.0
1
// // ProvideKeyRouter.swift // GroupLock // // Created by Sergej Jaskiewicz on 18.07.16. // Copyright (c) 2016 Lanit-Tercom School. All rights reserved. // import UIKit protocol ProvideKeyRouterInput { } class ProvideKeyRouter: ProvideKeyRouterInput { weak var viewController: ProvideKeyViewController! // MARK: - Navigation // MARK: - Communication func passDataToNextScene(_ segue: UIStoryboardSegue) { if segue.identifier == "ProcessedFile" { passDataToProcessedFileScene(segue) } } func passDataToProcessedFileScene(_ segue: UIStoryboardSegue) { // swiftlint:disable:next force_cast (since the destination is known) let processedFileViewController = segue.destination as! ProcessedFileViewController processedFileViewController.output.files = viewController.output.files processedFileViewController.output.cryptographicKey = viewController.output.keys processedFileViewController.output.isEncryption = true } }
659fa37a0fa9ea97bc71d522eb8977a1
24.725
91
0.724976
false
false
false
false
Sajjon/ViewComposer
refs/heads/master
Source/Classes/ViewAttribute/AttributedValues/DataSourceOwner.swift
mit
1
// // DataSourceOwner.swift // ViewComposer // // Created by Alexander Cyon on 2017-06-11. // // import Foundation protocol DataSourceOwner: class { var dataSourceProxy: NSObjectProtocol? { get set } } internal extension DataSourceOwner { func apply(_ style: ViewStyle) { style.attributes.forEach { switch $0 { case .dataSource(let dataSource): dataSourceProxy = dataSource case .dataSourceDelegate(let dataSource): dataSourceProxy = dataSource default: break } } } } extension UITableView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UITableViewDataSource else { return } self.dataSource = specificDataSource } } } extension UICollectionView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UICollectionViewDataSource else { return } self.dataSource = specificDataSource } } } extension UIPickerView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UIPickerViewDataSource else { return } self.dataSource = specificDataSource } } }
abb3511d58297c6673d77e11b5c37529
25.293103
98
0.622951
false
false
false
false
Ivacker/swift
refs/heads/master
utils/benchmark/Graph/prims.swift
apache-2.0
9
//===--- prims.swift - Implementation of Prims MST algorithm --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_silgen_name("mach_absolute_time") func __mach_absolute_time__() -> UInt64 struct Node { var id : Int var adjList : Array<Int> init(i : Int) { id = i adjList = Array<Int>() } } struct NodeCost { var nodeId : Int var cost : Double } func getLeftChildIndex(index : Int) -> Int { return index*2 + 1 } func getRightChildIndex(index : Int) -> Int { return (index + 1)*2 } func getParentIndex(childIndex : Int) -> Int { return (childIndex - 1)/2 } class PriorityQueue { var heap : Array<NodeCost?> var graphIndexToHeapIndexMap : Array<Int?> init() { heap = Array<NodeCost?>() graphIndexToHeapIndexMap = Array<Int?>() } // This should only be called when initializing an uninitialized queue. func append(n : NodeCost?) { heap.append(n) graphIndexToHeapIndexMap.append(n!.nodeId) } func dumpDebug() { print("QUEUE") for nodeCost in heap { let nodeId : Int = nodeCost!.nodeId let cost : Double = nodeCost!.cost print("(\(nodeId), \(cost))") } } func contains(i : Int) -> Bool { for nodeCost in heap { if nodeCost!.nodeId == i { return true } } return false } func checkInvariants(graph : Array<Node>) { // If the heap is empty, skip everything. if heap.isEmpty { return } var s = Array<Int>() s.append(0) while !s.isEmpty { let index = s.popLast(); let leftChild = getLeftChildIndex(index); let rightChild = getRightChildIndex(index); if (leftChild < heap.count) { if heap[leftChild]!.cost < heap[index]!.cost { print("Left: \(heap[leftChild]!.cost); Parent: \(heap[index]!.cost)") } assert(heap[leftChild]!.cost >= heap[index]!.cost); s.append(leftChild); } if (rightChild < heap.count) { if heap[rightChild]!.cost < heap[index]!.cost { print("Right: \(heap[rightChild]!.cost); Parent: \(heap[index]!.cost)") } assert(heap[rightChild]!.cost >= heap[index]!.cost); s.append(rightChild); } } // Make sure that each element in the graph that is not in the heap has // its index set to .None for i in 0..graph.count { if contains(i) { assert(graphIndexToHeapIndexMap[i] != .None, "All items contained in the heap must have an index assigned in map.") } else { assert(graphIndexToHeapIndexMap[i] == .None, "All items not in heap must not have an index assigned in map.") } } } // Pop off the smallest cost element, updating all data structures along the // way. func popHeap() -> NodeCost { // If we only have one element, just return it. if heap.count == 1 { return heap.popLast()! } // Otherwise swap the heap head with the last element of the heap and pop // the heap. swap(&heap[0], &heap[heap.count-1]) let result = heap.popLast() // Invalidate the graph index of our old head and update the graph index of // the new head value. graphIndexToHeapIndexMap[heap[0]!.nodeId] = .Some(0) graphIndexToHeapIndexMap[result!.nodeId] = .None // Re-establish the heap property. var heapIndex = 0 var smallestIndex : Int while true { smallestIndex = updateHeapAtIndex(heapIndex) if smallestIndex == heapIndex { break } heapIndex = smallestIndex } // Return result. return result! } func updateCostIfLessThan(graphIndex : Int, newCost : Double) -> Bool { // Look up the heap index corresponding to the input graph index. var heapIndex : Int? = graphIndexToHeapIndexMap[graphIndex] // If the graph index is not in the heap, return false. if heapIndex == .None { return false } // Otherwise, look up the cost of the node. let nodeCost = heap[heapIndex!] // If newCost >= nodeCost.1, don't update anything and return false. if newCost >= nodeCost!.cost { return false } // Ok, we know that newCost < nodeCost.1 so replace nodeCost.1 with // newCost and update all relevant data structures. Return true. heap[heapIndex!] = .Some(NodeCost(nodeCost!.nodeId, newCost)) while heapIndex != .None && heapIndex! > 0 { heapIndex = .Some(getParentIndex(heapIndex!)) updateHeapAtIndex(heapIndex!) } return true } func updateHeapAtIndex(index : Int) -> Int { let leftChildIndex : Int = getLeftChildIndex(index) let rightChildIndex : Int = getRightChildIndex(index) var smallestIndex : Int = 0 if leftChildIndex < heap.count && heap[leftChildIndex]!.cost < heap[index]!.cost { smallestIndex = leftChildIndex } else { smallestIndex = index } if rightChildIndex < heap.count && heap[rightChildIndex]!.cost < heap[smallestIndex]!.cost { smallestIndex = rightChildIndex } if smallestIndex != index { swap(&graphIndexToHeapIndexMap[heap[index]!.nodeId], &graphIndexToHeapIndexMap[heap[smallestIndex]!.nodeId]) swap(&heap[index], &heap[smallestIndex]) } return smallestIndex } func isEmpty() -> Bool { return heap.isEmpty } } func prim( graph : Array<Node>, fun : (Int, Int) -> Double) -> Array<Int?> { var treeEdges = Array<Int?>() // Create our queue, selecting the first element of the grpah as the root of // our tree for simplciity. var queue = PriorityQueue() queue.append(.Some(NodeCost(0, 0.0))) // Make the minimum spanning tree root its own parent for simplicity. treeEdges.append(.Some(0)) // Create the graph. for i in 1..graph.count { queue.append(.Some(NodeCost(i, Double.inf()))) treeEdges.append(.None) } while !queue.isEmpty() { let e = queue.popHeap() let nodeId = e.nodeId for adjNodeIndex in graph[nodeId].adjList { if queue.updateCostIfLessThan(adjNodeIndex, fun(graph[nodeId].id, graph[adjNodeIndex].id)) { treeEdges[adjNodeIndex] = .Some(nodeId) } } } return treeEdges } struct Edge : Equatable { var start : Int var end : Int } func ==(lhs: Edge, rhs: Edge) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end } extension Edge : Hashable { func hashValue() -> Int { return start.hashValue() ^ end.hashValue() } } func benchPrimsInternal(iterations: Int) { for i in 0..iterations { var graph = Array<Node>() var nodes : Int[] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 ] var edges : (Int, Int, Double)[] = [ (26, 47, 921), (20, 25, 971), (92, 59, 250), (33, 55, 1391), (78, 39, 313), (7, 25, 637), (18, 19, 1817), (33, 41, 993), (64, 41, 926), (88, 86, 574), (93, 15, 1462), (86, 33, 1649), (37, 35, 841), (98, 51, 1160), (15, 30, 1125), (65, 78, 1052), (58, 12, 1273), (12, 17, 285), (45, 61, 1608), (75, 53, 545), (99, 48, 410), (97, 0, 1303), (48, 17, 1807), (1, 54, 1491), (15, 34, 807), (94, 98, 646), (12, 69, 136), (65, 11, 983), (63, 83, 1604), (78, 89, 1828), (61, 63, 845), (18, 36, 1626), (68, 52, 1324), (14, 50, 690), (3, 11, 943), (21, 68, 914), (19, 44, 1762), (85, 80, 270), (59, 92, 250), (86, 84, 1431), (19, 18, 1817), (52, 68, 1324), (16, 29, 1108), (36, 80, 395), (67, 18, 803), (63, 88, 1717), (68, 21, 914), (75, 82, 306), (49, 82, 1292), (73, 45, 1876), (89, 82, 409), (45, 47, 272), (22, 83, 597), (61, 12, 1791), (44, 68, 1229), (50, 51, 917), (14, 53, 355), (77, 41, 138), (54, 21, 1870), (93, 70, 1582), (76, 2, 1658), (83, 73, 1162), (6, 1, 482), (11, 65, 983), (81, 90, 1024), (19, 1, 970), (8, 58, 1131), (60, 42, 477), (86, 29, 258), (69, 59, 903), (34, 15, 807), (37, 2, 1451), (7, 73, 754), (47, 86, 184), (67, 17, 449), (18, 67, 803), (25, 4, 595), (3, 31, 1337), (64, 31, 1928), (9, 43, 237), (83, 63, 1604), (47, 45, 272), (86, 88, 574), (87, 74, 934), (98, 94, 646), (20, 1, 642), (26, 92, 1344), (18, 17, 565), (47, 11, 595), (10, 59, 1558), (2, 76, 1658), (77, 74, 1277), (42, 60, 477), (80, 36, 395), (35, 23, 589), (50, 37, 203), (6, 96, 481), (78, 65, 1052), (1, 52, 127), (65, 23, 1932), (46, 51, 213), (59, 89, 89), (15, 93, 1462), (69, 3, 1305), (17, 37, 1177), (30, 3, 193), (9, 15, 818), (75, 95, 977), (86, 47, 184), (10, 12, 1736), (80, 27, 1010), (12, 10, 1736), (86, 1, 1958), (60, 12, 1240), (43, 71, 683), (91, 65, 1519), (33, 86, 1649), (62, 26, 1773), (1, 13, 1187), (2, 10, 1018), (91, 29, 351), (69, 12, 136), (43, 9, 237), (29, 86, 258), (17, 48, 1807), (31, 64, 1928), (68, 61, 1936), (76, 38, 1724), (1, 6, 482), (53, 14, 355), (51, 50, 917), (54, 13, 815), (19, 29, 883), (35, 87, 974), (70, 96, 511), (23, 35, 589), (39, 69, 1588), (93, 73, 1093), (13, 73, 435), (5, 60, 1619), (42, 41, 1523), (66, 58, 1596), (1, 67, 431), (17, 67, 449), (30, 95, 906), (71, 43, 683), (5, 87, 190), (12, 78, 891), (30, 97, 402), (28, 17, 1131), (7, 97, 1356), (58, 66, 1596), (20, 37, 1294), (73, 76, 514), (54, 8, 613), (68, 35, 1252), (92, 32, 701), (3, 90, 652), (99, 46, 1576), (13, 54, 815), (20, 87, 1390), (36, 18, 1626), (51, 26, 1146), (2, 23, 581), (29, 7, 1558), (88, 59, 173), (17, 1, 1071), (37, 49, 1011), (18, 6, 696), (88, 33, 225), (58, 38, 802), (87, 50, 1744), (29, 91, 351), (6, 71, 1053), (45, 24, 1720), (65, 91, 1519), (37, 50, 203), (11, 3, 943), (72, 65, 1330), (45, 50, 339), (25, 20, 971), (15, 9, 818), (14, 54, 1353), (69, 95, 393), (8, 66, 1213), (52, 2, 1608), (50, 14, 690), (50, 45, 339), (1, 37, 1273), (45, 93, 1650), (39, 78, 313), (1, 86, 1958), (17, 28, 1131), (35, 33, 1667), (23, 2, 581), (51, 66, 245), (17, 54, 924), (41, 49, 1629), (60, 5, 1619), (56, 93, 1110), (96, 13, 461), (25, 7, 637), (11, 69, 370), (90, 3, 652), (39, 71, 1485), (65, 51, 1529), (20, 6, 1414), (80, 85, 270), (73, 83, 1162), (0, 97, 1303), (13, 33, 826), (29, 71, 1788), (33, 12, 461), (12, 58, 1273), (69, 39, 1588), (67, 75, 1504), (87, 20, 1390), (88, 97, 526), (33, 88, 225), (95, 69, 393), (2, 52, 1608), (5, 25, 719), (34, 78, 510), (53, 99, 1074), (33, 35, 1667), (57, 30, 361), (87, 58, 1574), (13, 90, 1030), (79, 74, 91), (4, 86, 1107), (64, 94, 1609), (11, 12, 167), (30, 45, 272), (47, 91, 561), (37, 17, 1177), (77, 49, 883), (88, 23, 1747), (70, 80, 995), (62, 77, 907), (18, 4, 371), (73, 93, 1093), (11, 47, 595), (44, 23, 1990), (20, 0, 512), (3, 69, 1305), (82, 3, 1815), (20, 88, 368), (44, 45, 364), (26, 51, 1146), (7, 65, 349), (71, 39, 1485), (56, 88, 1954), (94, 69, 1397), (12, 28, 544), (95, 75, 977), (32, 90, 789), (53, 1, 772), (54, 14, 1353), (49, 77, 883), (92, 26, 1344), (17, 18, 565), (97, 88, 526), (48, 80, 1203), (90, 32, 789), (71, 6, 1053), (87, 35, 974), (55, 90, 1808), (12, 61, 1791), (1, 96, 328), (63, 10, 1681), (76, 34, 871), (41, 64, 926), (42, 97, 482), (25, 5, 719), (23, 65, 1932), (54, 1, 1491), (28, 12, 544), (89, 10, 108), (27, 33, 143), (67, 1, 431), (32, 45, 52), (79, 33, 1871), (6, 55, 717), (10, 58, 459), (67, 39, 393), (10, 4, 1808), (96, 6, 481), (1, 19, 970), (97, 7, 1356), (29, 16, 1108), (1, 53, 772), (30, 15, 1125), (4, 6, 634), (6, 20, 1414), (88, 56, 1954), (87, 64, 1950), (34, 76, 871), (17, 12, 285), (55, 59, 321), (61, 68, 1936), (50, 87, 1744), (84, 44, 952), (41, 33, 993), (59, 18, 1352), (33, 27, 143), (38, 32, 1210), (55, 70, 1264), (38, 58, 802), (1, 20, 642), (73, 13, 435), (80, 48, 1203), (94, 64, 1609), (38, 28, 414), (73, 23, 1113), (78, 12, 891), (26, 62, 1773), (87, 43, 579), (53, 6, 95), (59, 95, 285), (88, 63, 1717), (17, 5, 633), (66, 8, 1213), (41, 42, 1523), (83, 22, 597), (95, 30, 906), (51, 65, 1529), (17, 49, 1727), (64, 87, 1950), (86, 4, 1107), (37, 98, 1102), (32, 92, 701), (60, 94, 198), (73, 98, 1749), (4, 18, 371), (96, 70, 511), (7, 29, 1558), (35, 37, 841), (27, 64, 384), (12, 33, 461), (36, 38, 529), (69, 16, 1183), (91, 47, 561), (85, 29, 1676), (3, 82, 1815), (69, 58, 1579), (93, 45, 1650), (97, 42, 482), (37, 1, 1273), (61, 4, 543), (96, 1, 328), (26, 0, 1993), (70, 64, 878), (3, 30, 193), (58, 69, 1579), (4, 25, 595), (31, 3, 1337), (55, 6, 717), (39, 67, 393), (78, 34, 510), (75, 67, 1504), (6, 53, 95), (51, 79, 175), (28, 91, 1040), (89, 78, 1828), (74, 93, 1587), (45, 32, 52), (10, 2, 1018), (49, 37, 1011), (63, 61, 845), (0, 20, 512), (1, 17, 1071), (99, 53, 1074), (37, 20, 1294), (10, 89, 108), (33, 92, 946), (23, 73, 1113), (23, 88, 1747), (49, 17, 1727), (88, 20, 368), (21, 54, 1870), (70, 93, 1582), (59, 88, 173), (32, 38, 1210), (89, 59, 89), (23, 44, 1990), (38, 76, 1724), (30, 57, 361), (94, 60, 198), (59, 10, 1558), (55, 64, 1996), (12, 11, 167), (36, 24, 1801), (97, 30, 402), (52, 1, 127), (58, 87, 1574), (54, 17, 924), (93, 74, 1587), (24, 36, 1801), (2, 37, 1451), (91, 28, 1040), (59, 55, 321), (69, 11, 370), (8, 54, 613), (29, 85, 1676), (44, 19, 1762), (74, 79, 91), (93, 56, 1110), (58, 10, 459), (41, 50, 1559), (66, 51, 245), (80, 19, 1838), (33, 79, 1871), (76, 73, 514), (98, 37, 1102), (45, 44, 364), (16, 69, 1183), (49, 41, 1629), (19, 80, 1838), (71, 57, 500), (6, 4, 634), (64, 27, 384), (84, 86, 1431), (5, 17, 633), (96, 88, 334), (87, 5, 190), (70, 21, 1619), (55, 33, 1391), (10, 63, 1681), (11, 62, 1339), (33, 13, 826), (64, 70, 878), (65, 72, 1330), (70, 55, 1264), (64, 55, 1996), (50, 41, 1559), (46, 99, 1576), (88, 96, 334), (51, 20, 868), (73, 7, 754), (80, 70, 995), (44, 84, 952), (29, 19, 883), (59, 69, 903), (57, 53, 1575), (90, 13, 1030), (28, 38, 414), (12, 60, 1240), (85, 58, 573), (90, 55, 1808), (4, 10, 1808), (68, 44, 1229), (92, 33, 946), (90, 81, 1024), (53, 75, 545), (45, 30, 272), (41, 77, 138), (21, 70, 1619), (45, 73, 1876), (35, 68, 1252), (13, 96, 461), (53, 57, 1575), (82, 89, 409), (28, 61, 449), (58, 61, 78), (27, 80, 1010), (61, 58, 78), (38, 36, 529), (80, 30, 397), (18, 59, 1352), (62, 11, 1339), (95, 59, 285), (51, 98, 1160), (6, 18, 696), (30, 80, 397), (69, 94, 1397), (58, 85, 573), (48, 99, 410), (51, 46, 213), (57, 71, 500), (91, 30, 104), (65, 7, 349), (79, 51, 175), (47, 26, 921), (4, 61, 543), (98, 73, 1749), (74, 77, 1277), (61, 28, 449), (58, 8, 1131), (61, 45, 1608), (74, 87, 934), (71, 29, 1788), (30, 91, 104), (13, 1, 1187), (0, 26, 1993), (82, 49, 1292), (43, 87, 579), (24, 45, 1720), (20, 51, 868), (77, 62, 907), (82, 75, 306), ] for n in nodes { graph.append(Node(n)) } var map = Dictionary<Edge, Double>() for tup in edges { map.add(Edge(tup.0, tup.1), tup.2) graph[tup.0].adjList.append(tup.1) } let treeEdges = prim(graph, { (start: Int, end: Int) in return map[Edge(start, end)] }) //for i in 0...treeEdges.count { // print("Node: \(i). Parent: \(treeEdges[i]!)") //} } } func benchPrims() { let start = __mach_absolute_time__() benchPrimsInternal(100) let delta = __mach_absolute_time__() - start print("\(delta) nanoseconds.") } benchPrims()
3f86e51f7635a141979ff43d9278b988
22.276119
81
0.454419
false
false
false
false
tangplin/JSON2Anything
refs/heads/master
JSON2Anything/Source/Extensions/Swift+J2A.swift
mit
1
// // Swift+J2A.swift // // Copyright (c) 2014 Pinglin Tang. // // 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. extension Int: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Int? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.integerValue } else if let o_s = o as? NSString { return o_s.integerValue } else { return nil } } } extension Float: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Float? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.floatValue } else if let o_s = o as? NSString { return o_s.floatValue } else { return nil } } } extension Double: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Double? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.doubleValue } else if let o_s = o as? NSString { return o_s.doubleValue } else { return nil } } } extension Bool: Anything { static func anythingWithJSON(argumentJSON:[AnyObject]) -> Bool? { if argumentJSON.count != 1 { return nil } let o : AnyObject = argumentJSON[0] if let o_n = o as? NSNumber { return o_n.boolValue } else if let o_s = o as? NSString { return o_s.boolValue } else { return nil } } }
a6f5d92d70b03ecc5a5bb43fcadcd9ab
27.627451
80
0.594724
false
false
false
false
alblue/swift
refs/heads/master
stdlib/public/core/DropWhile.swift
apache-2.0
2
//===--- DropWhile.swift - Lazy views for drop(while:) --------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the elements that follow the initial /// consecutive elements of some base sequence that satisfy a given predicate. @_fixed_layout // lazy-performance public struct LazyDropWhileSequence<Base: Sequence> { public typealias Element = Base.Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable // lazy-performance internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // lazy-performance internal var _base: Base @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool } extension LazyDropWhileSequence { /// An iterator over the elements traversed by a base iterator that follow the /// initial consecutive elements that satisfy a given predicate. /// /// This is the associated iterator for the `LazyDropWhileSequence`, /// `LazyDropWhileCollection`, and `LazyDropWhileBidirectionalCollection` /// types. @_fixed_layout // lazy-performance public struct Iterator { public typealias Element = Base.Element @inlinable // lazy-performance internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // lazy-performance internal var _predicateHasFailed = false @usableFromInline // lazy-performance internal var _base: Base.Iterator @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool } } extension LazyDropWhileSequence.Iterator: IteratorProtocol { @inlinable // lazy-performance public mutating func next() -> Element? { // Once the predicate has failed for the first time, the base iterator // can be used for the rest of the elements. if _predicateHasFailed { return _base.next() } // Retrieve and discard elements from the base iterator until one fails // the predicate. while let nextElement = _base.next() { if !_predicate(nextElement) { _predicateHasFailed = true return nextElement } } return nil } } extension LazyDropWhileSequence: Sequence { public typealias SubSequence = AnySequence<Element> // >:( /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // lazy-performance public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileSequence: LazySequenceProtocol { public typealias Elements = LazyDropWhileSequence } extension LazySequenceProtocol { /// Returns a lazy sequence that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // lazy-performance public __consuming func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileSequence<Self.Elements> { return LazyDropWhileSequence(_base: self.elements, predicate: predicate) } } /// A lazy wrapper that includes the elements of an underlying /// collection after any initial consecutive elements that satisfy a /// predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, or any methods /// that depend on `startIndex` depends on how many elements satisfy the /// predicate at the start of the collection, and may not offer the usual /// performance given by the `Collection` protocol. Be aware, therefore, /// that general operations on lazy collections may not have the /// documented complexity. @_fixed_layout // lazy-performance public struct LazyDropWhileCollection<Base: Collection> { public typealias Element = Base.Element @inlinable // lazy-performance internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // lazy-performance internal var _base: Base @usableFromInline // lazy-performance internal let _predicate: (Element) -> Bool } extension LazyDropWhileCollection: Sequence { public typealias Iterator = LazyDropWhileSequence<Base>.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // lazy-performance public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileCollection { public typealias SubSequence = Slice<LazyDropWhileCollection<Base>> /// A position in a `LazyDropWhileCollection` or /// `LazyDropWhileBidirectionalCollection` instance. @_fixed_layout // lazy-performance public struct Index { /// The position corresponding to `self` in the underlying collection. public let base: Base.Index @inlinable // lazy-performance internal init(_base: Base.Index) { self.base = _base } } } extension LazyDropWhileCollection.Index: Equatable, Comparable { @inlinable // lazy-performance public static func == ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base == rhs.base } @inlinable // lazy-performance public static func < ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base < rhs.base } } extension LazyDropWhileCollection.Index: Hashable where Base.Index: Hashable { /// The hash value. @inlinable public var hashValue: Int { return base.hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(base) } } extension LazyDropWhileCollection: Collection { @inlinable // lazy-performance public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && _predicate(_base[index]) { _base.formIndex(after: &index) } return Index(_base: index) } @inlinable // lazy-performance public var endIndex: Index { return Index(_base: _base.endIndex) } @inlinable // lazy-performance public func index(after i: Index) -> Index { _precondition(i.base < _base.endIndex, "Can't advance past endIndex") return Index(_base: _base.index(after: i.base)) } @inlinable // lazy-performance public subscript(position: Index) -> Element { return _base[position.base] } } extension LazyDropWhileCollection: LazyCollectionProtocol { } extension LazyDropWhileCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // lazy-performance public func index(before i: Index) -> Index { _precondition(i > startIndex, "Can't move before startIndex") return Index(_base: _base.index(before: i.base)) } } extension LazyCollectionProtocol { /// Returns a lazy collection that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the collection /// as its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // lazy-performance public __consuming func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileCollection<Self.Elements> { return LazyDropWhileCollection( _base: self.elements, predicate: predicate) } }
a2cee089d9a134efca6ad7a11dde37fa
31.627907
81
0.699572
false
false
false
false
podverse/podverse-ios
refs/heads/master
Podverse/DeletingPodcasts.swift
agpl-3.0
1
// // DeletingPodcasts.swift // Podverse // // Created by Mitchell Downey on 11/19/17. // Copyright © 2017 Podverse LLC. All rights reserved. // import Foundation final class DeletingPodcasts { static let shared = DeletingPodcasts() var podcastKeys = [String]() func addPodcast(podcastId:String?, feedUrl:String?) { if let podcastId = podcastId { if self.podcastKeys.filter({$0 == podcastId}).count < 1 { self.podcastKeys.append(podcastId) } } else if let feedUrl = feedUrl { if self.podcastKeys.filter({$0 == feedUrl}).count < 1 { self.podcastKeys.append(feedUrl) } } } func removePodcast(podcastId:String?, feedUrl:String?) { if let podcastId = podcastId, let index = self.podcastKeys.index(of: podcastId) { self.podcastKeys.remove(at: index) } else if let feedUrl = feedUrl, let index = self.podcastKeys.index(of: feedUrl) { self.podcastKeys.remove(at: index) } } func hasMatchingId(podcastId:String) -> Bool { if let _ = self.podcastKeys.index(of: podcastId) { return true } return false } func hasMatchingUrl(feedUrl:String) -> Bool { if let _ = self.podcastKeys.index(of: feedUrl) { return true } return false } }
b7ef44681426f898cef6f7be082d7a9d
27.098039
90
0.573622
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Cells/WPReusableTableViewCells.swift
gpl-2.0
2
import Foundation import UIKit import WordPressShared.WPTableViewCell class WPReusableTableViewCell: WPTableViewCell { override func prepareForReuse() { super.prepareForReuse() textLabel?.text = nil textLabel?.textAlignment = .natural textLabel?.adjustsFontSizeToFitWidth = false detailTextLabel?.text = nil detailTextLabel?.textColor = UIColor.black imageView?.image = nil accessoryType = .none accessoryView = nil selectionStyle = .default accessibilityLabel = nil } } class WPTableViewCellDefault: WPReusableTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class WPTableViewCellSubtitle: WPReusableTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class WPTableViewCellValue1: WPReusableTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class WPTableViewCellValue2: WPReusableTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .value2, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class WPTableViewCellBadge: WPTableViewCellDefault { var badgeCount: Int = 0 { didSet { if badgeCount > 0 { badgeLabel.text = String(badgeCount) accessoryView = badgeLabel accessoryType = .none } else { accessoryView = nil } } } fileprivate lazy var badgeLabel: UILabel = { let label = UILabel(frame: CGRect(origin: CGPoint.zero, size: WPTableViewCellBadge.badgeSize)) label.layer.masksToBounds = true label.layer.cornerRadius = WPTableViewCellBadge.badgeCornerRadius label.textAlignment = .center label.backgroundColor = WPStyleGuide.newKidOnTheBlockBlue() label.textColor = UIColor.white return label }() fileprivate static let badgeSize = CGSize(width: 50, height: 30) fileprivate static var badgeCornerRadius: CGFloat { return badgeSize.height / 2 } }
16b93528afc83642332fe5507cd82bd3
29.344444
102
0.672281
false
false
false
false
FengDeng/RXGitHub
refs/heads/master
Carthage/Checkouts/Moya/Source/Moya.swift
apache-2.0
5
import Foundation import Result /// Closure to be executed when a request has completed. public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> () /// Represents an HTTP method. public enum Method: String { case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT } public enum StubBehavior { case Never case Immediate case Delayed(seconds: NSTimeInterval) } /// Protocol to define the base URL, path, method, parameters and sample data for a target. public protocol TargetType { var baseURL: NSURL { get } var path: String { get } var method: Moya.Method { get } var parameters: [String: AnyObject]? { get } var sampleData: NSData { get } } /// Protocol to define the opaque type returned from a request public protocol Cancellable { func cancel() } /// Request provider class. Requests should be made through this class only. public class MoyaProvider<Target: TargetType> { /// Closure that defines the endpoints for the provider. public typealias EndpointClosure = Target -> Endpoint<Target> /// Closure that resolves an Endpoint into an NSURLRequest. public typealias RequestClosure = (Endpoint<Target>, NSURLRequest -> Void) -> Void /// Closure that decides if/how a request should be stubbed. public typealias StubClosure = Target -> Moya.StubBehavior public let endpointClosure: EndpointClosure public let requestClosure: RequestClosure public let stubClosure: StubClosure public let manager: Manager /// A list of plugins /// e.g. for logging, network activity indicator or credentials public let plugins: [PluginType] /// Initializes a provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = MoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = []) { self.endpointClosure = endpointClosure self.requestClosure = requestClosure self.stubClosure = stubClosure self.manager = manager self.plugins = plugins } /// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure. public func endpoint(token: Target) -> Endpoint<Target> { return endpointClosure(token) } /// Designated request-making method. Returns a Cancellable token to cancel the request later. public func request(target: Target, completion: Moya.Completion) -> Cancellable { let endpoint = self.endpoint(target) let stubBehavior = self.stubClosure(target) var cancellableToken = CancellableWrapper() let performNetworking = { (request: NSURLRequest) in if cancellableToken.isCancelled { return } switch stubBehavior { case .Never: cancellableToken.innerCancellable = self.sendRequest(target, request: request, completion: completion) default: cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior) } } requestClosure(endpoint, performNetworking) return cancellableToken } /// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method. /// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override. internal func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { let cancellableToken = CancellableToken { } notifyPluginsOfImpendingStub(request, target: target) let plugins = self.plugins let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins) switch stubBehavior { case .Immediate: stub() case .Delayed(let delay): let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC)) let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset) dispatch_after(killTime, dispatch_get_main_queue()) { stub() } case .Never: fatalError("Method called to stub request when stubbing is disabled.") } return cancellableToken } } /// Mark: Defaults public extension MoyaProvider { // These functions are default mappings to MoyaProvider's properties: endpoints, requests, manager, etc. public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> { let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) } public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: NSURLRequest -> Void) { return closure(endpoint.urlRequest) } public final class func DefaultAlamofireManager() -> Manager { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders let manager = Manager(configuration: configuration) manager.startRequestsImmediately = false return manager } } /// Mark: Stubbing public extension MoyaProvider { // Swift won't let us put the StubBehavior enum inside the provider class, so we'll // at least add some class functions to allow easy access to common stubbing closures. public final class func NeverStub(_: Target) -> Moya.StubBehavior { return .Never } public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior { return .Immediate } public final class func DelayedStub(seconds: NSTimeInterval)(_: Target) -> Moya.StubBehavior { return .Delayed(seconds: seconds) } } internal extension MoyaProvider { func sendRequest(target: Target, request: NSURLRequest, completion: Moya.Completion) -> CancellableToken { let alamoRequest = manager.request(request) let plugins = self.plugins // Give plugins the chance to alter the outgoing request plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } // Perform the actual request alamoRequest.response { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in let result = convertResponseToResult(response, data: data, error: error) // Inform all plugins about the response plugins.forEach { $0.didReceiveResponse(result, target: target) } completion(result: result) } alamoRequest.resume() return CancellableToken(request: alamoRequest) } /// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters. internal final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) { return { if (token.canceled) { let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) return } switch endpoint.sampleResponseClosure() { case .NetworkResponse(let statusCode, let data): let response = Moya.Response(statusCode: statusCode, data: data, response: nil) plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) } completion(result: .Success(response)) case .NetworkError(let error): let error = Moya.Error.Underlying(error) plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) } completion(result: .Failure(error)) } } } /// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`. internal final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) { let alamoRequest = manager.request(request) plugins.forEach { $0.willSendRequest(alamoRequest, target: target) } } } internal func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> Result<Moya.Response, Moya.Error> { switch (response, data, error) { case let (.Some(response), .Some(data), .None): let response = Moya.Response(statusCode: response.statusCode, data: data, response: response) return .Success(response) case let (_, _, .Some(error)): let error = Moya.Error.Underlying(error) return .Failure(error) default: let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil)) return .Failure(error) } } private struct CancellableWrapper: Cancellable { var innerCancellable: CancellableToken? = nil private var isCancelled = false func cancel() { innerCancellable?.cancel() } }
bff8041167371ee89e084ef8d4fbd29f
40.470588
204
0.672239
false
false
false
false
nurv/CSSwift
refs/heads/master
CSSwift/searching.swift
cc0-1.0
1
// // searching.swift // CSSwift // // Created by Artur Ventura on 19/08/14. // Copyright (c) 2014 Artur Ventura. All rights reserved. // import Foundation // Sequential Search // Best: O(1), Avg: O(n), Worst: O(n) func sequentialSearch<T: Equatable> (array:[T], object:T) -> Bool{ for i in array{ if i == object{ return true } } return false; } // Binary Search // Best: O(1), Avg: O(log n), Worst: O(log n) func binarySearch<T: Comparable> (array:[T], object:T) -> Bool{ var low = 0 var high = array.count - 1 while low <= high { println(array[low...high]) var ix = (low + high) / 2 if object == array[ix] { return true } else if object < array[ix] { high = ix - 1 } else { low = ix + 1 } } return false } // Hash-based Search // Best: O(1), Avg: O(1), Worst: O(n) func loadTable<T: Comparable>(size:Int, C:[T], hash: (T)->Int) -> Array<LinkedList<T>?>{ var array = Array<LinkedList<T>?>(count: size, repeatedValue: nil) for(var i = 0; i<C.count-1; i++){ var h = hash(C[i]) if array[h] == nil{ array[h] = LinkedList<T>() } array[h]!.add(array[h]!.length, object: C[i]); } return array } func hashSearch<T: Comparable>(C:[T], hash: (T)->Int, object:T) -> Bool{ var array = loadTable(C.count, C, hash) var h = hash(object) if let list = array[h]{ return list.find(object) }else{ return false } }
e39ec570de17990f890d62925efdd0ba
20.849315
88
0.516614
false
false
false
false
shirai/SwiftLearning
refs/heads/master
playground/配列.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit /* * *宣言 * */ //型を指定して配列を作成 let party: [String] = ["勇者", "戦士", "魔法使い", "僧侶"] print(party[2]) //インデックスで要素を参照する。 print("パーティの人数は、\(party.count)人です。") //要素数をcountプロパティで取得する。 //初期値で型を推測して配列を作成 var お弁当 = ["おにぎり", "玉子焼き", "ミニトマト", "アスパラ"] //初期値に同じ数字を入れて配列を作成。 let point = Array(repeating: 100, count: 4) //repeatedValueではなくrepeating print(point) //空の配列を作成する。(データ型の指定が必須) var box : [UInt] = [] var box2 = [UInt] () var box3 : Array<UInt> = [] //配列が空かどうかをisEmptyプロパティで調べる if box.isEmpty { print("配列は空です。") } //初期化の時に異なる型の要素を含める。Any又はAnyObject var a: Array<Any> = [100, 123.4, "文字列"] // 異なる型の要素 print(50 + (a[0] as! Int)) // 計算等する場合はキャスト(型変換)が必要(なぜかasの後に!が必要) //関数を配列要素にする。 let add = { (a: Double, b: Double) -> Double in return a + b } //二つDouble型の値を受け取ったら、足し算して返す let sub = { (a: Double, b: Double) -> Double in return a - b } let mul = { (a: Double, b: Double) -> Double in return a * b } let div = { (a: Double, b: Double) -> Double in return a / b } var ope: [(Double, Double) -> Double] //[(関数の引数) -> 関数の戻り値] ope = [add, sub, mul, div] ope[2](10, 20) /* * *要素の追加 * */ お弁当.append("タコさんウインナー") お弁当 += ["ブロッコリー","りんご"] print(お弁当) //宣言時の値と異なる型の値を混在はできない //お弁当.append(100) //エラーになる //定数の配列は、要素を変更したり追加することはできない。 //party.append("盗賊") // エラーになる //要素を指定位置に挿入する //お弁当.insert("キウイ", atIndex : 2) お弁当.insert("キウイ", at : 2) print(お弁当) /* * *要素の変更 * */ お弁当[0] = "おむすび" print(お弁当) //お弁当[10] = "ふりかけ"// インデックス範囲外を指定すると実行時エラーになる //お弁当[0] = 10 // 配列の宣言時と異なる値を代入するとコンパイル時エラーになる // インデックス1の値(インデックス2は含めない)を変更 お弁当[1..<2] = ["ゆで卵", "肉巻き"] print(お弁当) // インデックス0の値(インデックス2は含めない)を変更 お弁当[0...2] = ["サンドイッチ", "オムレツ"] print(お弁当) /* * *要素の削除 * */ //指定したインデックスの要素を削除 お弁当.remove(at: 2) print(お弁当) //配列の最後の要素を削除 お弁当.removeLast() print(お弁当) //初期化 お弁当 = [] print(お弁当) /* * *イティレーション * */ //for文を使って繰り返し処理 var book = ["こころ", "山椒魚", "檸檬", "細雪"] for chara in book{ print(chara) } //インデックスも使いたい場合 //for (index, chara) in enumerate(party) { for(index, chara) in book.enumerated(){ print("\(index + 1): \(chara)") } /* * *配列のコピー * */ var book2 = book book2[1] = "蟹工船" print(book) print(book2)
ba8e72b5e99088309bed7d707886ced1
17.125
91
0.627126
false
false
false
false
mtransitapps/mtransit-for-ios
refs/heads/master
MonTransit/Source/SQL/SQLHelper/ServiceDateDataProvider.swift
apache-2.0
1
// // ServiceDateDataProvider.swift // MonTransit // // Created by Thibault on 16-01-07. // Copyright © 2016 Thibault. All rights reserved. // import UIKit import SQLite class ServiceDateDataProvider { private let service_dates = Table("service_dates") private let service_id = Expression<String>("service_id") private let date = Expression<Int>("date") init() { } func createServiceDate(iAgency:Agency, iSqlCOnnection:Connection) -> Bool { do { let wServiceRawType = iAgency.getMainFilePath() let wFileText = iAgency.getZipData().getDataFileFromZip(iAgency.mGtfsServiceDate, iDocumentName: wServiceRawType) if wFileText != "" { let wServices = wFileText.stringByReplacingOccurrencesOfString("'", withString: "").componentsSeparatedByString("\n") let docsTrans = try! iSqlCOnnection.prepare("INSERT INTO service_dates (service_id, date) VALUES (?,?)") try iSqlCOnnection.transaction { for wService in wServices { let wServiceFormated = wService.componentsSeparatedByString(",") if wServiceFormated.count == 2{ try docsTrans.run(wServiceFormated[0], Int(wServiceFormated[1])!) } } } } return true } catch { print("insertion failed: \(error)") return false } } func retrieveCurrentService(iId:Int) -> [String] { // get the user's calendar let userCalendar = NSCalendar.currentCalendar() // choose which date and time components are needed let requestedComponents: NSCalendarUnit = [ NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day ] // get the components let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: NSDate()) let wYear = dateTimeComponents.year let wMonth = dateTimeComponents.month let wDay = dateTimeComponents.day //Verify if the current date is in DB let wDate = getDatesLimit(iId) let wTimeString = String(format: "%04d", wYear) + String(format: "%02d", wMonth) + String(format: "%02d", wDay) var wTimeInt = Int(wTimeString)! if wDate.max.getNSDate().getDateToInt() < wTimeInt{ wTimeInt = wDate.max.getNSDate().getDateToInt() } let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == wTimeInt)) var wCurrentService = [String]() for wService in wServices { wCurrentService.append(wService.get(service_id)) } return wCurrentService } func retrieveCurrentServiceByDate(iDate:Int, iId:Int) -> [String] { let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == iDate)) var wCurrentServices = [String]() for wService in wServices { wCurrentServices.append(wService.get(service_id)) } return wCurrentServices } func getDatesLimit(iId:Int) ->(min:GTFSTimeObject, max:GTFSTimeObject){ var min:GTFSTimeObject! var max:GTFSTimeObject! var wGtfsList:[GTFSTimeObject] = [] let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates) for wService in wServices{ wGtfsList.append(GTFSTimeObject(iGtfsDate: wService[date])) } min = wGtfsList.first max = wGtfsList.last return (min,max) } }
d46e83bdb9485babb019872db8a3f7dc
31.491803
133
0.575322
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Money/Tests/MoneyKitTests/Balance/CryptoFormatterTests.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import XCTest // swiftlint:disable type_body_length class CryptoFormatterTests: XCTestCase { private var englishLocale: Locale! private var btcFormatter: CryptoFormatter! private var ethFormatter: CryptoFormatter! private var bchFormatter: CryptoFormatter! private var xlmFormatter: CryptoFormatter! override func setUp() { super.setUp() englishLocale = Locale(identifier: "en_US") btcFormatter = CryptoFormatter( locale: englishLocale, cryptoCurrency: .bitcoin, minFractionDigits: 1, withPrecision: .short ) ethFormatter = CryptoFormatter( locale: englishLocale, cryptoCurrency: .ethereum, minFractionDigits: 1, withPrecision: .short ) bchFormatter = CryptoFormatter( locale: englishLocale, cryptoCurrency: .bitcoinCash, minFractionDigits: 1, withPrecision: .short ) xlmFormatter = CryptoFormatter( locale: englishLocale, cryptoCurrency: .stellar, minFractionDigits: 1, withPrecision: .short ) } override func tearDown() { englishLocale = nil btcFormatter = nil ethFormatter = nil bchFormatter = nil xlmFormatter = nil super.tearDown() } func testFormatWithoutSymbolBtc() { XCTAssertEqual( "0.00000001", btcFormatter.format(minor: 1) ) XCTAssertEqual( "0.1", btcFormatter.format(major: 0.1) ) XCTAssertEqual( "0.0", btcFormatter.format(major: 0) ) XCTAssertEqual( "1.0", btcFormatter.format(major: 1) ) XCTAssertEqual( "1,000.0", btcFormatter.format(major: 1000) ) XCTAssertEqual( "1,000,000.0", btcFormatter.format(major: 1000000) ) } func testFormatWithSymbolBtc() { XCTAssertEqual( "0.00000001 BTC", btcFormatter.format(minor: 1, includeSymbol: true) ) XCTAssertEqual( "0.1 BTC", btcFormatter.format(major: 0.1, includeSymbol: true) ) XCTAssertEqual( "0.0 BTC", btcFormatter.format(major: 0, includeSymbol: true) ) XCTAssertEqual( "1.0 BTC", btcFormatter.format(major: 1, includeSymbol: true) ) XCTAssertEqual( "1,000.0 BTC", btcFormatter.format(major: 1000, includeSymbol: true) ) XCTAssertEqual( "1,000,000.0 BTC", btcFormatter.format(major: 1000000, includeSymbol: true) ) } func testFormatEthShortPrecision() { XCTAssertEqual( "0.0 ETH", ethFormatter.format(minor: 1, includeSymbol: true) ) XCTAssertEqual( "0.0 ETH", ethFormatter.format(minor: 1000, includeSymbol: true) ) XCTAssertEqual( "0.0 ETH", ethFormatter.format(minor: 1000000, includeSymbol: true) ) XCTAssertEqual( "0.0 ETH", ethFormatter.format(minor: 1000000000, includeSymbol: true) ) } func testFormatEthLongPrecision() { let formatter = CryptoFormatter( locale: englishLocale, cryptoCurrency: .ethereum, minFractionDigits: 1, withPrecision: .long ) XCTAssertEqual( "0.000000000000000001 ETH", formatter.format(minor: 1, includeSymbol: true) ) XCTAssertEqual( "0.000000000000001 ETH", formatter.format(minor: 1000, includeSymbol: true) ) XCTAssertEqual( "0.000000000001 ETH", formatter.format(minor: 1000000, includeSymbol: true) ) XCTAssertEqual( "0.000000001 ETH", formatter.format(minor: 1000000000, includeSymbol: true) ) } func testFormatWithoutSymbolEth() { XCTAssertEqual( "0.00000001", ethFormatter.format(minor: 10000000000) ) XCTAssertEqual( "0.00001", ethFormatter.format(minor: 10000000000000) ) XCTAssertEqual( "0.1", ethFormatter.format(minor: 100000000000000000) ) XCTAssertEqual( "1.0", ethFormatter.format(minor: 1000000000000000000) ) XCTAssertEqual( "10.0", ethFormatter.format(major: 10) ) XCTAssertEqual( "100.0", ethFormatter.format(major: 100) ) XCTAssertEqual( "1,000.0", ethFormatter.format(major: 1000) ) XCTAssertEqual( "1.213333", ethFormatter.format(major: 1.213333) ) XCTAssertEqual( "1.12345678", ethFormatter.format(major: 1.123456789) ) } func testFormatWithSymbolEth() { XCTAssertEqual( "0.00000001 ETH", ethFormatter.format(minor: 10000000000, includeSymbol: true) ) XCTAssertEqual( "0.00001 ETH", ethFormatter.format(minor: 10000000000000, includeSymbol: true) ) XCTAssertEqual( "0.1 ETH", ethFormatter.format(minor: 100000000000000000, includeSymbol: true) ) XCTAssertEqual( "1.213333 ETH", ethFormatter.format(major: 1.213333, includeSymbol: true) ) XCTAssertEqual( "1.12345678 ETH", ethFormatter.format(major: 1.123456789, includeSymbol: true) ) XCTAssertEqual( "1.12345678 ETH", ethFormatter.format(minor: 1123456789333222111, includeSymbol: true) ) } func testFormatWithoutSymbolBch() { XCTAssertEqual( "0.00000001", bchFormatter.format(minor: 1) ) XCTAssertEqual( "0.1", bchFormatter.format(major: 0.1) ) XCTAssertEqual( "0.0", bchFormatter.format(major: 0) ) XCTAssertEqual( "1.0", bchFormatter.format(major: 1) ) XCTAssertEqual( "1,000.0", bchFormatter.format(major: 1000) ) XCTAssertEqual( "1,000,000.0", bchFormatter.format(major: 1000000) ) } func testFormatWithSymbolBch() { XCTAssertEqual( "0.00000001 BCH", bchFormatter.format(minor: 1, includeSymbol: true) ) XCTAssertEqual( "0.1 BCH", bchFormatter.format(major: 0.1, includeSymbol: true) ) XCTAssertEqual( "0.0 BCH", bchFormatter.format(major: 0, includeSymbol: true) ) XCTAssertEqual( "1.0 BCH", bchFormatter.format(major: 1, includeSymbol: true) ) XCTAssertEqual( "1,000.0 BCH", bchFormatter.format(major: 1000, includeSymbol: true) ) XCTAssertEqual( "1,000,000.0 BCH", bchFormatter.format(major: 1000000, includeSymbol: true) ) } func testFormatWithoutSymbolXlm() { XCTAssertEqual( "0.0000001", xlmFormatter.format(minor: 1) ) XCTAssertEqual( "0.1", xlmFormatter.format(major: 0.1) ) XCTAssertEqual( "0.0", xlmFormatter.format(major: 0) ) XCTAssertEqual( "1.0", xlmFormatter.format(major: 1) ) XCTAssertEqual( "1,000.0", xlmFormatter.format(major: 1000) ) XCTAssertEqual( "1,000,000.0", xlmFormatter.format(major: 1000000) ) } func testFormatWithSymbolXlm() { XCTAssertEqual( "0.0000001 XLM", xlmFormatter.format(minor: 1, includeSymbol: true) ) XCTAssertEqual( "0.1 XLM", xlmFormatter.format(major: 0.1, includeSymbol: true) ) XCTAssertEqual( "0.0 XLM", xlmFormatter.format(major: 0, includeSymbol: true) ) XCTAssertEqual( "1.0 XLM", xlmFormatter.format(major: 1, includeSymbol: true) ) XCTAssertEqual( "1,000.0 XLM", xlmFormatter.format(major: 1000, includeSymbol: true) ) XCTAssertEqual( "1,000,000.0 XLM", xlmFormatter.format(major: 1000000, includeSymbol: true) ) } func testItalyLocaleFormattingBtc() { let italyLocale = Locale(identifier: "it_IT") let formatter = CryptoFormatter( locale: italyLocale, cryptoCurrency: .bitcoin, minFractionDigits: 1, withPrecision: .long ) XCTAssertEqual( "0,00000001", formatter.format(minor: 1) ) XCTAssertEqual( "0,1", formatter.format(major: 0.1) ) XCTAssertEqual( "0,0", formatter.format(major: 0) ) XCTAssertEqual( "1,0", formatter.format(major: 1) ) XCTAssertEqual( "1.000,0", formatter.format(major: 1000) ) XCTAssertEqual( "1.000.000,0", formatter.format(major: 1000000) ) } }
2ee2111ffffdd4ed501d77d29efbf2d8
26.520891
80
0.520951
false
false
false
false
couchbits/iOSToolbox
refs/heads/master
Sources/Extensions/UIKit/UILongPressGestureRecognizerExtensions.swift
mit
1
// // UILongTapGestureRecognizerExtension.swift // Alamofire // // Created by Dominik Gauggel on 10.04.18. // import Foundation import UIKit private var LongPressBlockHandlerKey: UInt8 = 0 extension UILongPressGestureRecognizer { public convenience init(longPress: ((UILongPressGestureRecognizer) -> Void)? = nil) { self.init() initializeHandler(longPress) } public var longPress: ((UILongPressGestureRecognizer) -> Void)? { get { return blockHandler?.blockHandler } set { initializeHandler(newValue) } } internal var blockHandler: GenericBlockHandler<UILongPressGestureRecognizer>? { get { return getAssociated(associativeKey: &LongPressBlockHandlerKey) } set { setAssociated(value: newValue, associativeKey: &LongPressBlockHandlerKey) } } internal func initializeHandler(_ handler: ((UILongPressGestureRecognizer) -> Void)?) { if let handler = blockHandler { removeTarget(handler, action: GenericBlockHandlerAction) } if let handler = handler { blockHandler = GenericBlockHandler(object: self, blockHandler: handler) if let blockHandler = blockHandler { addTarget(blockHandler, action: GenericBlockHandlerAction) } } } }
cf9731a1049bfea812b5627dd3ab4242
28.977778
91
0.661972
false
false
false
false
ustwo/formvalidator-swift
refs/heads/master
Tests/Unit Tests/Conditions/PresentConditionTests.swift
mit
1
// // PresentConditionTests.swift // FormValidatorSwift // // Created by Aaron McTavish on 13/01/2016. // Copyright © 2016 ustwo. All rights reserved. // import XCTest @testable import FormValidatorSwift final class PresentConditionTests: XCTestCase { // MARK: - Properties let condition = PresentCondition() // MARK: - Test Success func testPresentCondition_Success() { // Given let testInput = "Foo" let expectedResult = true // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } // MARK: - Test Failure func testPresentCondition_Empty_Failure() { // Given let testInput = "" let expectedResult = false // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } func testPresentCondition_Nil_Failure() { // Given let testInput: String? = nil let expectedResult = false // Test AssertCondition(condition, testInput: testInput, expectedResult: expectedResult) } }
3a6e8bb4f1d9c65b33446a8bc75fadb5
21.314815
88
0.59668
false
true
false
false
orcudy/archive
refs/heads/master
ios/razzle/circle-indicator/COIndicatorCircle/COIndicatorCircle.swift
gpl-3.0
1
// // Circle.swift // COIndicatorCircle // // Created by Chris Orcutt on 8/24/15. // Copyright (c) 2015 Chris Orcutt. All rights reserved. // import UIKit import QuartzCore class COIndicatorCircle: UIView { @IBOutlet var view: UIView! var radius: Float! let thickness: Float = 5 let foregroundCircleColor: UIColor = UIColor.blackColor() let backgroundCircleColor: UIColor = UIColor.whiteColor() private var backgroundCircleLayer: CAShapeLayer! private var foregroundCircleLayer: CAShapeLayer! private var backgroundPath: UIBezierPath! private var foregroundPath: UIBezierPath! //MARK: Initialization func baseInit() { NSBundle.mainBundle().loadNibNamed("COIndicatorCircle", owner: self, options: nil) if frame.width > frame.height { radius = Float(frame.height) / 2.0 } else { radius = Float(frame.width) / 2.0 } let x = center.x / 2 let y = center.y / 2 let width = radius * 2 let height = radius * 2 let arcCenter = CGPoint(x: CGFloat(radius), y: CGFloat(radius)) self.backgroundPath = UIBezierPath(arcCenter: arcCenter, radius: CGFloat(radius - (thickness / 2)), startAngle: 0, endAngle: 2 * pi, clockwise: true) self.foregroundPath = UIBezierPath(arcCenter: arcCenter, radius: CGFloat(radius - (thickness / 2)), startAngle: 0, endAngle: 0.83 * 2 * pi, clockwise: true) self.backgroundCircleLayer = createCircleLayer(view.bounds, path: backgroundPath.CGPath, lineWidth: CGFloat(thickness), strokeColor: backgroundCircleColor.CGColor, fillColor: UIColor.clearColor().CGColor, backgroundColor: UIColor.clearColor().CGColor) self.view.layer.addSublayer(backgroundCircleLayer) self.foregroundCircleLayer = createCircleLayer(view.bounds, path: foregroundPath.CGPath, lineWidth: CGFloat(thickness), strokeColor: foregroundCircleColor.CGColor, fillColor: UIColor.clearColor().CGColor, backgroundColor: UIColor.clearColor().CGColor) self.view.layer.addSublayer(foregroundCircleLayer) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = 2.0 animation.repeatCount = 1.0 animation.fromValue = 0.0 animation.toValue = 1.0 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) foregroundCircleLayer.addAnimation(animation, forKey: "foreGroundCircleAnimation") backgroundColor = UIColor.clearColor() self.view.frame = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) self.view.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) self.addSubview(self.view) } func createCircleLayer(frame: CGRect, path: CGPath, lineWidth: CGFloat, strokeColor: CGColor, fillColor: CGColor, backgroundColor: CGColor) -> CAShapeLayer { let circleLayer = CAShapeLayer() circleLayer.frame = frame circleLayer.path = path circleLayer.lineWidth = lineWidth circleLayer.strokeColor = strokeColor circleLayer.fillColor = fillColor circleLayer.backgroundColor = backgroundColor return circleLayer } override init(frame: CGRect) { super.init(frame: frame) baseInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) baseInit() } }
17ad4f5e2a4e38ac8d1ac91ab9114e91
40.152941
259
0.677816
false
false
false
false
rmannion/RMCore
refs/heads/master
RMCore/Table Manager/Models/RMTableSection.swift
mit
1
// // RMTableSection.swift // RMCore // // Created by Ryan Mannion on 4/29/16. // Copyright © 2016 Ryan Mannion. All rights reserved. // import Foundation import ReactiveKit public class RMTableSection { public var rows: [RMTableRow] = [] public var headerClass: RMTableSectionView.Type? public weak var headerDelegate: RMTableSectionViewDelegate? public var headerText: String? public var headerHeight: CGFloat = 0 public var footerClass: RMTableSectionView.Type? public var footerHeight: CGFloat = 0 public var userInfo: Any? public var closed: Property<Bool> = Property(false) public var section: Int = 0 public var indexTitle: String? public init(rows: [RMTableRow] = []) { self.rows = rows } public var selectedRows: [RMTableRow] { return rows.filter { $0.isSelected.value } } }
97a764cfcacd57143a250c39b2411ec9
26.25
63
0.68578
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
YourGoals/Utility/Date+DateRange.swift
lgpl-3.0
1
// // Date+DateRange.swift // YourGoals // // Created by André Claaßen on 17.12.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation // this extension is based on ideas of // http://adampreble.net/blog/2014/09/iterating-over-range-of-dates-swift/ extension Calendar { /// create a range from start date to end date. default is stepping a day with interval 1 /// /// - Parameters: /// - startDate: start date /// - endDate: end date /// - stepUnits: step in days /// - stepValue: 1 /// - Returns: a range func dateRange(startDate: Date, endDate: Date, stepComponent: Calendar.Component = .day, stepValue: Int = 1) -> DateRange { let dateRange = DateRange(calendar: self, startDate: startDate, endDate: endDate, stepComponent: stepComponent, stepValue: stepValue, multiplier: 0) return dateRange } /// create a range of dates with a start date and a number of steps (eg. days) /// /// - Parameters: /// - startDate: start date of the range /// - steps: number of steps /// - stepComponent: component eg. day /// - stepValue: increment /// - Returns: a daterange of nil func dateRange(startDate: Date, steps:Int, stepComponent: Calendar.Component = .day, stepValue: Int = 1) -> DateRange? { guard let endDate = self.date(byAdding: stepComponent, value: stepValue * steps, to: startDate) else { return nil } let dateRange = DateRange(calendar: self, startDate: startDate, endDate: endDate, stepComponent: stepComponent, stepValue: stepValue, multiplier: 0) return dateRange } } /// the date range is sequence for iterating easier over a range of dates struct DateRange:Sequence { var calendar: Calendar var startDate: Date var endDate: Date var stepComponent: Calendar.Component var stepValue: Int fileprivate var multiplier: Int // MARK: - Sequence Protocol func makeIterator() -> DateRange.Iterator { return Iterator(range: self) } // Mark: - Iterator struct Iterator: IteratorProtocol { var range: DateRange mutating func next() -> Date? { guard let nextDate = range.calendar.date(byAdding: Calendar.Component.day, value: range.stepValue * range.multiplier, to: range.startDate) else { return nil } if nextDate > range.endDate { return nil } else { range.multiplier += 1 return nextDate } } } }
f61324d3af349d98b99251ba5f8281d5
31.388235
157
0.593534
false
false
false
false
jiankaiwang/codein
refs/heads/master
examples/oop.swift
mit
1
/* * desc : structure and class definition * docv : 0.1.0 * plat : CodeIn * swif : 5.1.3 */ struct Car { var weight = 0 var horsepower = 0 var name = "" } class CarPhysicalProperty { var carInfo = Car() var acceleration : Double = 0.0 // private void function private func calAccelerate() { self.acceleration = Double(self.carInfo.horsepower) / Double(self.carInfo.weight) } // constructor init(carWeight : Int, carHorsepower : Int, carName : String) { self.carInfo = Car( weight : carWeight, horsepower : carHorsepower, name : carName ) self.calAccelerate() } // public Double function public func getCarAcc() -> Double { return(self.acceleration) } // public String function public func getCarName() -> String { return(self.carInfo.name) } } var firstCar = CarPhysicalProperty( carWeight : 100, carHorsepower : 200, carName : "FCar" ) print("The accelerate of \(firstCar.getCarName()) is \(firstCar.getCarAcc()).")
86b91eb217d037fc10b657640afdbd2a
21.979592
80
0.586146
false
false
false
false
CJGitH/QQMusic
refs/heads/master
QQMusic/Classes/Other/Tool/视频播放/视频播放/ViewController.swift
mit
1
// // ViewController.swift // 视频播放 // // Created by chen on 16/5/18. // Copyright © 2016年 chen. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var player: AVPlayer? var layer: AVPlayerLayer? override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let url = NSURL(string: "http://v1.mukewang.com/19954d8f-e2c2-4c0a-b8c1-a4c826b5ca8b/L.mp4") player = AVPlayer(URL: url!) player?.play() //添加到layer上播放 layer = AVPlayerLayer(player: player) layer?.frame = view.bounds view.layer.addSublayer(layer!) } //当点击停止时,就暂停视频播放 override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { player?.pause() } //设置尺寸,在这里设置才zhunque override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layer?.frame = view.bounds } }
a8c88e36818ee57caa5d2f3e82572d92
20.446809
100
0.607143
false
false
false
false
xuech/OMS-WH
refs/heads/master
OMS-WH/AppDelegate.swift
mit
1
// // AppDelegate.swift // OMS-WH // // Created by ___Gwy on 2017/8/15. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD import CoreData import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var time:Timer? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. keyBoardManager() UIApplication.shared.statusBarStyle = .lightContent RemoteManager.finishLaunching(at: application,with: launchOptions) window = UIWindow(frame: SCREEN_BOUNDS) window!.makeKeyAndVisible() window?.rootViewController = LoginViewController() defaultController() return true } func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { RemoteManager.shareInstance.application(application,didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. time = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(AppDelegate.showTap), userInfo: nil, repeats: false) } func applicationWillEnterForeground(_ application: UIApplication) { time!.invalidate() RemoteManager.shareInstance.dearWithPushBadge() } func applicationDidBecomeActive(_ application: UIApplication) { RemoteManager.shareInstance.dearWithPushBadge() Method.getMethod().systemUpdate { (result, error) in } } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "WMS") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } @objc fileprivate func showTap(){ if UserDefaults.Global.readString(forKey: .token) != nil{ if UserDefaults.Global.boolValue(forKey: .tapAllow) == true{ let tapView = TapAllowView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)) self.window?.addSubview(tapView) } } } func defaultController(){ if !(UserDefaults.standard.bool(forKey: "everLaunched")){ UserDefaults.standard.set(true, forKey: "everLaunched") self.window?.rootViewController = GuideViewController() }else{ if let _ = UserDefaults.Global.readString(forKey: .token){ self.window?.rootViewController = OMSTabBarController() if UserDefaults.Global.boolValue(forKey: .tapAllow) == true{ let tapView = TapAllowView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)) self.window?.addSubview(tapView) } }else{ self.window?.rootViewController = LoginViewController() } } } } extension AppDelegate { //MARK:-键盘 fileprivate func keyBoardManager() { let keyBoardManager = IQKeyboardManager.sharedManager() keyBoardManager.enable = true keyBoardManager.toolbarTintColor = kAppearanceColor // keyBoardManager.shouldResignOnTouchOutside = true // keyBoardManager.shouldToolbarUsesTextFieldTintColor = false // keyBoardManager.enableAutoToolbar = true } }
4ab7584eceaeb7f5d717b5277d31d8cf
43.526316
285
0.666076
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/Swift Note/LiveBroadcast/Server/LiveBroadcastServer/Server/ServerManager.swift
mit
1
// // ServerManager.swift // LiveBroadcastServer // // Created by 朱双泉 on 2018/12/13. // Copyright © 2018 Castie!. All rights reserved. // import Cocoa class ServerManager { fileprivate lazy var serverSocket = TCPServer(addr: "0.0.0.0", port: 6666) fileprivate var isServerRunning = false fileprivate lazy var clientManagers = [ClientManager]() } extension ServerManager { func startRunning() { serverSocket.listen() isServerRunning = true DispatchQueue.global().async { while self.isServerRunning { if let client = self.serverSocket.accept() { DispatchQueue.global().async { self.handlerClient(client) } } } } } func stopRunning() { isServerRunning = false } } extension ServerManager { fileprivate func handlerClient(_ client: TCPClient) { let manager = ClientManager(tcpClient: client) clientManagers.append(manager) manager.delegate = self manager.startReadMessage() } } extension ServerManager: ClientManagerDelegate { func removeClient(_ client: ClientManager) { guard let index = clientManagers.index(of: client) else { return } clientManagers.remove(at: index) } func sendMsgToClient(_ data: Data) { for manager in clientManagers { manager.tcpClient.send(data: data) } } }
7755234c359876f5237bcafbc41ce9cd
23.322581
78
0.599469
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
refs/heads/master
Example/Pods/KDEAudioPlayer/AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+PlayerEvent.swift
apache-2.0
2
// // AudioPlayer+PlayerEvent.swift // AudioPlayer // // Created by Kevin DELANNOY on 03/04/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // extension AudioPlayer { /// Handles player events. /// /// - Parameters: /// - producer: The event producer that generated the player event. /// - event: The player event. func handlePlayerEvent(from producer: EventProducer, with event: PlayerEventProducer.PlayerEvent) { switch event { case .endedPlaying(let error): if let error = error { state = .failed(.foundationError(error)) } else { nextOrStop() } case .interruptionBegan where state.isPlaying || state.isBuffering: //We pause the player when an interruption is detected backgroundHandler.beginBackgroundTask() pausedForInterruption = true pause() case .interruptionEnded where pausedForInterruption: if resumeAfterInterruption { resume() } pausedForInterruption = false backgroundHandler.endBackgroundTask() case .loadedDuration(let time): if let currentItem = currentItem, let time = time.ap_timeIntervalValue { updateNowPlayingInfoCenter() delegate?.audioPlayer(self, didFindDuration: time, for: currentItem) } case .loadedMetadata(let metadata): if let currentItem = currentItem, !metadata.isEmpty { currentItem.parseMetadata(metadata) delegate?.audioPlayer(self, didUpdateEmptyMetadataOn: currentItem, withData: metadata) } case .loadedMoreRange: if let currentItem = currentItem, let currentItemLoadedRange = currentItemLoadedRange { delegate?.audioPlayer(self, didLoad: currentItemLoadedRange, for: currentItem) } case .progressed(let time): if let currentItemProgression = time.ap_timeIntervalValue, let item = player?.currentItem, item.status == .readyToPlay { //This fixes the behavior where sometimes the `playbackLikelyToKeepUp` isn't //changed even though it's playing (happens mostly at the first play though). if state.isBuffering || state.isPaused { if shouldResumePlaying { stateBeforeBuffering = nil state = .playing player?.rate = rate } else { player?.rate = 0 state = .paused } backgroundHandler.endBackgroundTask() } //Then we can call the didUpdateProgressionTo: delegate method let itemDuration = currentItemDuration ?? 0 let percentage = (itemDuration > 0 ? Float(currentItemProgression / itemDuration) * 100 : 0) delegate?.audioPlayer(self, didUpdateProgressionTo: currentItemProgression, percentageRead: percentage) } case .readyToPlay: //There is enough data in the buffer if shouldResumePlaying { stateBeforeBuffering = nil state = .playing player?.rate = rate } else { player?.rate = 0 state = .paused } //TODO: where to start? retryEventProducer.stopProducingEvents() backgroundHandler.endBackgroundTask() case .routeChanged: //In some route changes, the player pause automatically //TODO: there should be a check if state == playing if let player = player, player.rate == 0 { state = .paused } case .sessionMessedUp: #if os(iOS) || os(tvOS) //We reenable the audio session directly in case we're in background setAudioSession(active: true) //Aaaaand we: restart playing/go to next state = .stopped qualityAdjustmentEventProducer.interruptionCount += 1 retryOrPlayNext() #endif case .startedBuffering: //The buffer is empty and player is loading if case .playing = state, !qualityIsBeingChanged { qualityAdjustmentEventProducer.interruptionCount += 1 } stateBeforeBuffering = state if reachability.isReachable() || (currentItem?.soundURLs[currentQuality]?.ap_isOfflineURL ?? false) { state = .buffering } else { state = .waitingForConnection } backgroundHandler.beginBackgroundTask() default: break } } }
fb8e5f7cac7e8f5e010d9675984ac5b9
37.421875
119
0.565677
false
false
false
false
MadeByHecho/DeLorean
refs/heads/master
Carthage/Checkouts/Miles/Miles/Miles.swift
mit
2
// // Miles.swift // Miles // // Created by Scott Petit on 2/16/15. // Copyright (c) 2015 Hecho. All rights reserved. // import XCTest import Foundation public extension Equatable { public func shouldEqual<T: Equatable>(other: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to equal \(other)" if let other = other as? Self { XCTAssertEqual(self, other, message, file: file, line: line) } else { XCTAssertTrue(false, message, file: file, line: line) } } } public extension Comparable { public func shouldBeGreaterThan<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be greater than \(other)" if let other = other as? Self { XCTAssertGreaterThan(self, other, message) } else { XCTAssertTrue(false, message) } } public func shouldBeGreaterThanOrEqualTo<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be greater than or equal to \(other)" if let other = other as? Self { XCTAssertGreaterThanOrEqual(self, other, message) } else { XCTAssertTrue(false, message) } } public func shouldBeLessThan<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be less than \(other)" if let other = other as? Self { XCTAssertLessThan(self, other, message) } else { XCTAssertTrue(false, message) } } public func shouldBeLessThanOrEqualTo<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be less than or Equal to \(other)" if let other = other as? Self { XCTAssertLessThanOrEqual(self, other, message) } else { XCTAssertTrue(false, message) } } } public extension FloatingPointType { public func shouldBeCloseTo<T: FloatingPointType>(other: T, withAccuracy accuracy: T, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be within \(accuracy) of \(other)" if let other = other as? Self, accuracy = accuracy as? Self { XCTAssertEqualWithAccuracy(self, other, accuracy: accuracy, message, file: file, line: line) } else { XCTAssertTrue(false, message) } } } public extension String { public func shouldContain(string: String, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to contain \(string)" XCTAssertTrue(self.rangeOfString(string) != nil, message, file: file, line: line) } public func shouldHavePrefix(string: String, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to have a prefix of \(string)" XCTAssertTrue(self.hasPrefix(string), message, file: file, line: line) } public func shouldHaveSuffix(string: String, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to have a suffix of \(string)" XCTAssertTrue(self.hasSuffix(string), message, file: file, line: line) } } public extension Bool { func shouldBeTrue(file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be true" XCTAssertTrue(self, message, file: file, line: line) } func shouldBeFalse(file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be false" XCTAssertFalse(self, message, file: file, line: line) } } public extension NSObject { func shouldEqual(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to equal \(object)" XCTAssertEqual(self, object, message, file: file, line: line) } func shouldNotEqual(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to not equal \(object)" XCTAssertNotEqual(self, object, message, file: file, line: line) } func shouldBeIdenticalTo(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be identical to \(object))" XCTAssertTrue(self === object, message, file: file, line: line) } func shouldBeKindOfClass(aClass: AnyClass, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be kind of Class \(aClass)" XCTAssertTrue(self.isKindOfClass(aClass), message, file: file, line: line) } } public extension CollectionType where Generator.Element : Equatable { func shouldContain(item: Self.Generator.Element, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to contain \(item)" var contains = false if let _ = indexOf(item) { contains = true } XCTAssertTrue(contains, message, file: file, line: line) } } public extension CollectionType { func shouldBeEmpty(file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be empty" XCTAssertTrue(isEmpty, message, file: file, line: line) } } public extension Dictionary where Value : Equatable { func shouldContain(item: Value, file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to contain \(item)" var contains = false for value in values { if value == item { contains = true break } } XCTAssertTrue(contains, message, file: file, line: line) } } public extension Optional { public func shouldBeNil(file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to be nil" switch self { case .Some(_): XCTAssertTrue(false, message, file: file, line: line) case .None: XCTAssertTrue(true, message, file: file, line: line) } } public func shouldNotBeNil(file: String = __FILE__, line: UInt = __LINE__) { let message = "Expected \(self) to not be nil" switch self { case .Some(_): XCTAssertTrue(true, message, file: file, line: line) case .None: XCTAssertTrue(false, message, file: file, line: line) } } }
75294ce42787bd10d8c45397370993fe
36.361582
139
0.592016
false
false
false
false
Chen-Dixi/SwiftHashDict
refs/heads/master
sy4/sy4/hashdict.swift
mit
1
// // hashdict.swift // sy4 // // Created by Dixi-Chen on 16/6/16. // Copyright © 2016年 Dixi-Chen. All rights reserved. // import Foundation class hashdict<Key:Equatable,E>{ var HT : [KVpair<Key,E>!] let EMPTYKEY:Key let M:Int var count:Int var perm = [Int]() init(sz:Int, k:Key) { self.count = 0 self.M = sz self.EMPTYKEY = k self.HT = [KVpair<Key,E>!](count: sz, repeatedValue: KVpair<Key,E>(EMPTYKEY,nil)) //这里的感叹号不是很明白 for var i=0 ; i<M; { let temp = Int.random(M) if nil == perm.indexOf(temp){ i = i + 1 perm.append(temp) } } } func size()->Int{ return count } private func h(x:Int) -> Int{ return x % M } private func h(x:String) -> Int{ var sum:Int = 0 for c in x.unicodeScalars { sum += Int(c.value) } return sum % M } private func p(key:Key, i:Int) -> Int{ return perm[i-1] } func find(k:Key) -> E? { return hashSearch(k) } func insert(k:Key,e:E){ hashInsert(k, e: e) count += 1 } } extension hashdict{ private func hashInsert(key:Key,e:E) { var home:Int var pos:Int if key is Int { home = self.h(key as! Int) pos = home }else { home = self.h(key as! String) pos = home } var i = 1 while EMPTYKEY != (HT[pos]).key() { pos = (home + p(key,i: i)) % M assert( key != (HT[pos].key()), "Duplicates not allowed") i += 1 } let temp = KVpair<Key,E>(key,e) HT[pos] = temp } private func hashSearch(key:Key) -> E?{ var home:Int var pos:Int if key is Int { home = self.h(key as! Int) pos = home }else { home = self.h(key as! String) pos = home } var i = 1 while EMPTYKEY != (HT[pos]).key() && key != (HT[pos]).key() { pos = (home + p(key,i: i)) % M i += 1 } if key == (HT[pos]).key() { return (HT[pos]).value() } else{ return nil } } } private extension Int{ static func random(max:Int) -> Int{ return Int(arc4random_uniform(UInt32(max))) } }
8cb16ddd9c66cb88060bb2ec817cd38b
19.540323
104
0.433621
false
false
false
false
malcommac/SwiftMsgPack
refs/heads/master
Sources/SwiftMsgPack/Decoder.swift
mit
1
/* * SwiftMsgPack * Lightweight MsgPack for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 // MARK: Helper Struct to read and decoded stream of `Data` private struct StreamReader { /// Pointer to `data` instance private var data: Data /// Current position on `data` instance private var index: Int /// Initialize a new stream with an input data /// /// - Parameter data: data to read public init(_ data: Data) { self.data = data self.index = 0 } /// Read the next data type header of the structure (8 bit) and move the index by 1 position /// /// - Returns: data type value /// - Throws: throw an exception if data cannot be read or it's not available mutating func readType() throws -> UInt8 { guard index < data.count else { throw MsgPackError.unexpectedData } let type: UInt8 = data[Data.Index(index)] index += 1 return type } /// Read 8 bit value and return it and move the index by 1 position /// /// - Returns: 8 bit value /// - Throws: throw an exception if data cannot be read or it's not available mutating func read8Bit() throws -> UInt8 { return try readType() } /// Read next 16 bytes and return the value (index is moved according to the task) /// /// - Returns: value read /// - Throws: throw an exception if data cannot be read or it's not available mutating func read16Bit() throws -> UInt16 { guard index + 2 <= data.count else { throw MsgPackError.unexpectedData } let value_int16 = UInt16(data[Data.Index(index)]) << 8 + UInt16(data[Data.Index(index + 1)]) index += 2 return value_int16 } /// Read next 32 bytes and return the value (index is moved according to the task) /// /// - Returns: value read /// - Throws: throw an exception if data cannot be read or it's not available mutating func read32Bit() throws -> UInt32 { guard index + 4 <= data.count else { throw MsgPackError.unexpectedData } var value_int32: UInt32 = 0 for idx in index...(index + 3) { value_int32 = (value_int32 << 8) + UInt32(data[Data.Index(idx)]) } index += 4 return value_int32 } /// Read next 64 bytes and return the value (index is moved according to the task) /// /// - Returns: value read /// - Throws: throw an exception if data cannot be read or it's not available mutating func read64Bit() throws -> UInt64 { guard index + 8 <= data.count else { throw MsgPackError.unexpectedData } var value_int64: UInt64 = 0 for idx in index...(index + 7) { value_int64 = (value_int64 << 8) + UInt64(data[Data.Index(idx)]) } index += 8 return value_int64 } /// Read next `length` bytes of data and return it (index is moved according to it) /// /// - Parameter length: length of data to read /// - Returns: read value /// - Throws: throw an exception if data cannot be read or it's not available mutating func readData(length: Int) throws -> Data { guard index + length <= data.count else { throw MsgPackError.unexpectedData } let range = index ..< (index + length) index += length return data.subdata(in: range) } } // MARK: Unpack of MsgPack Data public extension Data { // MARK - Unpack /// This is the public function which can read a sequence of Data /// and unpack all objects by returning decoded data. /// /// - Returns: decoded data /// - Throws: an error if decoding task cannot be finished correctly due to an error func unpack() throws -> Any? { // Create a reader which has a point to the current position in data instance // and several help functions to read data var reader = StreamReader(self) // try to unpack data return try self.unpack(stream: &reader) } // MARK - Unpack Internal Functions /// This is the unpack function which reader /// /// - Parameter stream: stream object /// - Returns: decoded data /// - Throws: an error if decoding task cannot be finished correctly due to an error private func unpack(stream: inout StreamReader) throws -> Any? { let type = try stream.readType() // Spec is defined here: // https://github.com/msgpack/msgpack/blob/master/spec.md#formats-bool switch type { // POSITIVE FIX INT // positive fixint 0xxxxxxx 0x00 - 0x7f case 0x00...0x7f: return Int8(type) // FIX DICTIONARY (< 16 ITEMS) // fixmap 1000xxxx 0x80 - 0x8f case 0x80...0x8f: let count_items = Int(type & 0xf) return try self.unpack(dictionary: &stream, count: count_items) // FIX ARRAY (< 16 ITEMS) // fixarray 1001xxxx 0x90 - 0x9f case 0x90...0x9f: let count_items = Int(type & 0xf) return try self.unpack(array: &stream, count: count_items) // NEGATIVE FIX NUM // negative fixint 111xxxxx 0xe0 - 0xff case 0xe0...0xff: return Int8( Int(type) - 256) // FIX STRING (< 16 CHARS) // fixstr 101xxxxx 0xa0 - 0xbf case 0xa0...0xbf: let str_length = Int(type - 0xa0) return try self.unpack(string: &stream, length: str_length) // NIL VALUE // nil 11000000 0xc0 case 0xc0: return nil // BOOLEAN FALSE // false 11000010 0xc2 case 0xc2: return false // BOOLEAN TRUE // true 11000011 0xc3 case 0xc3: return true // BINARY DATA 8 BIT // bin 8 11000100 0xc4 case 0xc4: let len_data = Int(try stream.read8Bit()) return try stream.readData(length: len_data) // BINARY DATA 16 BIT // bin 16 11000101 0xc5 case 0xc5: let len_data = Int(try stream.read16Bit()) return try stream.readData(length: len_data) // BINARY DATA 32 BIT // bin 32 11000110 0xc6 case 0xc6: let len_data = Int(try stream.read32Bit()) return try stream.readData(length: len_data) // FLOAT 32 BIT // float 32 11001010 0xca case 0xca: return Float(bitPattern: try stream.read32Bit()) // DOUBLE // float 64 11001011 0xcb case 0xcb: return Double(bitPattern: try stream.read64Bit()) // UNSIGNED INT 8 BIT // uint 8 11001100 0xcc case 0xcc: return try stream.readType() // UNSIGNED INT 16 BIT // uint 16 11001101 0xcd case 0xcd: let h = UInt16(try stream.read8Bit()) let l = UInt16(try stream.read8Bit()) return (h << 8 + l) // UNSIGNED INT 32 BIT // uint 32 11001110 0xce case 0xce: return try stream.read32Bit() // UNSIGNED INT 64 BIT // uint 64 11001111 0xcf case 0xcf: return try stream.read64Bit() // INT 8 BIT // int 8 11010000 0xd0 case 0xd0: let value = try stream.read8Bit() return Int8(Int(value) - 256) // INT 16 BIT // int 16 11010001 0xd1 case 0xd1: let h = UInt16(try stream.read8Bit()) let l = UInt16(try stream.read8Bit()) return Int16(bitPattern: h << 8 + l) // INT 32 BIT // int 32 11010010 0xd2 case 0xd2: return try Int32(bitPattern: stream.read32Bit()) // INT 64 BIT // int 64 11010011 0xd3 case 0xd3: return try Int64(bitPattern: stream.read64Bit()) // STRING 8 BIT LENGTH // str 8 11011001 0xd9 case 0xd9: let len_data = Int(try stream.read8Bit()) return try unpack(string: &stream, length: len_data) // STRING 16 BIT LENGTH // str 16 11011010 0xda case 0xda: let len_data = Int(try stream.read8Bit()) << 8 + Int(try stream.read8Bit()) return try unpack(string: &stream, length: len_data) // STRING 32 BIT LENGTH // str 32 11011011 0xdb case 0xdb: var len_data = Int(try stream.read8Bit()) << 24 len_data += Int(try stream.read8Bit()) << 16 len_data += Int(try stream.read8Bit()) << 8 len_data += Int(try stream.read8Bit()) return try unpack(string: &stream, length: len_data) // ARRAY 16 ITEMS LENGTH // array 16 11011100 0xdc case 0xdc: let count_items = Int(try stream.read16Bit()) return try unpack(array: &stream, count: count_items) // ARRAY 32 ITEMS LENGTH // array 32 11011101 0xdd case 0xdd: let count_items = Int(try stream.read32Bit()) return try unpack(array: &stream, count: count_items) // DICTIONARY 16 ITEMS LENGTH // map 16 11011110 0xde case 0xde: let count_items = Int(try stream.read16Bit()) return try unpack(dictionary: &stream, count: count_items) // DICTIONARY 32 ITEMS LENGTH // map 32 11011111 0xdf case 0xdf: let count_items = Int(try stream.read32Bit()) return try unpack(dictionary: &stream, count: count_items) default: throw MsgPackError.unsupportedValue(String(format: "Type(%02x)", type)) } } /// Unpack a `dictionary` sequence /// /// - Parameters: /// - stream: input stream of data /// - count: number of keys in dictionary /// - Returns: decoded dictionary /// - Throws: throw an exception if failed to decoded data private func unpack(dictionary stream: inout StreamReader, count: Int) throws -> [AnyHashable: Any?] { var dict: [AnyHashable: Any?] = [:] for _ in 0..<count { guard let key = try self.unpack(stream: &stream) as? AnyHashable else { throw MsgPackError.unsupportedValue("Invalid dict key") } let val = try self.unpack(stream: &stream) dict[key] = val } return dict } /// Unpack an `array` sequence /// /// - Parameters: /// - stream: input stream of data /// - count: number of keys in array /// - Returns: decoded array /// - Throws: throw an exception if failed to decoded data private func unpack(array stream: inout StreamReader, count: Int) throws -> [Any?] { var array: [Any?] = [] for _ in 0..<count { array.append(try self.unpack(stream: &stream)) } return array } /// Unpack a `string` sequence /// /// - Parameters: /// - stream: input stream of data /// - length: length of data to read /// - Returns: decoded string /// - Throws: throw an exception if failed to decoded data private func unpack(string stream: inout StreamReader, length: Int) throws -> String { let data = try stream.readData(length: length) guard let str = String(data: data, encoding: String.Encoding.utf8) else { throw MsgPackError.invalidEncoding } return str } }
1dd5ddcb97291e880a2815565fe2c6fd
27.80829
103
0.67455
false
false
false
false
nalexn/ViewInspector
refs/heads/master
Sources/ViewInspector/SwiftUI/LazyHGrid.swift
mit
1
import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension ViewType { struct LazyHGrid: KnownViewType { public static var typePrefix: String = "LazyHGrid" } } // MARK: - Extraction from SingleViewContent parent @available(iOS 14.0, macOS 11.0, tvOS 14.0, *) public extension InspectableView where View: SingleViewContent { func lazyHGrid() throws -> InspectableView<ViewType.LazyHGrid> { return try .init(try child(), parent: self) } } // MARK: - Extraction from MultipleViewContent parent @available(iOS 14.0, macOS 11.0, tvOS 14.0, *) public extension InspectableView where View: MultipleViewContent { func lazyHGrid(_ index: Int) throws -> InspectableView<ViewType.LazyHGrid> { return try .init(try child(at: index), parent: self, index: index) } } // MARK: - Content Extraction @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.LazyHGrid: MultipleViewContent { public static func children(_ content: Content) throws -> LazyGroup<Content> { let view = try Inspector.attribute(path: "tree|content", value: content.view) return try Inspector.viewsInContainer(view: view, medium: content.medium) } } // MARK: - Custom Attributes @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) public extension InspectableView where View == ViewType.LazyHGrid { func alignment() throws -> VerticalAlignment { return try Inspector.attribute( label: "alignment", value: lazyHGridLayout(), type: VerticalAlignment.self) } func spacing() throws -> CGFloat? { return try Inspector.attribute( label: "spacing", value: lazyHGridLayout(), type: CGFloat?.self) } func pinnedViews() throws -> PinnedScrollableViews { return try Inspector.attribute( label: "pinnedViews", value: lazyHGridLayout(), type: PinnedScrollableViews.self) } func rows() throws -> [GridItem] { return try Inspector.attribute( label: "rows", value: lazyHGridLayout(), type: [GridItem].self) } private func lazyHGridLayout() throws -> Any { return try Inspector.attribute(path: "tree|root", value: content.view) } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension GridItem: Equatable { public static func == (lhs: GridItem, rhs: GridItem) -> Bool { return lhs.size == rhs.size && lhs.spacing == rhs.spacing && lhs.alignment == rhs.alignment } } @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension GridItem.Size: Equatable { public static func == (lhs: GridItem.Size, rhs: GridItem.Size) -> Bool { switch (lhs, rhs) { case let (.fixed(lhsValue), .fixed(rhsValue)): return lhsValue == rhsValue case let (.flexible(lhsMin, lhsMax), .flexible(rhsMin, rhsMax)): return lhsMin == rhsMin && lhsMax == rhsMax case let (.adaptive(lhsMin, lhsMax), .adaptive(rhsMin, rhsMax)): return lhsMin == rhsMin && lhsMax == rhsMax default: return false } } }
70e24c027c718c70a37765f8a13525ff
32.4
93
0.64324
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/develop
Example/Pods/RxSwift/RxSwift/Observables/Filter.swift
apache-2.0
20
// // Filter.swift // RxSwift // // Created by Krunoslav Zaher on 2/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> { return Filter(source: self.asObservable(), predicate: predicate) } } extension ObservableType { /** Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) - returns: An observable sequence that skips all elements of the source sequence. */ public func ignoreElements() -> Completable { return self.flatMap { _ in return Observable<Never>.empty() } .asCompletable() } } final private class FilterSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Predicate = (Element) throws -> Bool typealias Element = Observer.Element private let _predicate: Predicate init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { self._predicate = predicate super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let satisfies = try self._predicate(value) if satisfies { self.forwardOn(.next(value)) } } catch let e { self.forwardOn(.error(e)) self.dispose() } case .completed, .error: self.forwardOn(event) self.dispose() } } } final private class Filter<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool private let _source: Observable<Element> private let _predicate: Predicate init(source: Observable<Element>, predicate: @escaping Predicate) { self._source = source self._predicate = predicate } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = FilterSink(predicate: self._predicate, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
ac9e6103d6096b91ddf96acfe8ddfc11
32.422222
171
0.636303
false
false
false
false
yura-voevodin/SumDUBot
refs/heads/master
Sources/App/Commands/MessengerCommand.swift
mit
1
// // MessengerCommand.swift // App // // Created by Yura Voevodin on 24.09.17. // import Vapor final class MessengerComand: Command { /// See `Command` var arguments: [CommandArgument] { return [.argument(name: "type")] } /// See `Command`. public var options: [CommandOption] { return [] } /// See `Command` var help: [String] { return ["This command tests a Messenger bot"] } func run(using context: CommandContext) throws -> EventLoopFuture<Void> { let type = try context.argument("type") // TODO: Finish this command context.console.print(type, newLine: true) return .done(on: context.container) } /// Create a new `BootCommand`. public init() { } } // MARK: - Methods extension MessengerComand { private func search(_ request: String?) throws { // guard let request = request else { return } // // var searchResults: [Button] = [] // searchResults = try Auditorium.find(by: request) // // print(searchResults) } private func show(_ request: String?) throws { // guard let request = request else { return } // // var result: [String] = [] // if request.hasPrefix(ObjectType.auditorium.prefix) { // result = try Auditorium.show(for: request, client: client) // } // print(result) } }
2d84e3ff97fc79b082cec2101b86cdde
22.095238
77
0.564948
false
false
false
false
TouchInstinct/LeadKit
refs/heads/master
Sources/Extensions/DataLoading/PaginationDataLoading/PaginationWrapperUIDelegate+DefaultImplementation.swift
apache-2.0
1
// // Copyright (c) 2018 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 UIKit public extension PaginationWrapperUIDelegate { func emptyPlaceholder() -> UIView? { TextPlaceholderView(title: .empty) } func customInitialLoadingErrorHandling(for error: Error) -> Bool { false } func errorPlaceholder(for error: Error) -> UIView? { TextPlaceholderView(title: .error) } func initialLoadingIndicator() -> AnyLoadingIndicator? { let indicator = UIActivityIndicatorView(style: .whiteLarge) indicator.color = .gray return AnyLoadingIndicator(indicator) } func loadingMoreIndicator() -> AnyLoadingIndicator? { let indicator = UIActivityIndicatorView(style: .gray) return AnyLoadingIndicator(indicator) } func footerRetryView() -> ButtonHolderView? { let retryButton = UIButton(type: .custom) retryButton.backgroundColor = .lightGray retryButton.setTitle("Retry load more", for: .normal) return retryButton } func footerRetryViewHeight() -> CGFloat { 44 } func footerRetryViewWillAppear() { // by default - nothing will happen } func footerRetryViewWillDisappear() { // by default - nothing will happen } }
618c6f7ed4ab6234eeba9854ab339f25
32.323944
81
0.703297
false
false
false
false
envoy/Embassy
refs/heads/master
Sources/SelectSelector.swift
mit
1
// // SelectSelector.swift // Embassy // // Created by Fang-Pen Lin on 1/6/17. // Copyright © 2017 Fang-Pen Lin. All rights reserved. // import Foundation public final class SelectSelector: Selector { enum Error: Swift.Error { case keyError(fileDescriptor: Int32) } private var fileDescriptorMap: [Int32: SelectorKey] = [:] public init() throws { } @discardableResult public func register( _ fileDescriptor: Int32, events: Set<IOEvent>, data: Any? ) throws -> SelectorKey { // ensure the file descriptor doesn't exist already guard fileDescriptorMap[fileDescriptor] == nil else { throw Error.keyError(fileDescriptor: fileDescriptor) } let key = SelectorKey(fileDescriptor: fileDescriptor, events: events, data: data) fileDescriptorMap[fileDescriptor] = key return key } @discardableResult public func unregister(_ fileDescriptor: Int32) throws -> SelectorKey { // ensure the file descriptor exists guard let key = fileDescriptorMap[fileDescriptor] else { throw Error.keyError(fileDescriptor: fileDescriptor) } fileDescriptorMap.removeValue(forKey: fileDescriptor) return key } public func close() { } public func select(timeout: TimeInterval?) throws -> [(SelectorKey, Set<IOEvent>)] { var readSet = fd_set() var writeSet = fd_set() var maxFd: Int32 = 0 for (fd, key) in fileDescriptorMap { if fd > maxFd { maxFd = fd } if key.events.contains(.read) { SystemLibrary.fdSet(fd: fd, set: &readSet) } if key.events.contains(.write) { SystemLibrary.fdSet(fd: fd, set: &writeSet) } } let status: Int32 let microsecondsPerSecond = 1000000 if let timeout = timeout { var timeoutVal = timeval() #if os(Linux) timeoutVal.tv_sec = Int(timeout) timeoutVal.tv_usec = Int( Int(timeout * Double(microsecondsPerSecond)) - timeoutVal.tv_sec * microsecondsPerSecond ) #else // TODO: not sure is the calculation correct here timeoutVal.tv_sec = Int(timeout) timeoutVal.tv_usec = __darwin_suseconds_t( Int(timeout * Double(microsecondsPerSecond)) - timeoutVal.tv_sec * microsecondsPerSecond ) #endif status = SystemLibrary.select(maxFd + 1, &readSet, &writeSet, nil, &timeoutVal) } else { status = SystemLibrary.select(maxFd + 1, &readSet, &writeSet, nil, nil) } switch status { case 0: // TODO: timeout? return [] // Error case -1: throw OSError.lastIOError() default: break } var result: [(SelectorKey, Set<IOEvent>)] = [] for (fd, key) in fileDescriptorMap { var events = Set<IOEvent>() if SystemLibrary.fdIsSet(fd: fd, set: &readSet) { events.insert(.read) } if SystemLibrary.fdIsSet(fd: fd, set: &writeSet) { events.insert(.write) } if events.count > 0 { result.append((key, events)) } } return result } public subscript(fileDescriptor: Int32) -> SelectorKey? { get { return fileDescriptorMap[fileDescriptor] } } }
a9f39e1fd53153144e55f42e97b71754
29.579832
91
0.552075
false
false
false
false
BenEmdon/swift-algorithm-club
refs/heads/master
Binary Search/BinarySearch.playground/Sources/BinarySearch.swift
mit
22
/** Binary Search Recursively splits the array in half until the value is found. If there is more than one occurrence of the search key in the array, then there is no guarantee which one it finds. Note: The array must be sorted! **/ import Foundation // The recursive version of binary search. public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? { if range.lowerBound >= range.upperBound { return nil } else { let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 if a[midIndex] > key { return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) } else if a[midIndex] < key { return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) } else { return midIndex } } } /** The iterative version of binary search. Notice how similar these functions are. The difference is that this one uses a while loop, while the other calls itself recursively. **/ public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? { var lowerBound = 0 var upperBound = a.count while lowerBound < upperBound { let midIndex = lowerBound + (upperBound - lowerBound) / 2 if a[midIndex] == key { return midIndex } else if a[midIndex] < key { lowerBound = midIndex + 1 } else { upperBound = midIndex } } return nil }
124e8f368b4d6d8e77579e84da6d3d89
27.673077
86
0.617036
false
false
false
false
zhou9734/Warm
refs/heads/master
Warm/Classes/Me/Model/WMenu.swift
mit
1
// // Menu.swift // Warm // // Created by zhoucj on 16/9/17. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class WMenu: NSObject { var menus: [Menu]? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forKey key: String) { if key == "menus"{ guard let _data = value as? [[String: AnyObject]] else{ return } var _menus = [Menu]() for i in _data{ let menu = Menu(dict: i) _menus.append(menu) } menus = _menus return } super.setValue(value, forKey: key) } //防治没有匹配到的key报错 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } } class Menu: NSObject { var image: String? var name: String? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } //防治没有匹配到的key报错 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
965940b65b33bc26ea3468fb99e359c4
23.695652
76
0.554577
false
false
false
false
tnantoka/GameplayKitSandbox
refs/heads/master
GameplayKitSandbox/VisualComponent.swift
mit
1
// // VisualComponent.swift // GameplayKitSandbox // // Created by Tatsuya Tobioka on 2015/09/21. // Copyright © 2015年 tnantoka. All rights reserved. // import UIKit import SpriteKit import GameplayKit class VisualComponent: GKComponent { let sprite: SKSpriteNode var position = CGPoint.zero { didSet { sprite.position = position } } init(color: SKColor, size: CGSize) { sprite = SKSpriteNode(color: color, size: size) super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func moveTo(_ position: CGPoint) { let action = SKAction.move(to: position, duration: 0.3) sprite.run(action, completion: { self.position = position }) } func moveBy(_ x: CGFloat, _ y: CGFloat) { let p = CGPoint(x: position.x + x, y: position.y + y) moveTo(p) } }
4a70a924aa495fcd1f2328c390559f9d
21.209302
63
0.602094
false
false
false
false
sfsam/Snk
refs/heads/master
Snk/AppDelegate.swift
mit
1
// Created Sanjay Madan on May 26, 2015 // Copyright (c) 2015 mowglii.com import Cocoa // MARK: Main window final class MainWindow: NSWindow { // The main window is non-resizable and non-zoomable. // Its fixed size is determined by the MainVC's view. // The window uses the NSFullSizeContentViewWindowMask // so that we can draw our own custom title bar. convenience init() { self.init(contentRect: NSZeroRect, styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], backing: .buffered, defer: false) self.titlebarAppearsTransparent = true self.standardWindowButton(.zoomButton)?.alphaValue = 0 } // The app terminates when the main window is closed. override func close() { NSApplication.shared.terminate(nil) } // Fade the contentView when the window resigns Main. override func becomeMain() { super.becomeMain() contentView?.alphaValue = 1 } override func resignMain() { super.resignMain() contentView?.alphaValue = 0.6 } } // MARK: - App delegate // // AppDelegate handles the main window (it owns the main // window controller), clears the high scores, and toggles // the board size. @NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var themesMenu: NSMenu? let mainWC = NSWindowController(window: MainWindow()) func applicationWillFinishLaunching(_ notification: Notification) { // Prevent "Enter Full Screen" from appearing in menu. // stackoverflow.com/a/52158264/111418 UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere") } func applicationDidFinishLaunching(_ aNotification: Notification) { UserDefaults.standard.register(defaults: [ kHiScoreSlowKey: 0, kHiScoreMediumKey: 0, kHiScoreFastKey: 0, kEnableSoundsKey: true, kEnableMusicKey: true, kBigBoardKey: false, ]) setupThemesMenu() showMainWindow() } func showMainWindow() { // If we are re-showing the window (because the // user toggled its size or changed its theme), // first make sure it is not miniturized and // not showing. if mainWC.window?.isMiniaturized == true { mainWC.window?.deminiaturize(nil) } mainWC.window?.orderOut(nil) mainWC.contentViewController = MainVC() // Fade the window in. mainWC.window?.alphaValue = 0 mainWC.showWindow(self) mainWC.window?.center() moDispatch(after: 0.1) { self.mainWC.window?.animator().alphaValue = 1 } } @IBAction func clearScores(_ sender: AnyObject) { // Called from the Clear Scores... menu item. // Show an alert to confirm the user really // wants to erase their saved high scores. let alert = NSAlert() alert.messageText = NSLocalizedString("Clear scores?", comment: "") alert.informativeText = NSLocalizedString("Do you really want to clear your best scores?", comment: "") alert.addButton(withTitle: NSLocalizedString("No", comment: "")) alert.addButton(withTitle: NSLocalizedString("Yes", comment: "")) if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn { UserDefaults.standard.set(0, forKey: kHiScoreSlowKey) UserDefaults.standard.set(0, forKey: kHiScoreMediumKey) UserDefaults.standard.set(0, forKey: kHiScoreFastKey) } } @IBAction func toggleSize(_ sender: AnyObject) { // Called from Toggle Size menu item. // Toggle between standard and big board size. // Set the user default to the new value, set // kScale and kStep to their new values, hide // the main window and then re-show it. // Re-showing the window will re-instantiate // MainVC with the new sizes. SharedAudio.stopEverything() let bigBoard = kScale == 1 ? true : false UserDefaults.standard.set(bigBoard, forKey: kBigBoardKey) kScale = bigBoard ? 2 : 1 kStep = kBaseStep * Int(kScale) showMainWindow() } @objc func selectTheme(_ sender: NSMenuItem) { let newIndex = sender.tag let oldIndex = SharedTheme.themeIndex guard newIndex != oldIndex else { return } // Uncheck old theme menu item, check new one. themesMenu?.item(at: oldIndex)?.state = NSControl.StateValue(rawValue: 0) themesMenu?.item(at: newIndex)?.state = NSControl.StateValue(rawValue: 1) // Save the theme name and set the theme manager // to use the new one. let savedName = SharedTheme.themes[newIndex].name.rawValue UserDefaults.standard.set(savedName, forKey: kThemeNameKey) SharedTheme.setTheme(savedName: savedName) showMainWindow() } func setupThemesMenu() { // Set the theme manager to use the saved theme. SharedTheme.setTheme(savedName: UserDefaults.standard.string(forKey: kThemeNameKey)) // Create menu items for the themes in the theme // manager's 'themes' array. for (index, theme) in SharedTheme.themes.enumerated() { let item = NSMenuItem() item.title = theme.name.rawValue item.state = NSControl.StateValue(rawValue: index == SharedTheme.themeIndex ? 1 : 0) item.tag = index item.action = #selector(selectTheme(_:)) themesMenu?.addItem(item) } } }
b8bd2e3e6056f33d294d1b92bc133fb7
33.927711
148
0.625216
false
false
false
false
YMXian/Deliria
refs/heads/master
Deliria/Deliria/Crypto/Poly1305.swift
mit
1
// // Poly1305.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 30/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // // http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4 // /// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the /// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message. final public class Poly1305: Authenticator { public enum Error: Swift.Error { case authenticateError } let blockSize = 16 private var ctx: Context? private final class Context { var r = Array<UInt8>(repeating: 0, count: 17) var h = Array<UInt8>(repeating: 0, count: 17) var pad = Array<UInt8>(repeating: 0, count: 17) var buffer = Array<UInt8>(repeating: 0, count: 16) var final: UInt8 = 0 var leftover: Int = 0 init(_ key: Array<UInt8>) { precondition(key.count == 32, "Invalid key length") for i in 0..<17 { h[i] = 0 } r[0] = key[0] & 0xff r[1] = key[1] & 0xff r[2] = key[2] & 0xff r[3] = key[3] & 0x0f r[4] = key[4] & 0xfc r[5] = key[5] & 0xff r[6] = key[6] & 0xff r[7] = key[7] & 0x0f r[8] = key[8] & 0xfc r[9] = key[9] & 0xff r[10] = key[10] & 0xff r[11] = key[11] & 0x0f r[12] = key[12] & 0xfc r[13] = key[13] & 0xff r[14] = key[14] & 0xff r[15] = key[15] & 0x0f r[16] = 0 for i in 0..<16 { pad[i] = key[i + 16] } pad[16] = 0 leftover = 0 final = 0 } deinit { for i in 0..<buffer.count { buffer[i] = 0 } for i in 0..<r.count { r[i] = 0 h[i] = 0 pad[i] = 0 final = 0 leftover = 0 } } } /// - parameter key: 32-byte key public init (key: Array<UInt8>) { ctx = Context(key) } // MARK: - Private /** Add message to be processed - parameter context: Context - parameter message: message - parameter bytes: length of the message fragment to be processed */ private func update(_ context: Context, message: Array<UInt8>, bytes: Int? = nil) { var bytes = bytes ?? message.count var mPos = 0 /* handle leftover */ if (context.leftover > 0) { var want = blockSize - context.leftover if (want > bytes) { want = bytes } for i in 0..<want { context.buffer[context.leftover + i] = message[mPos + i] } bytes -= want mPos += want context.leftover += want if (context.leftover < blockSize) { return } blocks(context, m: context.buffer) context.leftover = 0 } /* process full blocks */ if (bytes >= blockSize) { let want = bytes & ~(blockSize - 1) blocks(context, m: message, startPos: mPos) mPos += want bytes -= want } /* store leftover */ if (bytes > 0) { for i in 0..<bytes { context.buffer[context.leftover + i] = message[mPos + i] } context.leftover += bytes } } private func finish(_ context: Context) -> Array<UInt8>? { var mac = Array<UInt8>(repeating: 0, count: 16) /* process the remaining block */ if (context.leftover > 0) { context.buffer[context.leftover] = 1 for i in (context.leftover + 1)..<blockSize { context.buffer[i] = 0 } context.final = 1 blocks(context, m: context.buffer) } /* fully reduce h */ freeze(context) /* h = (h + pad) % (1 << 128) */ add(context, c: context.pad) for i in 0..<mac.count { mac[i] = context.h[i] } return mac } // MARK: - Utils private func add(_ context: Context, c: Array<UInt8>) { if (context.h.count != 17 && c.count != 17) { assertionFailure() return } var u: UInt16 = 0 for i in 0..<17 { u += UInt16(context.h[i]) + UInt16(c[i]) context.h[i] = UInt8.with(value: u) u = u >> 8 } return } private func squeeze(_ context: Context, hr: Array<UInt32>) { if (context.h.count != 17 && hr.count != 17) { assertionFailure() return } var u: UInt32 = 0 for i in 0..<16 { u += hr[i] context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff u >>= 8 } u += hr[16] context.h[16] = UInt8.with(value: u) & 0x03 u >>= 2 u += (u << 2); /* u *= 5; */ for i in 0..<16 { u += UInt32(context.h[i]) context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff u >>= 8 } context.h[16] += UInt8.with(value: u) } private func freeze(_ context: Context) { assert(context.h.count == 17, "Invalid length") if (context.h.count != 17) { return } let minusp: Array<UInt8> = [0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc] var horig: Array<UInt8> = Array<UInt8>(repeating: 0, count: 17) /* compute h + -p */ for i in 0..<17 { horig[i] = context.h[i] } add(context, c: minusp) /* select h if h < p, or h + -p if h >= p */ let bits: [Bit] = (context.h[16] >> 7).bits() let invertedBits = bits.map({ (bit) -> Bit in return bit.inverted() }) let negative = UInt8(bits: invertedBits) for i in 0..<17 { context.h[i] ^= negative & (horig[i] ^ context.h[i]) } } private func blocks(_ context: Context, m: Array<UInt8>, startPos: Int = 0) { var bytes = m.count let hibit = context.final ^ 1 // 1 <<128 var mPos = startPos while (bytes >= Int(blockSize)) { var hr: Array<UInt32> = Array<UInt32>(repeating: 0, count: 17) var u: UInt32 = 0 var c: Array<UInt8> = Array<UInt8>(repeating: 0, count: 17) /* h += m */ for i in 0..<16 { c[i] = m[mPos + i] } c[16] = hibit add(context, c: c) /* h *= r */ for i in 0..<17 { u = 0 for j in 0...i { u = u + UInt32(UInt16(context.h[j])) * UInt32(context.r[i - j]) // u += (unsigned short)st->h[j] * st->r[i - j]; } for j in (i+1)..<17 { var v: UInt32 = UInt32(UInt16(context.h[j])) * UInt32(context.r[i + 17 - j]) // unsigned long v = (unsigned short)st->h[j] * st->r[i + 17 - j]; v = ((v << 8) &+ (v << 6)) u = u &+ v } hr[i] = u } squeeze(context, hr: hr) mPos += blockSize bytes -= blockSize } } //MARK: - Authenticator /** Calculate Message Authentication Code (MAC) for message. Calculation context is discarder on instance deallocation. - parameter bytes: Message - returns: 16-byte tag that authenticates the message */ public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> { guard let ctx = self.ctx else { throw Error.authenticateError } update(ctx, message: bytes) guard let result = finish(ctx) else { throw Error.authenticateError } return result } }
3dc921d7fbcfbd2b409fe5f495201b07
26.692308
164
0.460024
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
refs/heads/master
MobilePeopleDirectory/PeopleListViewController.swift
gpl-3.0
1
// // PeopleListViewController.swift // MobilePeopleDirectory // // Created by Martin Zary on 1/6/15. // Copyright (c) 2015 Rivet Logic. All rights reserved. // import UIKit import CoreData class PeopleListViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! var searchActive:Bool = false var searchResultsList: [Person] = [] var personViewController: PersonViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil var peopleDao:PeopleDao = PeopleDao() var imageHelper:ImageHelper = ImageHelper() var serverFetchResult : ServerFetchResult = ServerFetchResult.Success var alertHelper:AlertHelper = AlertHelper() var appHelper = AppHelper() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.personViewController = controllers[controllers.count-1].topViewController as? PersonViewController } self.navigationItem.leftBarButtonItem = nil self.navigationItem.rightBarButtonItem = nil let logoutButton = UIBarButtonItem(image: UIImage(named: "logout"), style: UIBarButtonItemStyle.Plain, target: self, action: "logout:") self.navigationItem.rightBarButtonItem = logoutButton navigationController?.hidesBarsOnSwipe = true navigationController?.hidesBarsWhenKeyboardAppears = true //search bar if let search = self.searchBar { self.searchBar.delegate = self } } func logout(sender:UIBarButtonItem) { self.alertHelper.confirmationMessage(self, title: "Please confirm", message: "Are you sure you want to logout?", okButtonText: "Yes", cancelButtonText: "No", confirmed: { _ in self.appHelper.logout(self) }) } private func _showConnectionErrorMessage() { alertHelper.message(self, title: "Network", message: "There are connectivity issues please try again", buttonText: "OK", callback: {}) } override func loadView() { if !SessionContext.loadSessionFromStore() { self.appHelper.logout(self) } else { super.loadView() } } override func viewWillAppear(animated: Bool) { var this = self var peopleSync = ServerSync(syncable: peopleDao, primaryKey: "userId", itemsCountKey: "activeUsersCount", listKey: "users", errorHandler: { error in if error == ServerFetchResult.ConnectivityIssue { println("Connectivity issues") self._showConnectionErrorMessage() } }) serverFetchResult = peopleSync.syncData() self.searchActive = false self.searchResultsList = [] if let table = self.tableView { self.tableView.reloadData() } if let search = self.searchBar { self.searchBar.text = "" } let appDelegate: AppDelegate = appHelper.getAppDelegate() appDelegate.statusBar.backgroundColor = navigationController?.navigationBar.backgroundColor self.navigationController?.navigationBarHidden = false } override func viewDidAppear(animated: Bool) { if serverFetchResult == .CredIssue { let loginViewController = Storyboards.Login.Storyboard().instantiateInitialViewController() as? LoginViewController self.parentViewController?.presentViewController(loginViewController!, animated: true, completion: nil) } if serverFetchResult == .ConnectivityIssue { //TODO: Alert view informing the user of a network error and pointing the to the refresh button to try again } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { // let context = self.fetchedResultsController.managedObjectContext // let entity = self.fetchedResultsController.fetchRequest.entity! // let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject // // // If appropriate, configure the new managed object. // // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. // newManagedObject.setValue(NSDate(), forKey: "timeStamp") // // // Save the context. // var error: NSError? = nil // if !context.save(&error) { // // Replace this implementation with code to handle the error appropriately. // // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // //println("Unresolved error \(error), \(error.userInfo)") // abort() // } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { var person:Person if searchActive && self.searchResultsList.count > 0 { person = searchResultsList[indexPath.row] } else { person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person } let controller = (segue.destinationViewController as! UINavigationController).topViewController as! PersonViewController controller.detailItem = person controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.searchActive { return self.searchResultsList.count } let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 85.0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell", forIndexPath: indexPath) as! PersonViewCell self.configureCell(cell, atIndexPath: indexPath) if indexPath.row % 2 == 0 { cell.contentView.backgroundColor = UIColor.whiteColor() } else { cell.contentView.backgroundColor = UIColor(red: 241.0/255.0, green: 241.0/255.0, blue: 241.0/255.0, alpha: 1.0) } return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) var error: NSError? = nil if !context.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: PersonViewCell, atIndexPath indexPath: NSIndexPath) { var person:Person if searchActive && self.searchResultsList.count > 0 { person = searchResultsList[indexPath.row] } else { person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person } //NSLog(person.description) imageHelper.addThumbnailStyles(cell.thumbnailImage, radius: 30.0) if imageHelper.hasUserImage(person.portraitUrl) { imageHelper.addImageFromData(cell.thumbnailImage, image: person.portraitImage) } else { cell.thumbnailImage.image = UIImage(named: "UserDefaultImage") } cell.username!.text = person.screenName cell.skypeIcon.hidden = (person.skypeName == "") cell.emailIcon.hidden = (person.emailAddress == "") cell.phoneIcon.hidden = (person.userPhone == "") cell.fullName!.text = person.fullName } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "fullName", ascending: true) let sortDescriptors = [sortDescriptor] fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil ) aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController var error: NSError? = nil if !_fetchedResultsController!.performFetch(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) //case .Update: // self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)! as PersonViewCell, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ // MARK: - Search func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchActive = true; searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchActive = false; searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchActive = false; searchBar.resignFirstResponder() searchBar.setShowsCancelButton(false, animated: true) tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchActive = false; searchBar.resignFirstResponder() searchBar.setShowsCancelButton(false, animated: true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { let searchString = searchText searchResultsList.removeAll(keepCapacity: true) if !searchString.isEmpty { let filter:Person -> Bool = { person in let nameLength = count(person.fullName) let fullNameRange = person.fullName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) let screenNameRange = person.screenName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) let emailAddress = person.emailAddress.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) return fullNameRange != nil || screenNameRange != nil || emailAddress != nil } let sectionInfo = self.fetchedResultsController.sections![0] as! NSFetchedResultsSectionInfo let persons = sectionInfo.objects as! [Person] searchResultsList = persons.filter(filter) } if(searchResultsList.count == 0){ searchActive = false; } else { searchActive = true; } self.tableView.reloadData() } override func viewWillDisappear(animated: Bool) { //if searchBar.isFirstResponder() { // searchBar.resignFirstResponder() //} } }
56ff62d1619a949a27ae0d127da1dd8b
42.082902
360
0.658088
false
false
false
false
RMK19/UITextField-Shake
refs/heads/master
UITExtField-Shake/UITextField+Shake.swift
mit
1
// // UITextField+Shake.swift // TextField-Shake // // Created by Apple on 02/05/15. // Copyright (c) 2015 Rugmangathan. All rights reserved. // import Foundation import UIKit enum ShakeDirection: Int { case horizontal = 0, vertical }; extension UITextField { func shake(times: Int, delta: CGFloat) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: 0.03, shakeDirection: .horizontal, completionHandler: nil) } func shake(times: Int, delta: CGFloat, completionHandler: (() -> Void)?) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: 0.03, shakeDirection: .horizontal, completionHandler: completionHandler) } public func shake(times: Int, delta: CGFloat, speed: Double) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: speed, shakeDirection: .horizontal, completionHandler: nil) } public func shake(times: Int, delta: CGFloat, speed: Double, completionHandler: (() -> Void)?) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: speed, shakeDirection: .horizontal, completionHandler: completionHandler) } func shake(times: Int, delta: CGFloat, speed: Double, shakeDirection: ShakeDirection) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: speed, shakeDirection: shakeDirection, completionHandler: nil) } func shake(times: Int, delta: CGFloat, speed: Double, shakeDirection: ShakeDirection, completionHandler: (() -> Void)?) { shake(times: times, direction: 1, currentTimes: 0, withDelta: delta, andSpeed: speed, shakeDirection: shakeDirection, completionHandler: completionHandler) } func shake(times: Int, direction: Int, currentTimes: Int, withDelta: CGFloat, andSpeed: Double, shakeDirection: ShakeDirection, completionHandler: (() -> Void)?) { let animations: () -> Void = { [weak self] in guard let strongSelf = self else { return } strongSelf.transform = (shakeDirection == .horizontal ? CGAffineTransform(translationX: withDelta * CGFloat(direction), y: 0) : CGAffineTransform(translationX: 0, y: withDelta * CGFloat(direction))) } let animationCompletion: (Bool) -> Void = { [weak self] finished in guard let strongSelf = self else { return } if (currentTimes >= times) { UIView.animate(withDuration: andSpeed, animations: { strongSelf.transform = CGAffineTransform.identity }, completion: { (complete: Bool) in if (completionHandler != nil) { completionHandler?() } }) return } strongSelf.shake(times: (times - 1), direction: (direction * -1), currentTimes: (currentTimes + 1), withDelta: withDelta, andSpeed: andSpeed, shakeDirection: shakeDirection, completionHandler: completionHandler) } UIView.animate(withDuration: TimeInterval(andSpeed), animations: animations, completion: animationCompletion) } }
e2e29f92770e157c4568b176027e9530
32.601695
100
0.527617
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/Utility/Networking/WordPressComRestApi+Defaults.swift
gpl-2.0
1
import Foundation import WordPressKit extension WordPressComRestApi { @objc public static func defaultApi(oAuthToken: String? = nil, userAgent: String? = nil, localeKey: String = WordPressComRestApi.LocaleKeyDefault) -> WordPressComRestApi { return WordPressComRestApi(oAuthToken: oAuthToken, userAgent: userAgent, localeKey: localeKey, baseUrlString: Environment.current.wordPressComApiBase) } /// Returns the default API the default WP.com account using the given context @objc public static func defaultApi(in context: NSManagedObjectContext, userAgent: String? = WPUserAgent.wordPress(), localeKey: String = WordPressComRestApi.LocaleKeyDefault) -> WordPressComRestApi { let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: context) let token: String? = defaultAccount?.authToken return WordPressComRestApi.defaultApi(oAuthToken: token, userAgent: WPUserAgent.wordPress()) } }
d44c21573c274bcd46c57ca2290936fc
47.807692
122
0.584712
false
false
false
false
1457792186/JWSwift
refs/heads/master
CKMnemonic/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift
apache-2.0
5
// // UInt64Extension.swift // CryptoSwift // // Copyright (C) 2014-2017 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. // /** array of bytes */ extension UInt64 { @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Iterator.Element == UInt8, T.IndexDistance == Int, T.Index == Int { self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.IndexDistance == Int, T.Index == Int { let val0 = UInt64(bytes[index.advanced(by: 0)]) << 56 let val1 = UInt64(bytes[index.advanced(by: 1)]) << 48 let val2 = UInt64(bytes[index.advanced(by: 2)]) << 40 let val3 = UInt64(bytes[index.advanced(by: 3)]) << 32 let val4 = UInt64(bytes[index.advanced(by: 4)]) << 24 let val5 = UInt64(bytes[index.advanced(by: 5)]) << 16 let val6 = UInt64(bytes[index.advanced(by: 6)]) << 8 let val7 = UInt64(bytes[index.advanced(by: 7)]) self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 } func bytes(totalBytes: Int = MemoryLayout<UInt64>.size) -> Array<UInt8> { return arrayOfBytes(value: self, length: totalBytes) } }
0d036f6640da315a95a1596d26372a60
49.952381
217
0.683645
false
false
false
false
jellybeansoup/ios-sherpa
refs/heads/main
src/Sherpa/ArticleViewController.swift
bsd-2-clause
1
// // Copyright © 2021 Daniel Farrelly // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit import WebKit import SafariServices internal class ArticleViewController: ListViewController { // MARK: Instance life cycle internal let article: Article! init(document: Document, article: Article) { self.article = article super.init(document: document) dataSource.sectionTitle = NSLocalizedString("Related", comment: "Title for table view section containing one or more related articles.") dataSource.filter = { (article: Article) -> Bool in return article.key != nil && self.article.relatedKeys.contains(article.key!) } allowSearch = false bodyView.navigationDelegate = self bodyView.loadHTMLString(prepareHTML, baseURL: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View life cycle internal let contentView: UIView = UIView() internal let bodyView: WKWebView = WKWebView() private var loadingObserver: NSKeyValueObservation? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = nil contentView.preservesSuperviewLayoutMargins = true bodyView.backgroundColor = UIColor.clear bodyView.scrollView.isScrollEnabled = false bodyView.isOpaque = false contentView.addSubview(bodyView) loadingObserver = bodyView.observe(\.isLoading) { webView, change in guard change.newValue == false else { return } self.updateHeight(for: webView) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if contentView.superview == nil || contentView.frame.width != contentView.superview!.frame.width { layoutHeaderView() } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory { bodyView.loadHTMLString(prepareHTML, baseURL: nil) } } private func layoutHeaderView() { let margins = tableView.layoutMargins let width = tableView.frame.width let maxSize = CGSize(width: width - margins.left - margins.right, height: CGFloat.greatestFiniteMagnitude) let bodySize = bodyView.scrollView.contentSize bodyView.frame = CGRect(x: margins.left, y: 30, width: maxSize.width, height: bodySize.height) contentView.frame = CGRect(x: 0, y: 0, width: width, height: bodyView.frame.maxY) tableView.tableHeaderView = contentView } fileprivate var prepareHTML: String { let font = UIFont.preferredFont(forTextStyle: .body) let color = self.css(for: dataSource.document.articleTextColor) let weight = font.fontDescriptor.symbolicTraits.contains(.traitBold) ? "bold" : "normal" var css = """ body {margin: 0;font-family: -apple-system,system-ui,sans-serif;font-size: \(font.pointSize)px;line-height: 1.4;color: \(color);font-weight: \(weight);} img {max-width: 100%; opacity: 1;transition: opacity 0.3s;} img[data-src] {opacity: 0;} h1, h2, h3, h4, h5, h6 {font-weight: 500;line-height: 1.2;} h1 {font-size: 1.6em;} h2 {font-size: 1.4em;} h3 {font-size: 1.2em;} h4 {font-size: 1.0em;} h5 {font-size: 0.8em;} h6 {font-size: 0.6em;} """ if let tintColor = dataSource.document.tintColor ?? view.tintColor { css += " a {color: \(self.css(for: tintColor));}" } if let articleCSS = dataSource.document.articleCSS { css += " \(articleCSS)" } var string = article.body var searchRange = Range(uncheckedBounds: (lower: string.startIndex, upper: string.endIndex)) while let range = string.range(of: "(<img[^>]*)( src=\")", options: .regularExpression, range: searchRange) { string = string.replacingOccurrences(of: "src=\"", with: "data-src=\"", options: [], range: range) searchRange = Range(uncheckedBounds: (lower: range.lowerBound, upper: string.endIndex)) } return """ <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"> <style type="text/css">\(css)</style> <style type="text/css">body {background-color: transparent !important;}</style> </head> <body><h1>\(article.title)</h1>\n\(paragraphs(for: string))</body> <script type="text/javascript"> [].forEach.call(document.querySelectorAll('img[data-src]'), function(img) { img.setAttribute('src', img.getAttribute('data-src')); img.onload = function() { img.removeAttribute('data-src'); }; }); </script> </html> """ } fileprivate func css(for color: UIColor) -> String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return "rgba(\(Int(red * 255)), \(Int(green * 255)), \(Int(blue * 255)), \(alpha))" } fileprivate func paragraphs(for string: String) -> String { var string = string.trimmingCharacters(in: .whitespacesAndNewlines) guard string.range(of: "<(p|br)[/\\s>]", options: .regularExpression) == nil else { return string } while let range = string.range(of: "\n") { string.replaceSubrange(range, with: "<br/>") } return string } } extension ArticleViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url, navigationAction.navigationType != .other else { decisionHandler(.allow) return } let configuration = SFSafariViewController.Configuration() let viewController = SFSafariViewController(url: url, configuration: configuration) self.present(viewController, animated: true, completion: nil) decisionHandler(.cancel) } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { continuouslyUpdateHeight(for: webView) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { updateHeight(for: webView) } private func continuouslyUpdateHeight(for webView: WKWebView) { updateHeight(for: webView) guard webView.isLoading else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.continuouslyUpdateHeight(for: webView) } } private func updateHeight(for webView: WKWebView) { webView.evaluateJavaScript("document.body.scrollHeight") { response, _ in guard let number = response as? NSNumber else { return } webView.frame.size.height = CGFloat(number.doubleValue) self.layoutHeaderView() } } }
32f2b3e496094f6eeaa691f83e7cfbb9
31.631579
154
0.723945
false
false
false
false
leizh007/HiPDA
refs/heads/master
HiPDA/HiPDA/Sections/Login/LoginViewController.swift
mit
1
// // LoginViewController.swift // HiPDA // // Created by leizh007 on 16/9/3. // Copyright © 2016年 HiPDA. All rights reserved. // import UIKit import RxSwift import RxCocoa import MessageUI /// 登录成功后的回调 typealias LoggedInCompletionHandler = (Account) -> Void /// 默认的容器视图的顶部constraint private let kDefaultContainerTopConstraintValue = CGFloat(44.0) /// 登录的ViewController class LoginViewController: BaseViewController, StoryboardLoadable { /// 分割线的高度constriant @IBOutlet private var seperatorsHeightConstraint: [NSLayoutConstraint]! /// 点击背景的手势识别 @IBOutlet private var tapBackground: UITapGestureRecognizer! /// 显示密码被点击 @IBOutlet private var tapShowPassword: UITapGestureRecognizer! /// 输入密码的TextField @IBOutlet private weak var passwordTextField: UITextField! /// 隐藏显示密码的ImageView @IBOutlet private weak var hidePasswordImageView: UIImageView! /// 输入姓名的TextField @IBOutlet private weak var nameTextField: UITextField! /// 输入答案的TextField @IBOutlet private weak var answerTextField: UITextField! /// 安全问题Button @IBOutlet private weak var questionButton: UIButton! /// 是否可取消 var cancelable = false /// 取消按钮 @IBOutlet private weak var cancelButton: UIButton! /// 安全问题的driver private var questionDriver: Driver<Int>! /// 回答的driver private var answerDriver: Driver<String>! /// 登录按钮 @IBOutlet private weak var loginButton: UIButton! /// 容器视图的顶部constraint @IBOutlet private weak var containerTopConstraint: NSLayoutConstraint! /// 登录成功后的回调 var loggedInCompletion: LoggedInCompletionHandler? var cancelCompletion: ((Void) -> Void)? // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() cancelButton.isHidden = !cancelable configureKeyboard() configureQuestionButton() configureTapGestureRecognizer() configureTextFields() configureViewModel() } @IBAction func adviseButtonPressed(_ sender: UIButton) { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients([C.URL.authorEmail]) present(mail, animated: true, completion: nil) } else { UIApplication.shared.openURL(URL(string: "mailto:\(C.URL.authorEmail)")!) } } @IBAction func registerButtonPressed(_ sender: UIButton) { URLDispatchManager.shared.linkActived("https://www.hi-pda.com/forum/tobenew.php") } override func setupConstraints() { for heightConstraint in seperatorsHeightConstraint { heightConstraint.constant = 1.0 / UIScreen.main.scale } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - private method /// 设置手势识别 private func configureTapGestureRecognizer() { tapShowPassword.rx.event.subscribe(onNext: { [weak self] _ in guard let `self` = self else { return } let isSecureTextEntry = self.passwordTextField.isSecureTextEntry self.passwordTextField.isSecureTextEntry = !isSecureTextEntry let image: UIImage switch isSecureTextEntry { case true: image = #imageLiteral(resourceName: "login_password_show") case false: image = #imageLiteral(resourceName: "login_password_hide") } UIView.transition(with: self.hidePasswordImageView, duration: C.UI.animationDuration, options: .transitionCrossDissolve, animations: { self.hidePasswordImageView.image = image }, completion: nil) }).addDisposableTo(disposeBag) } /// 设置TextFields private func configureTextFields() { let textValue = Variable("") (passwordTextField.rx.textInput <-> textValue).addDisposableTo(disposeBag) textValue.asObservable().map { $0.characters.count == 0 } .bindTo(hidePasswordImageView.rx.isHidden).addDisposableTo(disposeBag) passwordTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in self?.answerTextField.becomeFirstResponder() }).addDisposableTo(disposeBag) nameTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in self?.passwordTextField.becomeFirstResponder() }).addDisposableTo(disposeBag) answerTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in self?.answerTextField.resignFirstResponder() }).addDisposableTo(disposeBag) } /// 配置安全问题的Button private func configureQuestionButton() { let questionVariable = Variable(0) let answerVariable = Variable("") (answerTextField.rx.textInput <-> answerVariable).addDisposableTo(disposeBag) questionButton.rx.tap.subscribe(onNext: { [weak self] _ in guard let `self` = self else { return } let questions = LoginViewModel.questions let pickerActionSheetController = PickerActionSheetController.load(from: .views) pickerActionSheetController.pickerTitles = questions pickerActionSheetController.initialSelelctionIndex = questions.index(of: self.questionButton.title(for: .normal)!) pickerActionSheetController.selectedCompletionHandler = { [unowned self] (index) in self.dismiss(animated: false, completion: nil) if let index = index, let title = questions.safe[index] { self.questionButton.setTitle(title, for: .normal) questionVariable.value = index } } pickerActionSheetController.modalPresentationStyle = .overCurrentContext self.present(pickerActionSheetController, animated: false, completion: nil) }).addDisposableTo(disposeBag) questionDriver = questionVariable.asDriver() questionDriver.drive(onNext: { [weak self] (index) in guard let `self` = self else { return } if index == 0 { self.answerTextField.isEnabled = false self.passwordTextField.returnKeyType = .done } else { self.answerTextField.isEnabled = true self.passwordTextField.returnKeyType = .next } answerVariable.value = "" }).addDisposableTo(disposeBag) answerDriver = answerVariable.asDriver() } /// 处理键盘相关 private func configureKeyboard() { let dismissEvents: [Observable<Void>] = [ tapBackground.rx.event.map { _ in () }, questionButton.rx.tap.map { _ in () }, cancelButton.rx.tap.map { _ in () }, loginButton.rx.tap.map { _ in () } ] Observable.from(dismissEvents).merge().subscribe(onNext: { [weak self] _ in self?.nameTextField.resignFirstResponder() self?.passwordTextField.resignFirstResponder() self?.answerTextField.resignFirstResponder() }).addDisposableTo(disposeBag) KeyboardManager.shared.keyboardChanged.drive(onNext: { [weak self, unowned keyboardManager = KeyboardManager.shared] transition in guard let `self` = self else { return } guard transition.toVisible.boolValue else { self.containerTopConstraint.constant = kDefaultContainerTopConstraintValue UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: { self.view.layoutIfNeeded() }, completion: nil) return } guard let textField = self.activeTextField() else { return } let keyboardFrame = keyboardManager.convert(transition.toFrame, to: self.view) let textFieldFrame = textField.convert(textField.frame, to: self.view) let heightGap = textFieldFrame.origin.y + textFieldFrame.size.height - keyboardFrame.origin.y let containerTopConstraintConstant = heightGap > 0 ? self.containerTopConstraint.constant - heightGap : kDefaultContainerTopConstraintValue self.containerTopConstraint.constant = containerTopConstraintConstant UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: { self.view.layoutIfNeeded() }, completion: nil) }).addDisposableTo(disposeBag) } /// 配置ViewModel相关信息 func configureViewModel() { let nameVariable = Variable("") let passwordVariable = Variable("") (nameTextField.rx.textInput <-> nameVariable).addDisposableTo(disposeBag) (passwordTextField.rx.textInput <-> passwordVariable).addDisposableTo(disposeBag) let viewModel = LoginViewModel(username: nameVariable.asDriver(), password: passwordVariable.asDriver(), questionid: questionDriver, answer: answerDriver, loginTaps: loginButton.rx.tap.asDriver()) viewModel.loginEnabled.drive(loginButton.rx.isEnabled).addDisposableTo(disposeBag) viewModel.loggedIn.drive(onNext: { [unowned self] result in self.hidePromptInformation() switch result { case .success(let account): self.showPromptInformation(of: .success("登录成功")) Settings.shared.shouldAutoLogin = true delay(seconds: 1.0) { self.loggedInCompletion?(account) } case .failure(let error): self.showPromptInformation(of: .failure("\(error)")) } }).addDisposableTo(disposeBag) loginButton.rx.tap.subscribe(onNext: { [weak self] _ in self?.showPromptInformation(of: .loading("正在登录...")) }).addDisposableTo(disposeBag) cancelButton.rx.tap.subscribe(onNext: { [weak self] _ in self?.cancelCompletion?() self?.presentingViewController?.dismiss(animated: true, completion: nil) }).addDisposableTo(disposeBag) if let account = Settings.shared.lastLoggedInAccount { nameVariable.value = account.name passwordVariable.value = account.password } } /// 找到激活的textField /// /// - returns: 返回first responser的textField private func activeTextField() -> UITextField? { for textField in [nameTextField, passwordTextField, answerTextField] { if textField!.isFirstResponder { return textField } } return nil } } extension LoginViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } }
c46b9bfb0decaa1e30d8f0e8e6b48090
38.923875
151
0.627058
false
false
false
false
RailwayStations/Bahnhofsfotos
refs/heads/develop
Modules/Data/Sources/Storage/CountryStorage.swift
apache-2.0
1
// // CountryStorage.swift // Bahnhofsfotos // // Created by Miguel Dönicke on 30.01.17. // Copyright © 2017 MrHaitec. All rights reserved. // import Domain import Foundation import Shared import SQLite import SwiftyUserDefaults public class CountryStorage { enum CountryError: Error { case message(String?) } public static var lastUpdatedAt: Date? private static var _countries: [Country] = [] public static var countries: [Country] { return _countries } public static var currentCountry: Country? { return CountryStorage.countries.first(where: { (country) -> Bool in country.code == Defaults.country }) } // table name for "migration" ... private static let tableOldName = "country" private static let tableName = "country_3" // SQLite properties private static let fileName = Constants.dbFilename private static let tableOld = Table(tableOldName) private static let table = Table(tableName) fileprivate static let expressionCountryCode = Expression<String>(Constants.JsonConstants.kCountryCode) fileprivate static let expressionCountryName = Expression<String>(Constants.JsonConstants.kCountryName) fileprivate static let expressionMail = Expression<String?>(Constants.JsonConstants.kCountryEmail) // OLD fileprivate static let expressionEmail = Expression<String?>(Constants.JsonConstants.kCountryEmail) fileprivate static let expressionTwitterTags = Expression<String?>(Constants.JsonConstants.kCountryTwitterTags) fileprivate static let expressionTimetableUrlTemplate = Expression<String?>(Constants.JsonConstants.kCountryTimetableUrlTemplate) // Open connection to database private static func openConnection() throws -> Connection { // find path to SQLite database guard let path = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true) .first else { throw CountryError.message("Path not found.") } // open connection let db = try Connection("\(path)/\(fileName)") // delete old table if exists if tableOldName != tableName { try db.run(tableOld.drop(ifExists: true)) } // create table if not exists try db.run(table.create(ifNotExists: true) { table in table.column(expressionCountryCode, primaryKey: true) table.column(expressionCountryName) table.column(expressionEmail) table.column(expressionTwitterTags) table.column(expressionTimetableUrlTemplate) }) // return connection return db } // Remove all public static func removeAll() throws { let db = try openConnection() try db.run(table.delete()) lastUpdatedAt = Date() } // Fetch all stations public static func fetchAll() throws { let db = try openConnection() _countries.removeAll() for country in try db.prepare(table) { let c = Country.from(row: country) _countries.append(c) } _countries = _countries.sorted { $0.name < $1.name } lastUpdatedAt = Date() } // Save a station public static func create(country: Country) throws { let db = try openConnection() try db.run(table.insert(expressionCountryName <- country.name, expressionCountryCode <- country.code, expressionEmail <- country.email, expressionTwitterTags <- country.twitterTags, expressionTimetableUrlTemplate <- country.timetableUrlTemplate )) _countries.append(country) _countries = _countries.sorted { $0.name < $1.name } lastUpdatedAt = Date() } } // MARK: - Country extension public extension Country { public func save() throws { try CountryStorage.create(country: self) } public static func from(row: Row) -> Country { .init( name: try! row.get(CountryStorage.expressionCountryName), code: try! row.get(CountryStorage.expressionCountryCode), email: try! row.get(CountryStorage.expressionEmail), twitterTags: try! row.get(CountryStorage.expressionTwitterTags), timetableUrlTemplate: try! row.get(CountryStorage.expressionTimetableUrlTemplate) ) } }
0907c2e7cde1c3eeca1b3a4a6af9cfc9
32.132353
133
0.648913
false
false
false
false
CodaFi/swift
refs/heads/master
test/stdlib/Reflection.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %{python} %S/../Inputs/timeout.py 360 %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // FIXME: timeout wrapper is necessary because the ASan test runs for hours // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // import Swift // A more interesting struct type. struct Complex<T> { let real, imag: T } // CHECK-LABEL: Complex: print("Complex:") // CHECK-NEXT: Reflection.Complex<Swift.Double> // CHECK-NEXT: real: 1.5 // CHECK-NEXT: imag: 0.75 dump(Complex<Double>(real: 1.5, imag: 0.75)) // CHECK-NEXT: Reflection.Complex<Swift.Double> // CHECK-NEXT: real: -1.5 // CHECK-NEXT: imag: -0.75 dump(Complex<Double>(real: -1.5, imag: -0.75)) // CHECK-NEXT: Reflection.Complex<Swift.Int> // CHECK-NEXT: real: 22 // CHECK-NEXT: imag: 44 dump(Complex<Int>(real: 22, imag: 44)) // CHECK-NEXT: Reflection.Complex<Swift.String> // CHECK-NEXT: real: "is this the real life?" // CHECK-NEXT: imag: "is it just fantasy?" dump(Complex<String>(real: "is this the real life?", imag: "is it just fantasy?")) // Test destructuring of a pure Swift class hierarchy. class Good { let x: UInt = 11 let y: String = "222" } class Better : Good { let z: Double = 333.5 } class Best : Better { let w: String = "4444" } // CHECK-LABEL: Root class: // CHECK-NEXT: Reflection.Good #0 // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" print("Root class:") dump(Good()) // CHECK-LABEL: Subclass: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Subclass:") dump(Best()) // Test protocol types, which reflect as their dynamic types. // CHECK-LABEL: Any int: // CHECK-NEXT: 1 print("Any int:") var any: Any = 1 dump(any) // CHECK-LABEL: Any class: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Any class:") any = Best() dump(any) // CHECK-LABEL: second verse // CHECK-NEXT: Reflection.Best #0 print("second verse same as the first:") dump(any) // CHECK-LABEL: Any double: // CHECK-NEXT: 2.5 print("Any double:") any = 2.5 dump(any) // CHECK-LABEL: Character: // CHECK-NEXT: "a" print("Character:") dump(Character("a")) protocol Fooable {} extension Int : Fooable {} extension Double : Fooable {} // CHECK-LABEL: Fooable int: // CHECK-NEXT: 1 print("Fooable int:") var fooable: Fooable = 1 dump(fooable) // CHECK-LABEL: Fooable double: // CHECK-NEXT: 2.5 print("Fooable double:") fooable = 2.5 dump(fooable) protocol Barrable : class {} extension Best: Barrable {} // CHECK-LABEL: Barrable class: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Barrable class:") var barrable: Barrable = Best() dump(barrable) // CHECK-LABEL: second verse // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("second verse same as the first:") dump(barrable) // CHECK-NEXT: Logical: true switch true.customPlaygroundQuickLook { case .bool(let x): print("Logical: \(x)") default: print("wrong quicklook type") } let intArray = [1,2,3,4,5] // CHECK-NEXT: 5 elements // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 dump(intArray) var justSomeFunction = { (x:Int) -> Int in return x + 1 } // CHECK-NEXT: (Function) dump(justSomeFunction as Any) // CHECK-NEXT: Swift.String dump(String.self) // CHECK-NEXT: ▿ // CHECK-NEXT: from: 1.0 // CHECK-NEXT: through: 12.15 // CHECK-NEXT: by: 3.14 dump(stride(from: 1.0, through: 12.15, by: 3.14)) // CHECK-NEXT: nil var nilUnsafeMutablePointerString: UnsafeMutablePointer<String>? dump(nilUnsafeMutablePointerString) // CHECK-NEXT: 123456 // CHECK-NEXT: - pointerValue: 1193046 var randomUnsafeMutablePointerString = UnsafeMutablePointer<String>( bitPattern: 0x123456)! dump(randomUnsafeMutablePointerString) // CHECK-NEXT: Hello panda var sanePointerString = UnsafeMutablePointer<String>.allocate(capacity: 1) sanePointerString.initialize(to: "Hello panda") dump(sanePointerString.pointee) sanePointerString.deinitialize(count: 1) sanePointerString.deallocate() // Don't crash on types with opaque metadata. rdar://problem/19791252 // CHECK-NEXT: (Opaque Value) var rawPointer = unsafeBitCast(0 as Int, to: Builtin.RawPointer.self) dump(rawPointer) // CHECK-LABEL: and now our song is done print("and now our song is done")
60a5eeef8bdea0ace4781cb7cb36ccb9
25.538071
82
0.654552
false
false
false
false
SwifterLC/SinaWeibo
refs/heads/master
LCSinaWeibo/LCSinaWeibo/Classes/Tools/extension/UILabel+Extension.swift
mit
1
// // UILabel+Extension.swift // LCSinaWeibo // // Created by 刘成 on 2017/8/3. // Copyright © 2017年 刘成. All rights reserved. // import UIKit extension UILabel{ /// 居中无行数限制 UILabel 便利构造函数 /// /// - Parameters: /// - title: UILabel title /// - fontSize: title 字体大小,默认系统字体14字号 /// - color: title 颜色,默认深灰色 convenience init(title: String, //label 文本 fontSize: CGFloat = 14, //字体大小 color: UIColor = UIColor.darkGray, //文字颜色 aligment:NSTextAlignment = .center, //文字对齐 margin:CGFloat = 0){ //文本框 margin self.init() text = title textColor = color textAlignment = aligment numberOfLines = 0 font = UIFont.systemFont(ofSize: fontSize) if margin != 0 { preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * margin } } }
dd2f7fc75afe2176dd9ffb53ba273eeb
28.058824
78
0.511134
false
false
false
false
peihsendoyle/ZCPlayer
refs/heads/master
ZCPlayer/ZCPlayer/PlayerController.swift
apache-2.0
1
// // PlayerController.swift // ZCPlayer // // Created by Doyle Illusion on 7/4/17. // Copyright © 2017 Zyncas Technologies. All rights reserved. // import Foundation import UIKit import AVFoundation class PlayerController : NSObject { fileprivate var mRestoreAfterScrubbingRate: Float = 0.0 fileprivate var player : AVPlayer! fileprivate var playerItem : AVPlayerItem! fileprivate var observer : AVObserver? lazy var playerView : PlayerView = { let view = PlayerView() view.delegate = self (view.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravityResizeAspect return view }() fileprivate var currentTime : Double = 0.0 fileprivate var durationTime : Double = 0.0 fileprivate var timeObserver : Any? fileprivate var isSeeking = false required init(url: URL) { super.init() self.playerItem = AVPlayerItem(url: url) self.player = AVPlayer(playerItem: self.playerItem) self.addLifeObservers() (self.playerView.layer as! AVPlayerLayer).player = self.player PlayerControllerManager.shared.dict[url.absoluteString] = self } func addLifeObservers() { self.observer = AVObserver(player: self.player) { (status, message, object) in switch status { case .playerFailed: self.syncScrubber() self.disableScrubber() self.removePlayerViewFromSuperview() print("Player failed. We don't have logic to recover from this.") case .itemFailed: self.removePlayerTimeObserver() self.syncScrubber() self.disableScrubber() self.removePlayerViewFromSuperview() print("Item failed. We don't have logic to recover from this.") case .stalled: print("Playback stalled at \(self.player.currentItem!.currentDate() ?? Date())") case .itemReady: self.initScrubberTimer() self.enableScrubber() case .accessLog: print("New Access log") case .errorLog: print("New Error log") case .playing: print("Status: Playing") case .paused: print("Status: Paused") case .likelyToKeepUp: self.playerView.hideLoading() case .unlikelyToKeepUp: self.playerView.showLoading() self.playerView.showContainerView() case .timeJump: print("Player reports that time jumped.") case .loadedTimeRanges: self.playerView.slider.setProgress(progress: self.getAvailableTime(), animated: true) default: break } } } func addPlayerViewToSuperview(view: UIView) { // if self.player.currentItem == nil { // self.player.replaceCurrentItem(with: self.playerItem) // } guard let player = self.player else { return } player.play() self.playerView.frame = view.bounds if !view.subviews.last!.isKind(of: PlayerView.self) { // First time init --> cell need to add playerView again view.addSubview(self.playerView) } else { if let lastPlayerView = view.subviews.last as? PlayerView { guard lastPlayerView !== self.playerView else { /* Non reuse here */ return } /* After Reused */ lastPlayerView.removeFromSuperview() view.addSubview(self.playerView) } } } func removePlayerViewFromSuperview() { guard let player = self.player else { return } player.pause() self.playerView.hideContainerView() // self.player.replaceCurrentItem(with: nil) } func initScrubberTimer() { guard let playerDuration = self.getItemDuration() else { return } self.durationTime = CMTimeGetSeconds(playerDuration) self.playerView.syncDuration(value: self.durationTime) var interval: Double = 0.1 if self.durationTime.isFinite { interval = 0.5 * self.durationTime / Double(self.playerView.slider.bounds.width) } self.timeObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(interval, Int32(NSEC_PER_SEC)), queue: nil, using: { [weak self] (time: CMTime) -> Void in guard let `self` = self else { return } self.syncScrubber() }) } func syncScrubber() { if self.durationTime.isFinite { let minValue = self.playerView.slider.minimumValue let maxValue = self.playerView.slider.maximumValue let time = CMTimeGetSeconds(self.player.currentTime()) guard time.isFinite else { return } self.playerView.syncTime(value: time) self.playerView.syncSlider(value: Double((maxValue - minValue) * Float(time) / Float(self.durationTime) + minValue)) } } func beginScrubbing() { mRestoreAfterScrubbingRate = self.player.rate self.player.rate = 0.0 self.removePlayerTimeObserver() } func scrub(_ sender: AnyObject) { if (sender is UISlider) && !self.isSeeking { self.isSeeking = true let slider = sender if self.durationTime.isFinite { let minValue: Float = slider.minimumValue let maxValue: Float = slider.maximumValue let value: Float = slider.value let time = (self.durationTime * Double((value - minValue) / (maxValue - minValue))) self.playerView.syncTime(value: time) self.player.seek(to: CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)), completionHandler: {(finished: Bool) -> Void in DispatchQueue.main.async(execute: { [weak self] () -> Void in self?.isSeeking = false }) }) } } } func endScrubbing() { guard timeObserver == nil else { return } if mRestoreAfterScrubbingRate != 0.0 { self.player.rate = mRestoreAfterScrubbingRate mRestoreAfterScrubbingRate = 0.0 //self.isPlay = true } if self.durationTime.isFinite { let width: CGFloat = self.playerView.slider.bounds.width let tolerance: Double = 0.5 * self.durationTime / Double(width) self.timeObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(tolerance, Int32(NSEC_PER_SEC)), queue: nil, using: { [weak self] (time: CMTime) -> Void in guard let `self` = self else { return } self.syncScrubber() }) } } func isScrubbing() -> Bool { return mRestoreAfterScrubbingRate != 0.0 } func enableScrubber() { self.playerView.enableSlider() } func disableScrubber() { self.playerView.disableSlider() } func toggle(isPlay: Bool) { isPlay ? self.player.pause() : self.player.play() } func getAvailableTime() -> Float { let timeRange = self.playerItem.loadedTimeRanges[0].timeRangeValue let startSeconds = CMTimeGetSeconds(timeRange.start) let durationSeconds = CMTimeGetSeconds(timeRange.duration) let result = startSeconds + durationSeconds return Float(result) } fileprivate func getItemDuration() -> CMTime? { guard let playerItem = self.playerItem else { return nil } return playerItem.duration } func removePlayerTimeObserver() { guard timeObserver != nil else { return } self.player.removeTimeObserver(timeObserver!) self.timeObserver = nil } func removeLifeObserver() { self.observer?.stop() self.observer = nil } } extension PlayerController : PlayerViewDelegate { func didTouchToggleButton(isPlay: Bool) { self.toggle(isPlay: isPlay) } func didScrubbing() { self.scrub(self.playerView.slider) } func didBeginScrubbing() { self.beginScrubbing() } func didEndScrubbing() { self.endScrubbing() } }
38f6e8612a48129ac9e4d1aedfd397ec
33.587045
194
0.586445
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dMaterial.swift
gpl-3.0
1
// // dMaterial.swift // DrakkenEngine // // Created by Allison Lindner on 23/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Foundation public class dMaterialDef { internal var name: String internal var shader: String fileprivate var buffers: [String : dBufferable] = [:] fileprivate var textures: [String : dMaterialTexture] = [:] public init(name: String, shader: String) { self.name = name self.shader = shader } internal func set(buffer name: String, _ data: dBufferable) { self.buffers[name] = data } internal func set(texture name: String, _ data: dTexture, _ index: Int) { let materialTexture = dMaterialTexture(texture: data, index: index) self.textures[name] = materialTexture } internal func get(texture name: String) -> dTexture? { return self.textures[name]?.texture } internal func get(buffer name: String) -> dBufferable? { return self.buffers[name] } } internal class dMaterial { private var _materialDef: dMaterialDef internal init(materialDef: dMaterialDef) { self._materialDef = materialDef } internal func build() { var buffers: [dBufferable] = [] for buffer in _materialDef.buffers { buffers.append(buffer.value) } var textures: [dMaterialTexture] = [] for materialTexture in _materialDef.textures { textures.append(materialTexture.value) } dCore.instance.mtManager.create(name: _materialDef.name, shader: _materialDef.shader, buffers: buffers, textures: textures) } }
786002c9cc1e879068d2aadddedcf74a
24.396825
74
0.6675
false
false
false
false
inket/MacSymbolicator
refs/heads/master
MacSymbolicator/Models/Architecture.swift
gpl-2.0
1
// // Architecture.swift // MacSymbolicator // import Foundation enum Architecture: Hashable { case x86 case x86_64 // swiftlint:disable:this identifier_name case arm64 case arm(String?) private static let architectureRegex = #"^(?:Architecture|Code Type):(.*?)(\(.*\))?$"# private static let binaryImagesRegex = #"Binary Images:.*\s+([^\s]+)\s+<"# static func find(in content: String) -> Architecture? { var result = content.scan(pattern: Self.architectureRegex).first?.first?.trimmed .components(separatedBy: " ").first.flatMap(Architecture.init) // In the case of plain "ARM" (without version or specifiers) the actual architecture is on // the first line of Binary Images. Cannot find recent examples of this, but keeping behavior just in case. if result?.isIncomplete == true { result = (content.scan( pattern: Self.binaryImagesRegex, options: [.caseInsensitive, .anchorsMatchLines, .dotMatchesLineSeparators] ).first?.first?.trimmed).flatMap(Architecture.init) } return result } init?(_ string: String) { let archString = string.lowercased() if archString.hasPrefix("x86-64") || archString.hasPrefix("x86_64") { // Example sub-architecture: x86_64h self = .x86_64 } else if ["x86", "i386"].contains(archString) { self = .x86 } else if archString == "arm" { self = .arm(nil) // More details can be found in the binary images, e.g. arm64e } else if ["arm-64", "arm64", "arm_64"].contains(archString) { self = .arm64 } else if archString.hasPrefix("arm") { // Example sub-architecture: armv7 self = .arm(archString) } else { return nil } } var atosString: String? { switch self { case .x86: return "i386" case .x86_64: return "x86_64" case .arm64: return "arm64" case .arm(let raw): return raw } } var isIncomplete: Bool { switch self { case .x86, .x86_64, .arm64: return false case .arm(let raw): return raw == nil } } }
f5ae7fb049d50b73983075325570d62a
32.552239
115
0.580961
false
false
false
false
PureSwift/CoreModel
refs/heads/develop
Sources/CoreDataModel/NSManagedObject.swift
mit
2
// // NSManagedObject.swift // CoreDataModel // // Created by Alsey Coleman Miller on 11/4/18. // #if canImport(CoreData) import Foundation import CoreData import CoreModel public final class CoreDataManagedObject: CoreModel.ManagedObject { internal let managedObject: NSManagedObject internal init(_ managedObject: NSManagedObject) { self.managedObject = managedObject } public var store: NSManagedObjectContext? { return managedObject.managedObjectContext } public var isDeleted: Bool { return managedObject.isDeleted } public func attribute(for key: String) -> AttributeValue { return managedObject.attribute(for: key) } public func setAttribute(_ newValue: AttributeValue, for key: String) { managedObject.setAttribute(newValue, for: key) } public func relationship(for key: String) -> RelationshipValue<CoreDataManagedObject> { guard let objectValue = managedObject.value(forKey: key) else { return .null } if let managedObject = objectValue as? NSManagedObject { return .toOne(CoreDataManagedObject(managedObject)) } else if let managedObjects = objectValue as? Set<NSManagedObject> { return .toMany(Set(managedObjects.map { CoreDataManagedObject($0) })) } else { fatalError("Invalid CoreData relationship value \(objectValue)") } } public func setRelationship(_ newValue: RelationshipValue<CoreDataManagedObject>, for key: String) { let objectValue: AnyObject? switch newValue { case .null: objectValue = nil case let .toOne(value): objectValue = value.managedObject case let .toMany(value): objectValue = Set(value.map({ $0.managedObject })) as NSSet } managedObject.setValue(objectValue, forKey: key) } } public extension CoreDataManagedObject { public static func == (lhs: CoreDataManagedObject, rhs: CoreDataManagedObject) -> Bool { return lhs.managedObject == rhs.managedObject } } public extension CoreDataManagedObject { public var hashValue: Int { return managedObject.hashValue } } internal extension NSManagedObject { func attribute(for key: String) -> AttributeValue { guard let objectValue = self.value(forKey: key) else { return .null } if let string = objectValue as? String { return .string(string) } else if let data = objectValue as? Data { return .data(data) } else if let date = objectValue as? Date { return .date(date) } else if let value = objectValue as? Bool { return .bool(value) } else if let value = objectValue as? Int16 { return .int16(value) } else if let value = objectValue as? Int32 { return .int32(value) } else if let value = objectValue as? Int64 { return .int64(value) } else if let value = objectValue as? Float { return .float(value) } else if let value = objectValue as? Double { return .double(value) } else { fatalError("Invalid CoreData attribute value \(objectValue)") } } func setAttribute(_ newValue: AttributeValue, for key: String) { let objectValue: AnyObject? switch newValue { case .null: objectValue = nil case let .string(value): objectValue = value as NSString case let .data(value): objectValue = value as NSData case let .date(value): objectValue = value as NSDate case let .bool(value): objectValue = value as NSNumber case let .int16(value): objectValue = value as NSNumber case let .int32(value): objectValue = value as NSNumber case let .int64(value): objectValue = value as NSNumber case let .float(value): objectValue = value as NSNumber case let .double(value): objectValue = value as NSNumber } self.setValue(objectValue, forKey: key) } } #endif
e640c482a6f55ecad182a7fc7e5e7d99
26.085714
104
0.555063
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Modules/Weekly Summary/WeeklySummaryViewController.swift
bsd-3-clause
1
import UIKit import RxCocoa import RxSwift class WeeklySummaryViewController: UIViewController { fileprivate var viewModel : WeeklySummaryViewModel! private var presenter : WeeklySummaryPresenter! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var weeklyChartView: ChartView! @IBOutlet weak var weekLabel: UILabel! @IBOutlet weak var previousButton: UIButton! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var categoryButtons: ButtonsCollectionView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var pieChart: ActivityPieChartView! @IBOutlet weak var emptyStateView: WeeklySummaryEmptyStateView! @IBOutlet weak var monthSelectorView: UIView! private var disposeBag = DisposeBag() func inject(presenter:WeeklySummaryPresenter, viewModel: WeeklySummaryViewModel) { self.presenter = presenter self.viewModel = viewModel } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.scrollView.addSubview(self.emptyStateView) previousButton.rx.tap .subscribe(onNext: { [unowned self] in self.viewModel.nextWeek() }) .disposed(by: disposeBag) nextButton.rx.tap .subscribe(onNext: { [unowned self] in self.viewModel.previousWeek() }) .disposed(by: disposeBag) viewModel.weekTitle .bind(to: weekLabel.rx.text) .disposed(by: disposeBag) // Chart View weeklyChartView.datasource = viewModel weeklyChartView.delegate = self viewModel.firstDayIndex .subscribe(onNext:weeklyChartView.setWeekStart) .disposed(by: disposeBag) // Category Buttons categoryButtons.toggleCategoryObservable .subscribe(onNext:viewModel.toggleCategory) .disposed(by: disposeBag) categoryButtons.categories = viewModel.topCategories .do(onNext: { [unowned self] _ in self.weeklyChartView.refresh() }) //Pie chart viewModel .weekActivities .map { activityWithPercentage in return activityWithPercentage.map { $0.0 } } .subscribe(onNext:self.pieChart.setActivities) .disposed(by: disposeBag) //Table view tableView.rowHeight = 48 tableView.allowsSelection = false tableView.separatorStyle = .none viewModel.weekActivities .do(onNext: { [unowned self] activities in self.tableViewHeightConstraint.constant = CGFloat(activities.count * 48) self.view.setNeedsLayout() }) .map { [unowned self] activities in return activities.sorted(by: self.areInIncreasingOrder) } .bind(to: tableView.rx.items(cellIdentifier: WeeklySummaryCategoryTableViewCell.identifier, cellType: WeeklySummaryCategoryTableViewCell.self)) { _, model, cell in cell.activityWithPercentage = model } .disposed(by: disposeBag) //Empty state viewModel.weekActivities .observeOn(MainScheduler.instance) .subscribe(onNext: { activityWithPercentage in self.emptyStateView.isHidden = !activityWithPercentage.isEmpty }) .disposed(by: disposeBag) scrollView.addTopShadow() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) scrollView.flashScrollIndicators() } private func areInIncreasingOrder(a1: ActivityWithPercentage, a2: ActivityWithPercentage) -> Bool { return a1.1 > a2.1 } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.emptyStateView.frame = self.weeklyChartView.frame } } extension WeeklySummaryViewController: ChartViewDelegate { func pageChange(index: Int) { viewModel.setFirstDay(index: index) } }
4a7ca258f52bc3e3ef0a50c156615962
30.883212
157
0.621795
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/LanguageTranslatorV3/Models/Language.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2020. * * 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 /** Response payload for languages. */ public struct Language: Codable, Equatable { /** The language code for the language (for example, `af`). */ public var language: String? /** The name of the language in English (for example, `Afrikaans`). */ public var languageName: String? /** The native name of the language (for example, `Afrikaans`). */ public var nativeLanguageName: String? /** The country code for the language (for example, `ZA` for South Africa). */ public var countryCode: String? /** Indicates whether words of the language are separated by whitespace: `true` if the words are separated; `false` otherwise. */ public var wordsSeparated: Bool? /** Indicates the direction of the language: `right_to_left` or `left_to_right`. */ public var direction: String? /** Indicates whether the language can be used as the source for translation: `true` if the language can be used as the source; `false` otherwise. */ public var supportedAsSource: Bool? /** Indicates whether the language can be used as the target for translation: `true` if the language can be used as the target; `false` otherwise. */ public var supportedAsTarget: Bool? /** Indicates whether the language supports automatic detection: `true` if the language can be detected automatically; `false` otherwise. */ public var identifiable: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case language = "language" case languageName = "language_name" case nativeLanguageName = "native_language_name" case countryCode = "country_code" case wordsSeparated = "words_separated" case direction = "direction" case supportedAsSource = "supported_as_source" case supportedAsTarget = "supported_as_target" case identifiable = "identifiable" } }
0db6fa00b18132579876b8baaae9e5d4
30.22093
120
0.673371
false
false
false
false
materik/stubborn
refs/heads/master
Stubborn/Http/Response.swift
mit
1
extension Stubborn { class Response { let url: Request.URL let body: Body var response: HTTPURLResponse { return HTTPURLResponse( url: Foundation.URL(string: self.url)!, statusCode: statusCode, httpVersion: nil, headerFields: [ "Content-Type": "application/json", "Content-Length": String(self.data.count), ] )! } var statusCode: Request.StatusCode { if let error = self.body as? Body.Error { return error.statusCode } else if let statusCode = self.body as? Body.Simple { return statusCode.statusCode } else { return 200 } } var data: Data { // NOTE(materik): // * seems I have to print the data in order to load it because sometime the data // turns up empty even if it's cleary not. must be a better way but this is a fix for now print(self.body.data) return self.body.data } var error: Swift.Error? { return (self.body as? Body.Error)?.error } init(request: Request) { self.url = request.url self.body = Body([:]) } init?(request: Request, stub: Stub) { guard stub.isStubbing(request: request) else { return nil } self.url = request.url self.body = stub.loadBody(request) } } }
5ffb1adc2c89254e91c1f007fc44f0a8
28.210526
103
0.473874
false
false
false
false
Chris-Perkins/Lifting-Buddy
refs/heads/master
Lifting Buddy/WorkoutTableView.swift
mit
1
// // WorkoutTableView.swift // Lifting Buddy // // Created by Christopher Perkins on 9/4/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit import RealmSwift import Realm import CDAlertView class WorkoutTableView: UITableView { // MARK: View Properties // The data displayed in cells private var sortedData: [(String, [Workout])] private var data: AnyRealmCollection<Workout> // MARK: Initializers override init(frame: CGRect, style: UITableView.Style) { let realm = try! Realm() data = AnyRealmCollection(realm.objects(Workout.self)) sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data) super.init(frame: frame, style: style) setupTableView() } init(style: UITableView.Style) { let realm = try! Realm() data = AnyRealmCollection(realm.objects(Workout.self)) sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data) super.init(frame: .zero, style: style) setupTableView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: TableView Functions override func reloadData() { let realm = try! Realm() data = AnyRealmCollection(realm.objects(Workout.self)) sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data) super.reloadData() } // MARK: Custom functions // Retrieve workouts public func getSortedData() -> [(String, [Workout])] { return sortedData } private func setupTableView() { delegate = self dataSource = self allowsSelection = true register(WorkoutTableViewCell.self, forCellReuseIdentifier: "cell") backgroundColor = .clear } } extension WorkoutTableView: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return sortedData.count } // Data is what we use to fill in the table view func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sortedData[section].1.count } // Create our custom cell class func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! WorkoutTableViewCell cell.showViewDelegate = superview as? ShowViewDelegate cell.setWorkout(workout: sortedData[indexPath.section].1[indexPath.row]) cell.updateSelectedStatus() // IndexPath of 0 denotes that this workout is today cell.workoutRequiresAttention = indexPath.section == 0 return cell } // Deletion methods func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let workout = sortedData[indexPath.section].1[indexPath.row] if workout.canModifyCoreProperties { let alert = CDAlertView(title: NSLocalizedString("Message.DeleteWorkout.Title", comment: ""), message: "This will delete all records of '\(workout.getName()!)', and this includes its occurrences on other days." + "This action cannot be undone.", type: CDAlertViewType.warning) alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.Cancel", comment: ""), font: nil, textColor: UIColor.white, backgroundColor: UIColor.niceBlue, handler: nil)) alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.Delete", comment: ""), font: nil, textColor: UIColor.white, backgroundColor: UIColor.niceRed, handler: { (CDAlertViewAction) in MessageQueue.shared.append(Message(type: .objectDeleted, identifier: workout.getName(), value: nil)) let realm = try! Realm() try! realm.write { realm.delete(workout) } self.reloadData() return true })) alert.show() } else { let alert = CDAlertView(title: NSLocalizedString("Message.CannotDeleteWorkout.Title", comment: ""), message: NSLocalizedString("Message.CannotDeleteWorkout.Desc", comment: ""), type: CDAlertViewType.error) alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.OK", comment: ""), font: nil, textColor: UIColor.white, backgroundColor: UIColor.niceBlue, handler: nil)) alert.show() } } } } extension WorkoutTableView: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.backgroundView?.backgroundColor = UIColor.lightBlackWhiteColor headerView.textLabel?.textColor = UILabel.titleLabelTextColor } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sortedData[section].1.isEmpty ? 0 : 30 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sortedData[section].0 } // Expand this cell, un-expand the other cell func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let cell = cellForRow(at: indexPath) as! WorkoutTableViewCell if indexPathForSelectedRow == indexPath { deselectRow(at: indexPath, animated: true) reloadData() cell.updateSelectedStatus() return nil } else { var cell2: WorkoutTableViewCell? = nil if indexPathForSelectedRow != nil { cell2 = cellForRow(at: indexPathForSelectedRow!) as? WorkoutTableViewCell } selectRow(at: indexPath, animated: false, scrollPosition: .none) reloadData() scrollToRow(at: indexPath, at: .none, animated: true) cell2?.updateSelectedStatus() cell.updateSelectedStatus() return indexPath } } // Each cell's height depends on whether or not it has been selected func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let exerCount = CGFloat(sortedData[indexPath.section].1[indexPath.row].getExercises().count) return indexPathForSelectedRow?.elementsEqual(indexPath) ?? false ? UITableViewCell.defaultHeight + PrettyButton.defaultHeight + exerCount * WorkoutTableViewCell.heightPerExercise + WorkoutTableViewCell.heightPerLabel : UITableViewCell.defaultHeight } }
6697111bcdba6995a0d5cb4927876c6c
41.852217
163
0.524313
false
false
false
false
zhangliangzhi/RollCall
refs/heads/master
RollCall/UserMinePage/UserMineViewController.swift
mit
1
// // UserMineViewController.swift // RollCall // // Created by ZhangLiangZhi on 2016/11/24. // Copyright © 2016年 xigk. All rights reserved. // import Foundation import UIKit import Charts import SwiftDate class UserMineViewController: UIViewController, ChartViewDelegate, IAxisValueFormatter { @IBOutlet weak var barChartView: BarChartView! struct MemCount { let name:String var count:Int let id:Int32 } var arrMemNameCount : [MemCount] = [] override func viewWillAppear(_ animated: Bool) { if arrClassData.count > 0 { self.navigationController?.navigationBar.topItem?.title = arrClassData[gIndexClass].classname! + "|" + arrClassData[gIndexClass].selCourse! } else { TipsSwift.showCenterWithText("请先创建班级!") } getMemCountName() chartsGo() } override func viewDidLoad() { barChartView.xAxis.valueFormatter = self barChartView.chartDescription?.text = "by 🍉西瓜点名🍉" } public func stringForValue(_ value: Double, axis: Charts.AxisBase?) -> String { return arrMemNameCount[Int(value)].name } func chartsGo() { if arrMemNameCount.count == 0 { TipsSwift.showCenterWithText("没有班级成员!") } // print(arrMemNameCount.count) var values: [Double] = [] for i in 0..<arrMemNameCount.count { let d:Double = Double(arrMemNameCount[i].count) values.append(d) } // print(values) var entries: [ChartDataEntry] = Array() for (i, value) in values.enumerated() { entries.append( BarChartDataEntry(x: Double(i), y: value) ) } let dataSet: BarChartDataSet = BarChartDataSet(values: entries, label: "点名次数") let data = BarChartData(dataSet: dataSet) data.barWidth = 0.85 dataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)] barChartView.backgroundColor = NSUIColor.clear barChartView.xAxis.labelPosition = .bottom let xAxis = barChartView.xAxis xAxis.drawGridLinesEnabled = false barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .linear) barChartView.data = data } func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { print(highlight) print(entry) } // 获取成员的总点名次数 func getMemCountName() -> Void { if arrClassData.count == 0 { return } let dateStart:String = arrClassData[gIndexClass].dateStart! let dateEnd:String = arrClassData[gIndexClass].dateEnd! let startTime = try! DateInRegion.init(string: dateStart, format: DateFormat.custom("yyyy-MM-dd")) let endTime = try! DateInRegion.init(string: dateEnd, format: DateFormat.custom("yyyy-MM-dd")) arrMemNameCount = [] // 获取所有成员id let strMembers:String = arrClassData[gIndexClass].member! let membersJsonData = strMembers.data(using: .utf8) var arrMembers = JSON(data:membersJsonData!) for i in 0..<arrMembers.count { let id:Int32 = arrMembers[i]["id"].int32Value var one:MemCount=MemCount(name: arrMembers[i]["name"].stringValue, count: 0, id: id) arrMemNameCount.append(one) } arrMemNameCount.sort(by: {$0.id<$1.id}) // 统计目前时间范围内的 次数 for i in 0..<arrCallFair.count { let one = arrCallFair[i] let onedate = DateInRegion.init(absoluteDate: one.date as! Date) let id:Int = Int(one.memID) // 统计在时间范围内的次数 if onedate >= startTime && onedate <= endTime { // 是选定课程 if arrClassData[gIndexClass].selCourse == one.course { for j in 0..<arrMemNameCount.count { if arrMemNameCount[j].id == one.memID { arrMemNameCount[j].count = arrMemNameCount[j].count + 1 break } } } } } // print(arrMemNameCount) return } }
08efbac24d8448ebaa9784022b715b10
31.659091
151
0.583159
false
false
false
false
liutongchao/LCRefresh
refs/heads/master
Source/LCRefreshFooter.swift
mit
1
// // LCRefreshFooter.swift // LCRefresh // // Created by 刘通超 on 16/8/3. // Copyright © 2016年 West. All rights reserved. // import UIKit public final class LCRefreshFooter: UIView { public let contenLab = UILabel() public let activity = UIActivityIndicatorView() var refreshStatus: LCRefreshFooterStatus? var refreshBlock: (()->Void)? required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public init(frame: CGRect) { super.init(frame: frame) configView() } public init(refreshBlock:@escaping (()->Void)) { super.init(frame: CGRect(x: LCRefresh.Const.Footer.X, y: LCRefresh.Const.Footer.Y, width: LCRefresh.Const.Common.screenWidth, height: LCRefresh.Const.Footer.height)) self.backgroundColor = UIColor.clear self.refreshBlock = refreshBlock configView() } public init(width:CGFloat ,refreshBlock:@escaping (()->Void)) { super.init(frame: CGRect(x: LCRefresh.Const.Footer.X, y: LCRefresh.Const.Footer.Y, width: width, height: LCRefresh.Const.Footer.height)) self.backgroundColor = UIColor.clear self.refreshBlock = refreshBlock configView() } func configView() { addSubview(contenLab) addSubview(activity) contenLab.frame = self.bounds contenLab.textAlignment = .center contenLab.text = "上拉加载更多数据" contenLab.font = UIFont.systemFont(ofSize: 14) activity.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) activity.activityIndicatorViewStyle = .gray activity.center = CGPoint.init(x: 40, y: LCRefresh.Const.Header.height/2) } func setStatus(_ status:LCRefreshFooterStatus){ refreshStatus = status switch status { case .normal: setNomalStatus() break case .waitRefresh: setWaitRefreshStatus() break case .refreshing: setRefreshingStatus() break case .loadover: setLoadoverStatus() break } } } extension LCRefreshFooter{ /** 各种状态切换 */ func setNomalStatus() { if activity.isAnimating { activity.stopAnimating() } activity.isHidden = true contenLab.text = "上拉加载更多数据" } func setWaitRefreshStatus() { if activity.isAnimating { activity.stopAnimating() } activity.isHidden = true contenLab.text = "松开加载更多数据" } func setRefreshingStatus() { activity.isHidden = false activity.startAnimating() contenLab.text = "正在加载更多数据..." } func setLoadoverStatus() { if activity.isAnimating { activity.stopAnimating() } activity.isHidden = true contenLab.text = "全部加载完毕" } }
62e6413e7726d57ef68a79fc7be7beda
24.827586
173
0.593792
false
false
false
false
OpenKitten/BSON
refs/heads/master/6.0
Sources/BSON/Types/RegularExpression.swift
mit
1
// // RegularExpression.swift // BSON // // Created by Robbert Brandsma on 23/07/2018. // import Foundation /// The `RegularExpression` struct represents a regular expression as part of a BSON `Document`. /// /// An extension to `NSRegularExpression` is provided for converting between `Foundation.NSRegularExpression` and `BSON.RegularExpression`. public struct RegularExpression: Primitive, Equatable { private enum CodingKeys: String, CodingKey { case pattern = "$regex" case options = "$options" } public var pattern: String public var options: String /// Returns an initialized BSON RegularExpression instance with the specified regular expression pattern and options. public init(pattern: String, options: String) { self.pattern = pattern self.options = options } /// Initializes the `RegularExpression` using the pattern and options from the given NSRegularExpression. /// /// The following mapping is used for regular expression options (Foundation -> BSON): /// /// - caseInsensitive -> i /// - anchorsMatchLines -> m /// - dotMatchesLineSeparators -> s /// /// Other options are discarded. public init(_ regex: NSRegularExpression) { self.pattern = regex.pattern self.options = makeBSONOptions(from: regex.options) } // MARK: - Codable public init(from decoder: Decoder) throws { if let container = (try? decoder.singleValueContainer() as? AnySingleValueBSONDecodingContainer) ?? nil { self = try container.decodeRegularExpression() } else { let container = try decoder.container(keyedBy: CodingKeys.self) self.pattern = try container.decode(String.self, forKey: .pattern) self.options = try container.decode(String.self, forKey: .options) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(pattern, forKey: .pattern) try container.encode(options, forKey: .options) } } extension NSRegularExpression { /// Returns an initialized NSRegularExpression instance with the pattern and options from the specified BSON regular expression. public convenience init(_ regex: RegularExpression) throws { try self.init(pattern: regex.pattern, options: makeFoundationOptions(from: regex.options)) } } extension NSRegularExpression: PrimitiveConvertible { public func makePrimitive() -> Primitive? { return RegularExpression(self) } } fileprivate func makeBSONOptions(from options: NSRegularExpression.Options) -> String { var optionsString = "" // Options are identified by characters, which must be stored in alphabetical order if options.contains(.caseInsensitive) { optionsString += "i" } if options.contains(.anchorsMatchLines) { optionsString += "m" } if options.contains(.dotMatchesLineSeparators) { optionsString += "s" } return optionsString } fileprivate func makeFoundationOptions(from string: String) -> NSRegularExpression.Options { var options: NSRegularExpression.Options = [] if string.contains("i") { options.insert(.caseInsensitive) } if string.contains("m") { options.insert(.anchorsMatchLines) } if string.contains("s") { options.insert(.dotMatchesLineSeparators) } return options }
7bba08f078c967cddb7a5359df9ed784
31.550459
139
0.673055
false
false
false
false
weipin/jewzruxin
refs/heads/master
Jewzruxin/Source/HTTP/Service.swift
mit
1
// // Service.swift // // Copyright (c) 2015 Weipin Xia // // 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 /** This class is an abstract class you use to represent a "service". Because it is abstract, you do not use this class directly but instead subclass. */ public class HTTPService { public enum Key: String { case BaseURL = "BaseURL" case Resources = "Resources" case Name = "Name" case URITemplate = "URITemplate" case Method = "Method" } /** - Create: Always create a new `HTTPCycle`. - Reuse: If there is a `HTTPCycle` with the specified identifier, the `HTTPCycle` will be reused. - Replace: If there is a `HTTPCycle` with the specified identifier, the `HTTPCycle` will cancelled. A new one will be created and replaces the old one. */ public enum CycleForResourceOption { case Create case Reuse case Replace } /// The String represents the beginning common part of the endpoint URLs. private var _baseURLString: String! public var baseURLString: String { get { if (_baseURLString != nil) { return _baseURLString } if let str = self.profile![Key.BaseURL.rawValue] as? String { return str } return "" } set { self._baseURLString = newValue } } /// The dictionary describes the resources of a service. public var profile: [String: AnyObject]! public var session: HTTPSession! /// MUST be overridden public class func serviceName() -> String { // TODO: Find a way to obtain class name assert(false) return "Service" } public class func filenameOfDefaultProfile() -> String { let serviceName = self.serviceName() let filename = serviceName + ".plist" return filename } /// Override this method to return a custom `HTTPSession` public class func defaultSession() -> HTTPSession { return HTTPSession(configuration: nil, delegateQueue: nil, workerQueue: nil) } /// Override this method to customize the newly created `HTTPCycle`. public func cycleDidCreateWithResourceName(cycle: HTTPCycle, name: String) { } /// Find and read the service profile in the bundle with the specified filename. public class func profileForFilename(filename: String) throws -> [String: AnyObject] { let bundle = NSBundle(forClass: self) guard let URL = bundle.URLForResource(filename, withExtension: nil) else { throw Error.FileNotFound } let data = try NSData(contentsOfURL: URL, options: []) return try self.profileForData(data) } public class func profileForData(data: NSData) throws -> [String: AnyObject] { let d = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) guard let profile = d as? [String: AnyObject] else { throw Error.TypeNotMatch } return profile } public class func URLStringByJoiningComponents(part1: String, part2: String) -> String { if part1.isEmpty { return part2 } if part2.isEmpty { return part1 } var p1 = part1 var p2 = part2 if !part1.isEmpty && part1.hasSuffix("/") { p1 = part1[part1.startIndex ..< part1.endIndex.advancedBy(-1)] } if !part2.isEmpty && part2.hasPrefix("/") { p2 = part2[part2.startIndex.advancedBy(1) ..< part2.endIndex] } let result = p1 + "/" + p2 return result } /** Initialize a `HTTPService` object. - Parameter profile: A dictionary for profile. If nil, the default bundled file will be used to create the dictionary. */ public init?(profile: [String: AnyObject]? = nil) { self.session = self.dynamicType.defaultSession() if profile != nil { self.profile = profile! } else { do { try self.updateProfileFromLocalFile() } catch { NSLog("\(error)") return nil } } } public func updateProfileFromLocalFile(URL: NSURL? = nil) throws { if URL == nil { let filename = self.dynamicType.filenameOfDefaultProfile() self.profile = try self.dynamicType.profileForFilename(filename) return } let data = try NSData(contentsOfURL: URL!, options: []) self.profile = try self.dynamicType.profileForData(data) } /** Check if specified profile is valid. - Parameter profile: A dictionary as profile. - Returns: true if valid, or false if an error occurs. */ public func verifyProfile(profile: [String: AnyObject]) -> Bool { var names: Set<String> = [] guard let value: AnyObject = profile[HTTPService.Key.Resources.rawValue] else { NSLog("Warning: no resources found in Service profile!") return false } guard let resources = value as? [[String: String]] else { NSLog("Error: Malformed Resources in Service profile (type does not match)!") return false } for (index, resource) in resources.enumerate() { guard let name = resource[HTTPService.Key.Name.rawValue] else { NSLog("Error: Malformed Resources (name not found) in Service profile (resource index: \(index))!") return false } if names.contains(name) { NSLog("Error: Malformed Resources (duplicate name \(name)) in Service profile (resource index: \(index))!") return false } if resource[HTTPService.Key.URITemplate.rawValue] == nil { NSLog("Error: Malformed Resources (URL Template not found) in Service profile (resource index: \(index))!") return false } names.insert(name) } return true } public func resourceProfileForName(name: String) -> [String: String]? { guard let value: AnyObject = self.profile![HTTPService.Key.Resources.rawValue] else { return nil } guard let resources = value as? [[String: String]] else { return nil } for resource in resources { if let n = resource[HTTPService.Key.Name.rawValue] { if n == name { return resource } } } return nil } public func cycleForIdentifer(identifier: String) -> HTTPCycle? { return self.session.cycleForIdentifer(identifier) } /** Create a `HTTPCycle` based on the specified resource profile and parameters. - Parameter name: The name of the resource, MUST presents in the profile. The name is case sensitive. - Parameter identifer: If presents, the identifer will be used to locate an existing `HTTPCycle`. REQUIRED if option is `Reuse` or `Replace`. - Parameter option: Determines the HTTPCycle creation logic. - Parameter URIValues: The object to provide values for the URI Template expanding. - Parameter requestObject: The property `object` of the `HTTPRequest` for the `HTTPCycle`. - Parameter solicited: The same property of `HTTPCycle`. - Returns: A new or existing `HTTPCycle`. */ public func cycleForResourceWithIdentifer(name: String, identifier: String? = nil, option: CycleForResourceOption = .Create, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false) throws -> HTTPCycle { var cycle: HTTPCycle! switch option { case .Create: break case .Reuse: assert(identifier != nil) cycle = self.cycleForIdentifer(identifier!) case .Replace: assert(identifier != nil) cycle = self.cycleForIdentifer(identifier!) cycle.cancel(true) cycle = nil } if cycle != nil { return cycle } if let resourceProfile = self.resourceProfileForName(name) { let URITemplate = resourceProfile[HTTPService.Key.URITemplate.rawValue] let part2 = ExpandURITemplate(URITemplate!, values: URIValues) let URLString = HTTPService.URLStringByJoiningComponents(self.baseURLString, part2: part2) guard let URL = NSURL(string: URLString) else { throw Error.InvalidURL } var method = resourceProfile[HTTPService.Key.Method.rawValue] if method == nil { method = "GET" } cycle = HTTPCycle(requestURL: URL, taskType: .Data, session: self.session, requestMethod: method!, requestObject: requestObject) cycle.solicited = solicited if identifier != nil { cycle.identifier = identifier! } self.cycleDidCreateWithResourceName(cycle, name: name) } else { assert(false, "Endpoind \(name) not found in profile!") } return cycle } /** Create a new `HTTPCycle` object based on the specified resource profile and parameters. - Parameter name: The name of the resouce, MUST presents in the profile. The name is case sensitive. - Parameter URIValues: The object to provide values for the URI Template expanding. - Parameter requestObject: The property `object` of the `HTTPRequest` for the Cycle. - Parameter solicited: The same property of `HTTPCycle`. - Returns: A new Cycle. */ public func cycleForResource(name: String, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false) throws -> HTTPCycle { let cycle = try self.cycleForResourceWithIdentifer(name, URIValues: URIValues, requestObject: requestObject, solicited: solicited) return cycle } /** Create a `HTTPCycle` object based on the specified resource profile and parameters, and start the `HTTPCycle`. See `cycleForResourceWithIdentifer` for details. */ public func requestResourceWithIdentifer(name: String, identifier: String, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { let cycle = try self.cycleForResourceWithIdentifer(name, identifier: identifier, URIValues: URIValues, requestObject: requestObject, solicited: solicited) cycle.start(completionHandler) return cycle } /** Create a `HTTPCycle` object based on the specified resource profile and parameters, and start the `HTTPCycle`. See `cycleForResource` for details. */ public func requestResource(name: String, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle { let cycle = try self.cycleForResourceWithIdentifer(name, identifier: nil, URIValues: URIValues, requestObject: requestObject, solicited: solicited) cycle.start(completionHandler) return cycle } }
c6a37d3b56a8ab94dfd1aa5c976ab7e1
37.345679
246
0.634981
false
false
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Main/Apply/Controller/JobDailyCreatViewController.swift
mit
1
// // JobDailyCreatViewController.swift // YCOA // // Created by Jerry on 2016/12/22. // Copyright © 2016年 com.baochunsteel. All rights reserved. // // 工作日报 import UIKit import TZImagePickerController import MBProgressHUD import Alamofire class JobDailyCreatViewController: UIViewController, TZImagePickerControllerDelegate { private var fileInfo: (id_: String, name: String)? @IBOutlet weak var selectDateButton: UIButton! //日报日期(-1 昨天、0 今天、-2 明天) @IBOutlet weak var contentTextView: UITextView! //内容 @IBOutlet weak var nextPlanTextField: UITextField! //下次计划 @IBOutlet weak var relatedFileButton: UIButton! //相关文件 @IBOutlet weak var submitButton: UIButton! //提交 @IBOutlet weak var backGroundView: UIScrollView! //背景View //Private private var date = "0" override func viewDidLoad() { super.viewDidLoad() self.title = "工作日报" self.UIConfigure() self.ActionConfigure() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Action //绑定控件Action func ActionConfigure() { //日报日期 self.selectDateButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in self.view.endEditing(true) let dates = ["今天", "昨天", "前天"] UIPickerView.showDidSelectView(SingleColumnDataSource: dates, onView: self.navigationController!.view, selectedTap: { (index) in //不懂看接口文档去 if(index == 0){self.date = "0"}else if(index == 1){self.date = "-1"}else{self.date = "-2"} self.selectDateButton.setTitle(dates[index], for: .normal) }) } //相关文件 self.relatedFileButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in self.view.endEditing(true) // self.navigationController!.view.jrShow(withTitle: "您没有上传文件的权限") self.updateFile() } //提交 self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in self.view.endEditing(true) self.didSubmit() } //backGroundView self.backGroundView.isUserInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer { (sender) in self.view.endEditing(true) } self.backGroundView.addGestureRecognizer(tapGestureRecognizer) } //提交 private func didSubmit() { let dts_ = self.date let content_ : String = self.contentTextView.text guard content_.utf8.count > 0 else { self.navigationController?.view.jrShow(withTitle: "请填写工作内容!") return } var parameters : [String : Any] = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!, "dts" : dts_, "content" : content_] //可选 let plan_ = self.nextPlanTextField.text if(plan_ != nil && plan_!.utf8.count > 0){ parameters["plan"] = plan_! } //相关文件 if(self.fileInfo != nil){ parameters["fileid"] = self.fileInfo!.id_ } //Get YCOA_NetWork.get(url: "/index.php?d=taskrun&m=flow_daily|appapi&a=saveweb&ajaxbool=true", parameters: parameters) { (error, returnValue) in if(error != nil){ self.navigationController?.view.jrShow(withTitle: error!.domain) return } self.navigationController?.view.jrShow(withTitle: "提交成功!") } } //上传文件 private func updateFile() { let imagePicker = TZImagePickerController(maxImagesCount: 1, delegate: self) imagePicker?.allowPickingVideo = false self.present(imagePicker!, animated: true, completion: nil) } func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) { let hud = MBProgressHUD.showAdded(to: (self.navigationController?.view)!, animated: true) hud.mode = .indeterminate hud.label.text = "上传中..." let imageName = NSDate.nowTimeToTimeStamp() let imageData: Data = UIImagePNGRepresentation(photos.first!)! let urlPar = "/index.php?d=taskrun&m=upload|appapi&a=upfile&ajaxbool=true&adminid=\(UserCenter.shareInstance().uid!)&timekey=\(NSDate.nowTimeToTimeStamp())&token=\(UserCenter.shareInstance().token!)&cfrom=appiphone&appapikey=\(UserCenter.shareInstance().apikey!)" guard let url_ = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending(urlPar)) else { hud.hide(animated: true) self.navigationController?.view.jrShow(withTitle: "请求错误") return } Alamofire.upload( multipartFormData: { (multipartFormData) in multipartFormData.append(imageData, withName: "file", fileName: "\(imageName).png", mimeType: "image/png") }, to: url_) { (encodingResult) in switch encodingResult { case .success(request: let upload, streamingFromDisk: _, streamFileURL: _): upload.responseJSON(completionHandler: { (response) in guard response.result.isSuccess else{ hud.hide(animated: true) self.navigationController?.view.jrShow(withTitle: "网络错误") return } guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{ hud.hide(animated: true) self.navigationController?.view.jrShow(withTitle: "服务器出错") return } guard returnValue.value(forKey: "code") as! Int == 200 else{ let msg = "\(returnValue.value(forKey: "msg")!)" hud.hide(animated: true) self.navigationController?.view.jrShow(withTitle: msg) return } //获取上传信息 hud.hide(animated: false) NSLog("上传成功") self.getFileInfo() }) case .failure(let encodingError): NSLog("Failure: \(encodingError)") } } } private func getFileInfo() { let hud = MBProgressHUD.showAdded(to: (self.navigationController?.view)!, animated: true) hud.mode = .indeterminate hud.label.text = "请等待..." let parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!] YCOA_NetWork.get(url: "/index.php?d=taskrun&m=upload|appapi&a=getfile&ajaxbool=true", parameters: parameters) { (error, returnValue) in guard error == nil else{ hud.hide(animated: false) self.view.jrShow(withTitle: error!.domain) return } guard let dataDic = (returnValue as! NSDictionary).value(forKey: "data") as? NSDictionary else{ hud.hide(animated: false) self.view.jrShow(withTitle: "暂无数据") return } //同步数据 self.fileInfo = ("\(dataDic["id"] as! Int)", dataDic["filename"] as! String) hud.hide(animated: true) self.relatedFileButton.setTitle("相关文件(\(self.fileInfo!.name))", for: .normal) } } //MARK: - UI //配置控件UI func UIConfigure() { self.makeTextFieldStyle(sender: self.selectDateButton) self.makeTextFieldStyle(sender: self.contentTextView) self.makeTextFieldStyle(sender: self.relatedFileButton) self.makeTextFieldStyle(sender: self.submitButton) self.selectDateButton.setTitle("今天", for: .normal) } ///设置控件成为TextField一样的样式 func makeTextFieldStyle(sender: UIView) { sender.layer.masksToBounds = true sender.layer.cornerRadius = 10/2 sender.layer.borderWidth = 0.3 sender.layer.borderColor = UIColor.lightGray.cgColor } /* // 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. } */ }
0741bf61899f8dae1580d2585d3347e6
37.42915
271
0.558892
false
false
false
false
CoderST/DYZB
refs/heads/master
DYZB/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQTextView/IQTextView.swift
apache-2.0
5
// // IQTextView.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 /** @abstract UITextView with placeholder support */ open class IQTextView : UITextView { required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self) } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self) } override open func awakeFromNib() { super.awakeFromNib() NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name: NSNotification.Name.UITextViewTextDidChange, object: self) } deinit { NotificationCenter.default.removeObserver(self) } fileprivate var placeholderLabel: UILabel? /** @abstract To set textView's placeholder text. Default is ni. */ @IBInspectable open var placeholder : String? { get { return placeholderLabel?.text } set { if placeholderLabel == nil { placeholderLabel = UILabel() if let unwrappedPlaceholderLabel = placeholderLabel { unwrappedPlaceholderLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] unwrappedPlaceholderLabel.lineBreakMode = .byWordWrapping unwrappedPlaceholderLabel.numberOfLines = 0 unwrappedPlaceholderLabel.font = self.font unwrappedPlaceholderLabel.backgroundColor = UIColor.clear unwrappedPlaceholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0) unwrappedPlaceholderLabel.alpha = 0 addSubview(unwrappedPlaceholderLabel) } } placeholderLabel?.text = newValue refreshPlaceholder() } } open override func layoutSubviews() { super.layoutSubviews() if let unwrappedPlaceholderLabel = placeholderLabel { unwrappedPlaceholderLabel.sizeToFit() unwrappedPlaceholderLabel.frame = CGRect(x: 4, y: 8, width: self.frame.width-16, height: unwrappedPlaceholderLabel.frame.height) } } open func refreshPlaceholder() { if text.characters.count != 0 { placeholderLabel?.alpha = 0 } else { placeholderLabel?.alpha = 1 } } override open var text: String! { didSet { refreshPlaceholder() } } override open var font : UIFont? { didSet { if let unwrappedFont = font { placeholderLabel?.font = unwrappedFont } else { placeholderLabel?.font = UIFont.systemFont(ofSize: 12) } } } override open var delegate : UITextViewDelegate? { get { refreshPlaceholder() return super.delegate } set { super.delegate = newValue } } }
f4b57885413a6543fb0190053512f417
33.604478
163
0.629502
false
false
false
false
NeoGolightly/CartographyKit
refs/heads/master
CartographyKit/Edges.swift
mit
1
// // Edges.swift // CartographyKit iOS // // Created by Michael Helmbrecht on 07/01/2018. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif import Cartography //////////////////////////////////////////////////////////////////////////////////////////////// //Edges //////////////////////////////////////////////////////////////////////////////////////////////// private protocol BasicEdges{ static func edges(_ view: View) -> [NSLayoutConstraint?] #if os(iOS) static func edgesWithinMargins(_ view: View) -> [NSLayoutConstraint?] #endif } //////////////////////////////////////////////////////////////////////////////////////////////// //BasicEdges Modifier //////////////////////////////////////////////////////////////////////////////////////////////// private protocol EdgesInsetsPlus{ static func edges(_ view: View, plus: CGFloat) -> [NSLayoutConstraint?] } private protocol EdgesInsetsMinus{ static func edges(_ view: View, minus: CGFloat) -> [NSLayoutConstraint?] } private protocol EdgesInsets{ static func edgesInset(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] static func edgesInset(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] static func edgesInset(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] static func edgesInset(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] static func edgesInset(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] #if os(iOS) static func edgesWithinMargins(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] static func edgesWithinMargins(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] static func edgesWithinMargins(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] static func edges(_ view: View, insets: UIEdgeInsets)-> [NSLayoutConstraint?] #endif } extension CartographyKit: BasicEdges{ @discardableResult public static func edges(_ view: View) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges return } return c } @discardableResult public static func edgesWithinMargins(_ view: View) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins return } return c } } extension CartographyKit: EdgesInsetsPlus{ @discardableResult public static func edges(_ view: View, plus: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(by: plus) return } return c } } extension CartographyKit: EdgesInsetsMinus{ @discardableResult public static func edges(_ view: View, minus: CGFloat) -> [NSLayoutConstraint?]{ var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(by: -minus) return } return c } } extension CartographyKit: EdgesInsets{ @discardableResult public static func edgesInset(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(by: all) return } return c } @discardableResult public static func edgesInset(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(horizontally: horizontal) return } return c } @discardableResult public static func edgesInset(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(vertically: vertical) return } return c } @discardableResult public static func edgesInset(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(horizontally: horizontal, vertically: vertical) return } return c } @discardableResult public static func edgesInset(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edges == view.superview!.edges.inseted(top: top, leading: leading, bottom: bottom, trailing: trailing) return } return c } @discardableResult public static func edgesWithinMargins(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(by: all) return } return c } @discardableResult public static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(horizontally: horizontal) return } return c } @discardableResult public static func edgesWithinMargins(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(vertically: vertical) return } return c } @discardableResult public static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(horizontally: horizontal, vertically: vertical) return } return c } @discardableResult public static func edgesWithinMargins(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(top: top, leading: leading, bottom: bottom, trailing: trailing) return } return c } @discardableResult public static func edges(_ view: View, insets: UIEdgeInsets) -> [NSLayoutConstraint?] { var c: [NSLayoutConstraint?] = [] constrain(view){ view in c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(by: insets) return } return c } }
aee0d7f294871ec9cdd0d585ea3c51c8
33.516588
148
0.653714
false
false
false
false
UIKonf/uikonf-app
refs/heads/master
UIKonfApp/UIKonfApp/EntityLookUp.swift
mit
1
// // EntityLookUp.swift // UIKonfApp // // Created by Maxim Zaks on 11.04.15. // Copyright (c) 2015 UIKonf. All rights reserved. // import Foundation import Entitas private var lookups : [Lookup] = [] class Lookup { unowned let context : Context private init(context : Context){ self.context = context } static func get(context : Context) -> Lookup { for lookup in lookups { if lookup.context === context { return lookup } } let lookup = Lookup(context: context) lookups.append(lookup) return lookup } lazy var personLookup: SimpleLookup<String> = SimpleLookup(group:self.context.entityGroup(Matcher.All(NameComponent, PhotoComponent))) { (entity, removedComponent) -> String in if let c = removedComponent as? NameComponent { return c.name } return entity.get(NameComponent)!.name } lazy var talksLookupByTimeSlotId : SimpleLookup<String> = SimpleLookup(group: self.context.entityGroup(Matcher.All(SpeakerNameComponent, TitleComponent, TimeSlotIdComponent, TimeSlotIndexComponent))) { (entity, removedComponent) -> String in if let c : TimeSlotIdComponent = removedComponent as? TimeSlotIdComponent { return c.id } return entity.get(TimeSlotIdComponent)!.id } lazy var locationLookupByName : SimpleLookup<String> = SimpleLookup<String>(group: self.context.entityGroup(Matcher.All(NameComponent, AddressComponent))) { (entity, removedComponent) -> String in if let component = removedComponent as? NameComponent { return component.name } return entity.get(NameComponent)!.name } }
0073738ee97700444a72c616ef1e3ff9
31.236364
245
0.649549
false
false
false
false
aipeople/PokeIV
refs/heads/master
Pods/ProtocolBuffers-Swift/Source/Field.swift
gpl-3.0
1
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public func ==(lhs:Field, rhs:Field) -> Bool { var check = (lhs.variantArray == rhs.variantArray) check = check && (lhs.fixed32Array == rhs.fixed32Array) check = check && (lhs.fixed64Array == rhs.fixed64Array) check = check && (lhs.groupArray == rhs.groupArray) check = check && (lhs.lengthDelimited == rhs.lengthDelimited) return check } //public func ==(lhs:Array<Array<UInt8>>, rhs:Array<Array<UInt8>>) -> Bool //{ // if lhs.count == rhs.count // { // for (var i = 0; i < lhs.count; i++) // { // var lbytes = lhs[i] // var rbytes = rhs[i] // // if lbytes.count == rbytes.count // { // if lbytes == rbytes // { // continue // } // else // { // return false // } // } // else // { // return false // } // } // return true // } // return false //} // // // //public func ==(lhs:Array<UInt8>, rhs:Array<UInt8>) -> Bool //{ // if lhs.count == rhs.count // { // for (var i = 0; i < lhs.count; i++) // { // var lbytes = lhs[i] // var rbytes = rhs[i] // if lbytes != rbytes // { // return false // } // } // return true // } // return false //} //public protocol FieldOverload //{ // func +=(inout left:Field, right:Int64) // func +=(inout left:Field, right:Int32) // func +=(inout left:Field, right:UInt64) // func +=(inout left:Field, right:UInt32) //} public func +=(left:Field, right:Int64) { left.variantArray += [right] } public func +=(left:Field, right:Int32) { var result:Int64 = 0 result = WireFormat.convertTypes(convertValue: right, defaultValue:result) left.variantArray += [result] } public func +=(left:Field, right:UInt32) { left.fixed32Array += [UInt32(right)] } public func +=(left:Field, right:UInt64) { left.fixed64Array += [UInt64(right)] } final public class Field:Equatable,Hashable { public var variantArray:Array<Int64> public var fixed32Array:Array<UInt32> public var fixed64Array:Array<UInt64> public var lengthDelimited:Array<NSData> public var groupArray:Array<UnknownFieldSet> public init() { variantArray = [Int64](count: 0, repeatedValue: 0) fixed32Array = [UInt32](count: 0, repeatedValue: 0) fixed64Array = [UInt64](count: 0, repeatedValue: 0) lengthDelimited = Array<NSData>() groupArray = Array<UnknownFieldSet>() } public func getSerializedSize(fieldNumber:Int32) -> Int32 { var result:Int32 = 0 for value in variantArray { result += value.computeInt64Size(fieldNumber) } for value in fixed32Array { result += value.computeFixed32Size(fieldNumber) } for value in fixed64Array { result += value.computeFixed64Size(fieldNumber) } for value in lengthDelimited { result += value.computeDataSize(fieldNumber) } for value in groupArray { result += value.computeUnknownGroupSize(fieldNumber) } return result } public func getSerializedSizeAsMessageSetExtension(fieldNumber:Int32) -> Int32 { var result:Int32 = 0 for value in lengthDelimited { result += value.computeRawMessageSetExtensionSize(fieldNumber) } return result } public func writeTo(fieldNumber:Int32, output:CodedOutputStream) throws { for value in variantArray { try output.writeInt64(fieldNumber, value:value) } for value in fixed32Array { try output.writeFixed32(fieldNumber, value: value) } for value in fixed64Array { try output.writeFixed64(fieldNumber, value:value) } for value in lengthDelimited { try output.writeData(fieldNumber, value: value) } for value in groupArray { try output.writeUnknownGroup(fieldNumber, value:value) } } public func getDescription(fieldNumber:Int32, indent:String) -> String { var outputString = "" for value in variantArray { outputString += "\(indent)\(fieldNumber): \(value)\n" } for value in fixed32Array { outputString += "\(indent)\(fieldNumber): \(value)\n" } for value in fixed64Array { outputString += "\(indent)\(fieldNumber): \(value)\n" } for value in lengthDelimited { outputString += "\(indent)\(fieldNumber): \(value)\n" } for value in groupArray { outputString += "\(indent)\(fieldNumber)[\n" outputString += value.getDescription(indent) outputString += "\(indent)]" } return outputString } public func writeAsMessageSetExtensionTo(fieldNumber:Int32, output:CodedOutputStream) throws { for value in lengthDelimited { try output.writeRawMessageSetExtension(fieldNumber, value: value) } } public var hashValue:Int { get { var hashCode = 0 for value in variantArray { hashCode = (hashCode &* 31) &+ value.hashValue } for value in fixed32Array { hashCode = (hashCode &* 31) &+ value.hashValue } for value in fixed64Array { hashCode = (hashCode &* 31) &+ value.hashValue } for value in lengthDelimited { hashCode = (hashCode &* 31) &+ value.hashValue } for value in groupArray { hashCode = (hashCode &* 31) &+ value.hashValue } return hashCode } } } public extension Field { public func clear() { variantArray.removeAll(keepCapacity: false) fixed32Array.removeAll(keepCapacity: false) fixed64Array.removeAll(keepCapacity: false) groupArray.removeAll(keepCapacity: false) lengthDelimited.removeAll(keepCapacity: false) } public func mergeFromField(other:Field) -> Field { if (other.variantArray.count > 0) { variantArray += other.variantArray } if (other.fixed32Array.count > 0) { fixed32Array += other.fixed32Array } if (other.fixed64Array.count > 0) { fixed64Array += other.fixed64Array } if (other.lengthDelimited.count > 0) { lengthDelimited += other.lengthDelimited } if (other.groupArray.count > 0) { groupArray += other.groupArray } return self } }
6ec27f0ec0df0b792a19375a49d983a7
25.006536
96
0.544929
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Utility/UIKit+Extensions.swift
lgpl-2.1
2
// // UIKit+Extensions.swift // Neocom // // Created by Artem Shimanski on 11/26/19. // Copyright © 2019 Artem Shimanski. All rights reserved. // import UIKit import SafariServices extension UIApplication { func endEditing(_ force: Bool) { self.windows.first{$0.isKeyWindow}?.endEditing(force) } } extension Notification.Name { static let didFinishJob = Notification.Name(rawValue: "com.shimanski.neocom.didFinishJob") static let didFinishPaymentTransaction = Notification.Name(rawValue: "com.shimanski.neocom.didFinishPaymentTransaction") static let didFinishStartup = Notification.Name(rawValue: "com.shimanski.neocom.didFinishStartup") } extension NSAttributedString { var attachments: [NSRange: NSTextAttachment] { var result = [NSRange: NSTextAttachment]() enumerateAttribute(.attachment, in: NSRange(location: 0, length: length), options: []) { value, range, _ in guard let attachment = value as? NSTextAttachment else {return} result[range] = attachment } return result } } extension UIBezierPath { convenience init(points: [CGPoint]) { self.init() guard !points.isEmpty else {return} move(to: points[0]) points.dropFirst().forEach { addLine(to: $0) } } } extension UIViewController { var topMostPresentedViewController: UIViewController { return presentedViewController?.topMostPresentedViewController ?? self } } extension UIAlertController { convenience init(title: String? = NSLocalizedString("Error", comment: ""), error: Error, handler: ((UIAlertAction) -> Void)? = nil) { self.init(title: title, message: error.localizedDescription, preferredStyle: .alert) self.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: handler)) } } extension UIApplication { func openSafari(with url: URL) { let safari = SFSafariViewController(url: url) rootViewController?.topMostPresentedViewController.present(safari, animated: true) } }
b5e114f2df7e7934769f5761abbdc72b
32.111111
137
0.698945
false
false
false
false
Antondomashnev/FBSnapshotsViewer
refs/heads/master
FBSnapshotsViewer/Event Listeners/RecursiveFolderEventsListener.swift
mit
1
// // RecursiveFolderEventsListener.swift // FBSnapshotsViewer // // Created by Anton Domashnev on 11/02/2017. // Copyright © 2017 Anton Domashnev. All rights reserved. // import Foundation /// `NonRecursiveFolderEventsListener` is responsible to watch folder /// changes (new file, updated file, deleted file), watches only the given folder recursively. /// It uses the 3rd party dependency under the hood. final class RecursiveFolderEventsListener: FolderEventsListener { /// Internal 3rd party watcher fileprivate let watcher: FileWatcher /// Applied filters for watched events fileprivate let filter: FolderEventFilter? /// Underlying listeners for subfolders fileprivate var listeners: [String: FolderEventsListener] = [:] /// Currently watching folder path let folderPath: String /// Handler for `FolderEventsListener` output weak var output: FolderEventsListenerOutput? /// Internal accessor for private listeners property var dependentListeners: [String: FolderEventsListener] { let dependentListeners = listeners return dependentListeners } init(folderPath: String, filter: FolderEventFilter? = nil, fileWatcherFactory: FileWatcherFactory = FileWatcherFactory()) { self.filter = filter self.folderPath = folderPath self.watcher = fileWatcherFactory.fileWatcher(for: [folderPath]) } // MARK: - Interface func startListening() { try? watcher.start { [weak self] event in let folderEvent = FolderEvent(eventFlag: event.flag, at: event.path) self?.process(received: folderEvent) if let existedFilter = self?.filter, !existedFilter.apply(to: folderEvent) { return } if let strongSelf = self { strongSelf.output?.folderEventsListener(strongSelf, didReceive: folderEvent) } } } func stopListening() { watcher.stop() } // MARK: - Helpers private func process(received event: FolderEvent) { switch event { case .created(let path, let object) where object == FolderEventObject.folder: let listener = RecursiveFolderEventsListener(folderPath: path, filter: filter) listener.output = output listener.startListening() listeners[path] = listener case .deleted(let path, let object) where object == FolderEventObject.folder: listeners.removeValue(forKey: path) default: break } } }
213d673750e739dc3827cd7eabe2ee3b
33.066667
127
0.670841
false
false
false
false
SonnyBrooks/ProjectEulerSwift
refs/heads/master
ProjectEulerSwift/Problem21.swift
mit
1
// // Problem21.swift // ProjectEulerSwift // https://projecteuler.net/problem=21 // // Created by Andrew Budziszek on 12/22/16. // Copyright © 2016 Andrew Budziszek. All rights reserved. // //Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). //If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. // //For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. // //Evaluate the sum of all the amicable numbers under 10000. // import Foundation class Problem21 { var sumOfAmicableNumbers = 0 var alreadyObserved : [Int] = [] func AmicableNumbers() -> Int{ var count = 2 while count <= 10000 { let a = sumOfDivisors(count) let b = sumOfDivisors(a) if b == count && a != b && !alreadyObserved.contains(count) { alreadyObserved.append(a) alreadyObserved.append(b) sumOfAmicableNumbers += a + b } count += 1 } return sumOfAmicableNumbers } func sumOfDivisors(_ n: Int) -> Int { var sum = 0 if n / 2 > 0 { for i in 1...n / 2 { if n % i == 0 { sum += i } } } else { return 0 } return sum } }
e70a476afed3f919225684bd713d63ab
26.534483
182
0.522229
false
false
false
false