repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hulinSun/MyRx
MyRx/MyRx/Classes/Core/Service/HttpService.swift
1
1589
// // HttpService.swift // MyRx // // Created by Hony on 2017/1/11. // Copyright © 2017年 Hony. All rights reserved. // import UIKit import Moya import RxCocoa import RxSwift import HandyJSON /// 对rxmoya 的一层分装。不暴露,直接回调数据,降低一些耦合性。所有的moya 请求数据都在这里 class HttpService: NSObject { private static let bag = DisposeBag() class func getHomeMomentSad(callback: @escaping (([Topic?]) -> Void)){ let provider = RxMoyaProvider<MatchService>(stubClosure: MoyaProvider.immediatelyStub) provider .request(.momentsad) .filterSuccessfulStatusCodes() .observeOn(.main) .subscribe { (e) in guard let response = e.element else{ return } if let m = response.mapArray(Topic.self, designatedPath: "data"){ callback(m) } }.addDisposableTo(bag) } class func getHomeMusic(callback: @escaping (([Music]) -> Void)){ let provider = RxMoyaProvider<MatchService>(stubClosure: MoyaProvider.immediatelyStub) provider .request(.chaifei) .filterSuccessfulStatusCodes() .observeOn(.main) .subscribe { (e) in guard let response = e.element else{ return } if let m = response.mapArray(Music.self, designatedPath: "data"){ let s = m.flatMap{$0}.filter{$0.type == "music"} callback(s) } }.addDisposableTo(bag) } }
mit
c6d0c91734c2ecff9985aba8d38e4d65
30.541667
94
0.581242
4.375723
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGAP/GAPRandomTargetAddress.swift
1
2356
// // GAPRandomTargetAddress.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// The Random Target Address data type defines the address of one or more intended recipients of an advertisement when one or more devices were bonded using a random address. /// This data type is intended to be used to avoid a situation where a bonded device unnecessarily responds to an advertisement intended for another bonded device. /// /// Size: Multiples of 6 octets /// The format of each 6 octet address is the same as the Random Device Address defined in Vol. 6, Part B, Section 1.3. /// The Random Target Address value shall be the enumerated value as defined by Bluetooth Assigned Numbers. @frozen public struct GAPRandomTargetAddress: GAPData, Equatable { public typealias ByteValue = (UInt8, UInt8, UInt8) public static let dataType: GAPDataType = .randomTargetAddress public let addresses: [BluetoothAddress] public init(addresses: [BluetoothAddress]) { self.addresses = addresses } } public extension GAPRandomTargetAddress { init?(data: Data) { guard data.count % BluetoothAddress.length == 0 else { return nil } let count = data.count / BluetoothAddress.length let addresses: [BluetoothAddress] = (0 ..< count).map { let index = $0 * BluetoothAddress.length return BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[index], data[index+1], data[index+2], data[index+3], data[index+4], data[index+5]))) } self.init(addresses: addresses) } var dataLength: Int { return addresses.count * BluetoothAddress.length } func append(to data: inout Data) { addresses.forEach { data += $0.littleEndian } } } // MARK: - CustomStringConvertible extension GAPRandomTargetAddress: CustomStringConvertible { public var description: String { return addresses.description } } // MARK: - ExpressibleByArrayLiteral extension GAPRandomTargetAddress: ExpressibleByArrayLiteral { public init(arrayLiteral elements: BluetoothAddress...) { self.init(addresses: elements) } }
mit
5b3ad0e2402f9451fe7cfa19e9c009d3
29.192308
175
0.671338
4.806122
false
false
false
false
exbeim/Tippytap
Tippytap/ViewController.swift
1
2621
// // ViewController.swift // Tippytap // // Created by Pallav Sharda on 3/7/16. // Copyright © 2016 Avlokan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var BillAmtField: UITextField! @IBOutlet weak var ServiceSlider: UISlider! @IBOutlet weak var TipLabel: UILabel! @IBOutlet weak var TotalLabel: UILabel! @IBOutlet weak var TipControl: UISegmentedControl! @IBOutlet weak var TipSlider: UISlider! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. BillAmtField.text = "$0.00" TipLabel.text = "$0.00" TotalLabel.text = "$0.00" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func OnEditingChange(sender: AnyObject) { var BillAmount: Double? var Tip: Double? var Total: Double? var TipPercentages = [0.10, 0.15, 0.20, 0.25] let TipPercentage = TipPercentages[TipControl.selectedSegmentIndex] BillAmount = Double(BillAmtField.text!) //Checking if the value was nil, and reseting to zero if yes if BillAmount == nil {BillAmount = 0} Tip = BillAmount! * TipPercentage TipLabel.text = "$\(Tip!)" TipLabel.text = String(format: "$%.2f", Tip!) //formatting to two decimal Total = BillAmount! + Tip! TotalLabel.text = "$\(Total!)" TotalLabel.text = String(format: "$%.2f", Total!) //formatting to two decimal } // Hiding keyboard if clicking elsewhere @IBAction func OnTap(sender: AnyObject) { view.endEditing(true) } @IBAction func OnSliderChange(sender: AnyObject) { var BillAmount: Double? var Tip: Double? var Total: Double? BillAmount = Double(BillAmtField.text!) //Checking if the value was nil, and reseting to zero if yes if BillAmount == nil {BillAmount = 0} let TipSlide = Double(TipSlider.value/100) Tip = BillAmount! * TipSlide TipLabel.text = "$\(Tip!)" TipLabel.text = String(format: "$%.2f", Tip!) //formatting to two decimal Total = BillAmount! + Tip! TotalLabel.text = "$\(Total!)" TotalLabel.text = String(format: "$%.2f", Total!) //formatting to two decimal } }
gpl-3.0
8d422f0f9abe36e27ecf6ad8e9494558
25.464646
85
0.590076
4.418212
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
Liferay-Screens/Themes/Default/DDL/FormScreenlet/DDLFieldDocumentlibraryTableCell_default.swift
1
4873
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ import UIKit public class DDLFieldDocumentlibraryTableCell_default: DDLBaseFieldTextboxTableCell_default { //MARK: Outlets @IBOutlet internal var chooseButton: UIButton? { didSet { setButtonDefaultStyle(chooseButton) } } @IBOutlet internal var progress: MDRadialProgressView? //MARK: Constants private let presenterViewController = DDLFieldDocumentlibraryPresenterViewController_default() private let completedColor = [ DDLFieldDocument.UploadStatus.Uploading(0,0) : DefaultThemeBasicBlue, DDLFieldDocument.UploadStatus.Uploaded([:]) : UIColor(red:90/255.0, green:212/255.0, blue:39/255.0, alpha:1), DDLFieldDocument.UploadStatus.Failed(nil) : UIColor(red:1, green:0, blue:0, alpha:1) ] private let incompletedColor = [ DDLFieldDocument.UploadStatus.Uploading(0,0) : UIColor(red:176/255.0, green:238/255.0, blue:1.0, alpha:0.87) ] private let centerColor = [ DDLFieldDocument.UploadStatus.Uploading(0,0) : UIColor(red:240/255.0, green:1, blue:1.0, alpha:0.87), DDLFieldDocument.UploadStatus.Uploaded([:]) : UIColor(red:240/255.0, green:1, blue:1, alpha:1), DDLFieldDocument.UploadStatus.Failed(nil) : UIColor(red:1, green:220/255.0, blue:200/255.0, alpha:1) ] private let labelColor = [ DDLFieldDocument.UploadStatus.Uploading(0,0) : DefaultThemeBasicBlue, DDLFieldDocument.UploadStatus.Uploaded([:]) : UIColor(red:240/255.0, green:1, blue:1, alpha:1), DDLFieldDocument.UploadStatus.Failed(nil) : UIColor(red:1, green:220/255.0, blue:200/255.0, alpha:1) ] //MARK: Actions @IBAction private func chooseButtonAction(sender: AnyObject) { textField!.becomeFirstResponder() } //MARK: DDLBaseFieldTextboxTableCell override internal func onChangedField() { super.onChangedField() if let docField = field as? DDLFieldDocument { textField?.text = docField.currentValueAsLabel presenterViewController.selectedDocumentClosure = selectedDocumentClosure setFieldPresenter(docField) setProgress(docField) if field!.lastValidationResult != nil { onPostValidation(field!.lastValidationResult!) } } } override internal func changeDocumentUploadStatus(field: DDLFieldDocument) { let theme = progress!.theme theme.completedColor = completedColor[field.uploadStatus] theme.incompletedColor = incompletedColor[field.uploadStatus] theme.centerColor = centerColor[field.uploadStatus] theme.labelColor = labelColor[field.uploadStatus] switch field.uploadStatus { case .Uploading(let current, let max): progress!.progressTotal = max progress!.progressCounter = current if progress!.alpha == 0 { changeProgressVisilibity(show:true) } case .Failed(_): changeProgressVisilibity(show:false, delay:2.0) case .Uploaded(_): if field.lastValidationResult != nil { field.validate() } default: () } dispatch_async(dispatch_get_main_queue()) { self.progress!.setNeedsDisplay() } } //MARK: Private methods private func setProgress(field:DDLFieldDocument) { let theme = progress!.theme theme.font = UIFont(descriptor: textField!.font.fontDescriptor(), size: 30.0) theme.sliceDividerHidden = true theme.thickness = 10.0 progress!.theme = theme changeDocumentUploadStatus(field) } private func changeProgressVisilibity(#show:Bool, delay:Double = 0.0) { UIView.animateWithDuration(0.3, delay: delay, options: nil, animations: { self.progress!.alpha = show ? 1.0 : 0.0 self.chooseButton!.alpha = show ? 0.0 : 1.0 }, completion: nil) } private func setFieldPresenter(field:DDLFieldDocument) { let presenter = DTViewPresenter(view:presenterViewController.view) presenter.presenterView.backgroundColor = UIColor.whiteColor() presenter.presenterView.layer.borderColor = UIColor.lightGrayColor().CGColor presenter.presenterView.layer.borderWidth = 1.5 textField?.dt_setPresenter(presenter) } private func selectedDocumentClosure(image:UIImage?, url:NSURL?) { textField!.resignFirstResponder() if image != nil || url != nil { field!.currentValue = image ?? url textField?.text = field?.currentValueAsLabel formView?.userActionWithName( actionName: "upload-document", sender: field! as! DDLFieldDocument) } } }
gpl-3.0
c41613a16c713390b996d67708f2ae38
27.16763
93
0.734045
3.544
false
false
false
false
exyte/Macaw
Source/svg/SVGSerializer.swift
1
14853
// // SVGSerializer.swift // Macaw // // Created by Yuriy Kashnikov on 8/17/17. // Copyright © 2017 Exyte. All rights reserved. // import Foundation /// /// This class serializes Macaw Scene into an SVG String /// open class SVGSerializer { fileprivate let width: Int? fileprivate let height: Int? fileprivate let id: String? fileprivate init(width: Int?, height: Int?, id: String?) { self.width = width self.height = height self.id = id } // header and footer fileprivate let SVGDefaultHeader = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\"" fileprivate static let SVGDefaultId = "" fileprivate static let SVGUndefinedSize = -1 fileprivate let SVGFooter = "</svg>" // groups fileprivate let SVGGroupOpenTag = "<g" fileprivate let SVGGroupCloseTag = "</g>" // shapes fileprivate let SVGRectOpenTag = "<rect " fileprivate let SVGCircleOpenTag = "<circle " fileprivate let SVGEllipseOpenTag = "<ellipse " fileprivate let SVGLineOpenTag = "<line " fileprivate let SVGPolylineOpenTag = "<polyline " fileprivate let SVGPolygonOpenTag = "<polygon " fileprivate let SVGPathOpenTag = "<path " fileprivate let SVGImageOpenTag = "<image " fileprivate let SVGTextOpenTag = "<text " fileprivate let SVGGenericEndTag = ">" fileprivate let SVGGenericCloseTag = "/>" fileprivate let SVGUndefinedTag = "<UNDEFINED " fileprivate let SVGClipPathName = "clipPath" fileprivate let SVGMaskName = "mask" fileprivate let SVGEpsilon: Double = 0.00001 fileprivate let SVGDefaultOpacityValueAsAlpha = 1 * 255 fileprivate func tag(_ tag: String, _ args: [String: String]=[:], close: Bool = false) -> String { let attrs = args.sorted { a1, a2 -> Bool in a1.key < a2.key } .map { "\($0)=\"\($1)\"" }.joined(separator: " ") let closeTag = close ? " />" : "" return "\(tag) \(attrs) \(closeTag)" } fileprivate func arcToSVG(_ arc: Arc) -> String { if arc.shift == 0.0 && abs(arc.extent - .pi * 2.0) < SVGEpsilon { return tag(SVGEllipseOpenTag, ["cx": arc.ellipse.cx.serialize(), "cy": arc.ellipse.cy.serialize(), "rx": arc.ellipse.rx.serialize(), "ry": arc.ellipse.ry.serialize()]) } else { let rx = arc.ellipse.rx let ry = arc.ellipse.ry let cx = arc.ellipse.cx let cy = arc.ellipse.cy let theta1 = arc.shift let delta = arc.extent let theta2 = theta1 + delta let x1 = cx + rx * cos(theta1) let y1 = cy + ry * sin(theta1) let x2 = cx + rx * cos(theta2) let y2 = cy + ry * sin(theta2) let largeArcFlag = abs(delta) > .pi ? 1 : 0 let sweepFlag = delta > 0.0 ? 1 : 0 var d = "M\(x1),\(y1) " d += "A \(rx),\(ry) 0.0 \(largeArcFlag), \(sweepFlag) \(x2),\(y2)" return tag(SVGPathOpenTag, ["d": d]) } } fileprivate func polygonToSVG(_ polygon: Polygon) -> String { let points = polygon.points.compactMap { String($0) }.joined(separator: ",") return tag(SVGPolygonOpenTag, ["points": points]) } fileprivate func polylineToSVG(_ polyline: Polyline) -> String { let points = polyline.points.compactMap { String($0) }.joined(separator: ",") return tag(SVGPolylineOpenTag, ["points": points]) } fileprivate func pathToSVG(_ path: Path) -> String { var d = "" for segment in path.segments { d += "\(segment.type) \(segment.data.compactMap { $0.serialize() }.joined(separator: " "))" } return tag(SVGPathOpenTag, ["d": d]) } fileprivate func lineToSVG(_ line: Line) -> String { return tag(SVGLineOpenTag, ["x1": line.x1.serialize(), "y1": line.y1.serialize(), "x2": line.x2.serialize(), "y2": line.y2.serialize()]) } fileprivate func ellipseToSVG(_ ellipse: Ellipse) -> String { return tag(SVGEllipseOpenTag, ["cx": ellipse.cx.serialize(), "cy": ellipse.cy.serialize(), "rx": ellipse.rx.serialize(), "ry": ellipse.ry.serialize()]) } fileprivate func circleToSVG(_ circle: Circle) -> String { return tag(SVGCircleOpenTag, ["cx": circle.cx.serialize(), "cy": circle.cy.serialize(), "r": circle.r.serialize()]) } fileprivate func roundRectToSVG(_ roundRect: RoundRect) -> String { return tag(SVGRectOpenTag, ["x": roundRect.rect.x.serialize(), "y": roundRect.rect.y.serialize(), "width": roundRect.rect.w.serialize(), "height": roundRect.rect.h.serialize(), "rx": roundRect.rx.serialize(), "ry": roundRect.ry.serialize()]) } fileprivate func rectToSVG(_ rect: Rect) -> String { return tag(SVGRectOpenTag, ["x": rect.x.serialize(), "y": rect.y.serialize(), "width": rect.w.serialize(), "height": rect.h.serialize()]) } fileprivate func imageToSVG(_ image: Image) -> String { var result = tag(SVGImageOpenTag, close: false) result += idToSVG(image.tag) result += clipToSVG(image.clip) result += transformToSVG(image.place) if image.src.contains("memory://") { if let data = image.base64encoded(type: Image.ImageRepresentationType.PNG) { result += " xlink:href=\"data:image/png;base64,\(data)\"" } } else { result += " xlink:href=\"\(image.src)\" " } if let bounds = image.bounds { result += " width=\"\(String(bounds.w))\" height=\"\(String(bounds.h))\" " } result += SVGGenericCloseTag return result } fileprivate func alignToSVG(_ align: Align) -> String { if align === Align.mid { return " text-anchor=\"middle\" " } if align === Align.max { return " text-anchor=\"end " } return "" } fileprivate func baselineToSVG(_ baseline: Baseline) -> String { if baseline == .top { return " dominant-baseline=\"text-before-edge\" " } return "" } fileprivate func textToSVG(_ text: Text) -> String { var result = tag(SVGTextOpenTag) result += idToSVG(text.tag) if let font = text.font { result += " font-family=\"\(font.name)\" font-size=\"\(font.size)\" " // TODO: check with enums if font.name != "normal" { result += " font-weight=\"\(font.weight)\" " } } result += alignToSVG(text.align) result += baselineToSVG(text.baseline) result += clipToSVG(text.clip) result += fillToSVG(text.fillVar.value) result += strokeToSVG(text.strokeVar.value) result += transformToSVG(text.place) result += SVGGenericEndTag result += text.text result += "</text>" return result } fileprivate func colorToSVG(_ color: Color) -> String { if let c = SVGConstants.valueToColor(color.val) { return "\(c)" } else { let r = color.r() let g = color.g() let b = color.b() return "#\(String(format: "%02X%02X%02X", r, g, b))" } } fileprivate func fillToSVG(_ fill: Fill?) -> String { if let fillColor = fill as? Color { var result = " fill=\"\(colorToSVG(fillColor))\"" if let opacity = alphaToSVGOpacity(fillColor.a()) { result += " fill-opacity=\"\(opacity)\"" } return result } return " fill=\"none\"" } fileprivate func alphaToSVGOpacity(_ alpha: Int) -> String? { if alpha == SVGDefaultOpacityValueAsAlpha { return .none } return String(Double(alpha) / Double(SVGDefaultOpacityValueAsAlpha)) } fileprivate func strokeToSVG(_ stroke: Stroke?) -> String { var result = "" if let strokeColor = stroke?.fill as? Color { result += " stroke=\"\(colorToSVG(strokeColor))\"" if let opacity = alphaToSVGOpacity(strokeColor.a()) { result += " stroke-opacity=\"\(opacity)\"" } } if let strokeWidth = stroke?.width { result += " stroke-width=\"\(strokeWidth)\"" } if let strokeCap = stroke?.cap { if strokeCap != SVGConstants.defaultStrokeLineCap { result += " stroke-linecap=\"\(strokeCap)\"" } } if let strokeJoin = stroke?.join { if strokeJoin != SVGConstants.defaultStrokeLineJoin { result += " stroke-linejoin=\"\(strokeJoin)\"" } } if let strokeDashes = stroke?.dashes, !strokeDashes.isEmpty { let dashes = strokeDashes.map { String($0) }.joined(separator: ",") result += " stroke-dasharray=\"\(dashes)\"" } if let strokeOffset = stroke?.offset { if strokeOffset != 0 { result += " stroke-dashoffset=\"\(strokeOffset)\"" } } return result } fileprivate func isSignificantMatrixTransform(_ t: Transform) -> Bool { for k in [t.m11, t.m12, t.m21, t.m22, t.dx, t.dy] { if abs(k) > SVGEpsilon { return true } } return false } fileprivate func transformToSVG(_ place: Transform) -> String { if [place.m11, place.m12, place.m21, place.m22] == [1.0, 0.0, 0.0, 1.0] { if [place.dx, place.dy] == [0.0, 0.0] { return "" } return " transform=\"translate(\(place.dx.serialize()),\(place.dy.serialize()))\" " } let matrixArgs = [place.m11, place.m12, place.m21, place.m22, place.dx, place.dy].map { $0.serialize() }.joined(separator: ",") return " transform=\"matrix(\(matrixArgs))\" " } fileprivate func locusToSVG(_ locus: Locus) -> String { switch locus { case let arc as Arc: return arcToSVG(arc) case let polygon as Polygon: return polygonToSVG(polygon) case let polyline as Polyline: return polylineToSVG(polyline) case let path as Path: return pathToSVG(path) case let line as Line: return lineToSVG(line) case let ellipse as Ellipse: return ellipseToSVG(ellipse) case let circle as Circle: return circleToSVG(circle) case let roundRect as RoundRect: return roundRectToSVG(roundRect) case let rect as Rect: return rectToSVG(rect) case let transformedLocus as TransformedLocus: return locusToSVG(transformedLocus.locus) + transformToSVG(transformedLocus.transform) default: return "\(SVGUndefinedTag) locus:\(locus)" } } fileprivate var defs: String = "" fileprivate func getDefs() -> String { if defs.isEmpty { return "" } return "<defs>" + defs + "</defs>" } fileprivate var clipPathCount: Int = 0 fileprivate func addClipToDefs(_ clip: Locus) { clipPathCount += 1 defs += "<\(SVGClipPathName) id=\"\(SVGClipPathName)\(clipPathCount)\">" + locusToSVG(clip) + SVGGenericCloseTag + "</\(SVGClipPathName)>" } fileprivate var maskCount: Int = 0 fileprivate func addMaskToDefs(_ mask: Node) { maskCount += 1 defs += "<\(SVGMaskName) id=\"\(SVGMaskName)\(maskCount)\">" + serialize(node: mask) + SVGGenericCloseTag + "</\(SVGMaskName)>" } fileprivate func idToSVG(_ tag: [String]) -> String { guard !tag.isEmpty, let id = tag.first else { return "" } return " id=\"\(id)\"" } fileprivate func clipToSVG(_ clipLocus: Locus?) -> String { guard let clip = clipLocus else { return "" } addClipToDefs(clip) return " clip-path=\"url(#\(SVGClipPathName)\(clipPathCount))\" " } fileprivate func maskToSVG(_ mask: Node?) -> String { guard let mask = mask else { return "" } addMaskToDefs(mask) return " mask=\"url(#\(SVGMaskName)\(maskCount))\" " } fileprivate func macawShapeToSvgShape (macawShape: Shape) -> String { let locus = macawShape.formVar.value var result = locusToSVG(locus) result += idToSVG(macawShape.tag) result += clipToSVG(macawShape.clip) result += maskToSVG(macawShape.mask) result += fillToSVG(macawShape.fillVar.value) result += strokeToSVG(macawShape.strokeVar.value) result += transformToSVG(macawShape.place) result += SVGGenericCloseTag return result } fileprivate func serialize(node: Node) -> String { if let shape = node as? Shape { return macawShapeToSvgShape(macawShape: shape) } if let group = node as? Group { var result = SVGGroupOpenTag result += idToSVG(group.tag) result += clipToSVG(group.clip) result += transformToSVG(group.place) result += SVGGenericEndTag for child in group.contentsVar.value { result += serialize(node: child) } result += SVGGroupCloseTag return result } if let image = node as? Image { return imageToSVG(image) } if let text = node as? Text { return textToSVG(text) } return "SVGUndefinedTag \(node)" } fileprivate func serializeRootNode(node: Node) -> String { var optionalSection = "" if let w = width { optionalSection += "width=\"\(w)\"" } if let h = height { optionalSection += " height=\"\(h)\"" } if let i = id { optionalSection += " id=\"\(i)\"" } var result = [SVGDefaultHeader, optionalSection, SVGGenericEndTag].joined(separator: " ") let body = serialize(node: node) result += getDefs() + body result += SVGFooter return result } open class func serialize(node: Node, width: Int? = nil, height: Int? = nil, id: String? = nil) -> String { return SVGSerializer(width: width, height: height, id: id).serializeRootNode(node: node) } } extension Double { func serialize() -> String { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 1 formatter.maximumFractionDigits = 6 formatter.decimalSeparator = "." return abs(self.remainder(dividingBy: 1)) > 0.00001 ? formatter.string(from: NSNumber(value: self))! : String(Int(self.rounded())) } }
mit
a7701b2889813156f669ef1388d81099
34.874396
249
0.567398
4.055707
false
false
false
false
Azoy/Sword
Sources/Sword/Types/Snowflake.swift
1
3020
// // Snowflake.swift // Sword // // Created by Alejandro Alonso // Copyright © 2018 Alejandro Alonso. All rights reserved. // import Foundation /// The stored type of a Discord Snowflake ID public struct Snowflake { /// Discord's Epoch public static let epoch = Date(timeIntervalSince1970: 1420070400) /// Number of generated ID's for the process public var increment: UInt16 { return UInt16(rawValue & 0xFFF) } /// Discord's internal process under worker that generated this snowflake public var processId: UInt8 { return UInt8((rawValue & 0x1F000) >> 12) } /// The internal value storage for a snowflake public let rawValue: UInt64 /// Time when snowflake was created public var timestamp: Date { return Date( timeInterval: Double( (rawValue >> 22) / 1000 ), since: Snowflake.epoch ) } /// Discord's internal worker ID that generated this snowflake public var workerId: UInt8 { return UInt8((rawValue & 0x3E0000) >> 17) } /// Produces a fake Snowflake with the given time and process ID public init() { var rawValue: UInt64 = 0 // Setup timestamp (42 bits) let now = Date() let difference = UInt64(now.timeIntervalSince(Snowflake.epoch) * 1000) rawValue |= difference << 22 // Setup worker id (5 bits) rawValue |= 16 << 17 // Setup process id (6 bits) rawValue |= 1 << 12 // Setup incremented id (11 bits) rawValue += 128 self.rawValue = rawValue } /// Init for rawValue conformance /// /// - parameter rawValue: The raw snowflake number public init(rawValue: UInt64) { self.rawValue = rawValue } } extension Snowflake: Encodable { /// Encode to JSON /// /// - parameter encoder: JSONEncoder public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } extension Snowflake: Decodable { /// Decode from JSON /// /// - parameter decoder: JSONDecoder public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let str = try container.decode(String.self) self.rawValue = UInt64(str)! } } extension Snowflake: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = UInt64 /// Initialize from an integer literal public init(integerLiteral value: UInt64) { self.rawValue = value } } extension Snowflake: CustomStringConvertible { /// Description for string conversion public var description: String { return rawValue.description } } extension Snowflake: RawRepresentable, Equatable { public typealias RawValue = UInt64 } extension Snowflake: Comparable { /// Used to compare Snowflakes public static func <(lhs: Snowflake, rhs: Snowflake) -> Bool { return lhs.rawValue < rhs.rawValue } } extension Snowflake: Hashable { /// The hash value of a Snowflake public var hashValue: Int { return rawValue.hashValue } }
mit
d551152cb6c203c5caf6f59286770e29
22.960317
75
0.676714
4.433186
false
false
false
false
moonknightskye/Luna
Luna/ViewController+ SCSChatDelegate.swift
1
1759
// // ViewController+ SCSChatDelegate.swift // Luna // // Created by Mart Civil on 2017/09/14. // Copyright © 2017年 salesforce.com. All rights reserved. // import Foundation import ServiceCore import ServiceChat extension ViewController: SCSChatDelegate { /** Delegate method invoked when a Live Agent Session Ends. @param chat `SCSChat` instance which invoked the method. @param reason `SCSChatEndReason` describing why the session has ended. @param error `NSError` instance describing the error. Error codes can be referenced from `SCSChatErrorCode`. @see `SCSChat` @see `SCSChatEndReason` */ func chat(_ chat: SCSChat!, didEndWith reason: SCSChatEndReason, error: Error!) { var code = 0 var label = "" if (error != nil) { code = (error as NSError).code print("ERROR") print(error) print(code) print(error.localizedDescription) } else { code = reason.rawValue } label = SFServiceLiveAgent.instance.getErrorLabel(reason: reason) let value = NSMutableDictionary() value.setValue( code, forKey: "code") value.setValue( label, forKey: "label") CommandProcessor.processSFServiceLiveAgentDidend( value: value ) } func chat(_ chat: SCSChat!, stateDidChange current: SCSChatSessionState, previous: SCSChatSessionState) { let value = NSMutableDictionary() value.setValue( current.rawValue, forKey: "code") value.setValue( SFServiceLiveAgent.instance.getState(state: current), forKey: "label") CommandProcessor.processSFServiceLiveAgentstateChange(value: value) } }
gpl-3.0
5bf9f02e9103117ea6f2b14ffbb24a1c
31.518519
94
0.645216
4.335802
false
false
false
false
PedroTrujilloV/TIY-Assignments
19--Keep-On-The-Sunny-Side/Forecaster/Forecaster/DetailViewController.swift
1
16191
// // ViewController.swift // GitHub Friends // // Created by Pedro Trujillo on 10/29/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit import MapKit import CoreLocation class DetailViewController: UIViewController,CLLocationManagerDelegate { var widthDevice = UIScreen.mainScreen().bounds.width var heightDevice = UIScreen.mainScreen().bounds.height // var currentDevice: UIDevice = UIDevice.currentDevice() var superiorView:UIView! var userImageView:UIImageView! var imagePath = "gravatar.png" var userImage:UIImage! let WeatherLabelEmoji:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 100)) let TemperatureLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 100)) let NameLabel:UILabel = UILabel(frame: CGRect(x:0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) let SummaryLabel:UILabel = UILabel(frame: CGRect(x: 0 , y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)) var mapView: MKMapView!//= MKMapView(frame: CGRect(x: 0 , y: 0, width: UIScreen.mainScreen().bounds.width, height: 200)) var widthConstrain :NSLayoutConstraint! var heighConstrain: NSLayoutConstraint! let locationManager = CLLocationManager() let geoCoder = CLGeocoder() var cityData: CityData! var rigthAddButtonItem:UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() // title = "City" self.setSuperiorView() self.loadImage(cityData.WeatherWeek[0].icon) self.setTemperaturLabel(cityData.WeatherWeek[0].temperature) self.setNameLabel(cityData.name) self.setSummaryLabel(cityData.WeatherWeek[0].summary) self.setMap(cityData) rigthAddButtonItem = UIBarButtonItem(title: "Next days", style: UIBarButtonItemStyle.Plain, target: self, action: "addButtonActionTapped:") self.navigationItem.setRightBarButtonItems([rigthAddButtonItem], animated: true) } //http://stackoverflow.com/questions/25666269/ios8-swift-how-to-detect-orientation-change override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { updateConstraints() } func updateConstraints() //update { mapView.removeConstraint(widthConstrain) mapView.removeConstraint(heighConstrain) if UIDevice.currentDevice().orientation.isLandscape.boolValue { print("landscape") heighConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice) mapView.addConstraint(heighConstrain) widthConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice * 0.7) mapView.addConstraint(widthConstrain) } else { print("portraight") widthConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice) mapView.addConstraint(widthConstrain) heighConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice * 0.8) mapView.addConstraint(heighConstrain) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setSuperiorView() { var superiorXpos = view.center.x var superiorYpos = view.center.y if widthDevice > heightDevice { let temp = widthDevice widthDevice = heightDevice heightDevice = temp superiorXpos = view.center.y superiorYpos = view.center.x } superiorView = UIView(frame: CGRect(x: 0 , y: 0, width: widthDevice , height: widthDevice )) //superiorView.backgroundColor = UIColor.blueColor() superiorView.center.x = superiorXpos //superiorView.center.y = UIScreen.mainScreen().bounds.height/2 //http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically superiorView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(superiorView) let horizontalConstraint = NSLayoutConstraint(item: superiorView , attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -10) view.addConstraint(horizontalConstraint) /*let horizontalConstraint2 = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1, constant: 0) superiorView(horizontalConstraint2)*/ let topMarginConstraint = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 30) view.addConstraint(topMarginConstraint) //let verticalConstraint = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //view.addConstraint(verticalConstraint) let widthConstraint = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice) superiorView.addConstraint(widthConstraint) // view.addConstraint(widthConstraint) // also works let heightConstraint = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice) superiorView.addConstraint(heightConstraint) let BottomMarginConstraint = NSLayoutConstraint(item: superiorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -5) view.addConstraint(BottomMarginConstraint) } func setMap(city:CityData) { print(UIDevice.currentDevice().orientation) var superiorXpos = view.center.x var superiorYpos = heightDevice * 0.8 if widthDevice > heightDevice { let temp = widthDevice widthDevice = heightDevice heightDevice = temp superiorXpos = UIScreen.mainScreen().bounds.width * 0.8 superiorYpos = UIScreen.mainScreen().bounds.height/2//heightDevice * 0.8 } mapView = MKMapView(frame: CGRect(x: 0 , y: 0, width: widthDevice, height: widthDevice * 0.8)) mapView.center.x = superiorXpos //view.center.x//UIScreen.mainScreen().bounds.width * (2/3) mapView.center.y = superiorYpos// UIScreen.mainScreen().bounds.height * 0.8 mapView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(mapView) let LocationCroords = CLLocationCoordinate2DMake( Double(city.latitude)!, Double(city.longitude)!) let weatherPlace = MKPointAnnotation() weatherPlace.coordinate = LocationCroords weatherPlace.title = city.name+", "+city.state weatherPlace.subtitle = city.WeatherWeek[0].temperature+"°F" let annotations = [weatherPlace] mapView.addAnnotations(annotations) mapView.showAnnotations(annotations, animated: true) mapView.camera.altitude *= 2 //mapView.translatesAutoresizingMaskIntoConstraints = false //let horizontalConstraint = NSLayoutConstraint(item: mapView , attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //view.addConstraint(horizontalConstraint) let horizontalConstraintRight = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0) view.addConstraint(horizontalConstraintRight) //let topMarginConstraint = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superiorView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) //view.addConstraint(topMarginConstraint) //let verticalConstraint = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //view.addConstraint(verticalConstraint) widthConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice) mapView.addConstraint(widthConstrain) // view.addConstraint(widthConstraint) // also works heighConstrain = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: widthDevice * 0.8) mapView.addConstraint(heighConstrain) updateConstraints() let BottomMarginConstraint = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) view.addConstraint(BottomMarginConstraint) } func setNameLabel(name:String = "0") { if name.characters.count < 8 { NameLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 50)//-Next-Condensed } else { NameLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 30)//-Next-Condensed } NameLabel.text = name NameLabel.textAlignment = .Center NameLabel.textColor = UIColor.blackColor() NameLabel.center.x = superiorView.center.x NameLabel.center.y = superiorView.bounds.height * 0.2 superiorView.addSubview(NameLabel) } func setTemperaturLabel(temperature:String = "0") { TemperatureLabel.text = temperature+"°F" // WeatherLabelEmoji.center.y = (imageView?.center.y)! TemperatureLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 80)//-Next-Condensed TemperatureLabel.textAlignment = .Center TemperatureLabel.textColor = UIColor.blackColor() TemperatureLabel.center.x = superiorView.bounds.width * (3/4) TemperatureLabel.center.y = superiorView.bounds.height * 0.4 superiorView.addSubview(TemperatureLabel) } func setSummaryLabel(summary:String = "0") { if summary.characters.count < 7 { SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 60)//-Next-Condensed } else { SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 40)//-Next-Condensed } SummaryLabel.text = summary SummaryLabel.textAlignment = .Center SummaryLabel.textColor = UIColor.grayColor() SummaryLabel.center.x = superiorView.center.x SummaryLabel.center.y = superiorView.bounds.height * 0.6 superiorView.addSubview(SummaryLabel) } func loadImage(wEmoji:String = "fog",var ImagePath:String = "gravatar.png") { if ImagePath == "" {ImagePath = self.imagePath} else {self.imagePath = ImagePath} if let url = NSURL(string: ImagePath) { if let data = NSData(contentsOfURL: url) { self.userImage = UIImage(data: data) self.userImageView = UIImageView(image: userImage!) self.userImageView!.contentMode = UIViewContentMode.ScaleAspectFit self.userImageView.frame = CGRect(x: 0, y: 0 , width: self.view.frame.size.width * 0.5 , height: self.view.frame.size.width * 0.5 ) self.userImageView.center.x = superiorView.bounds.width * (1/5) self.userImageView.center.y = superiorView.bounds.height * 0.4 superiorView.addSubview(userImageView) } } //var cosa = "⚡️🌙☀️⛅️☁️💧💦☔️💨❄️🔥🌌⛄️⚠️❗️🌁" let dictEmoji:Dictionary = [ "clear-day": "☀️","clear-night": "🌙", "rain":"☔️", "snow":"❄️", "sleet":"💦", "wind":"💨","fog":"🌁", "cloudy":"☁️", "partly-cloudy-day":"⛅️", "partly-cloudy-night":"🌌", "hail":"⛄️", "thunderstorm":"⚡️", "tornado":"⚠️"] WeatherLabelEmoji.text = dictEmoji[wEmoji] // WeatherLabelEmoji.center.y = (imageView?.center.y)! WeatherLabelEmoji.font = UIFont(name: "HelveticaNeue-Bold", size: 100) WeatherLabelEmoji.textAlignment = .Center WeatherLabelEmoji.textColor = UIColor.cyanColor() WeatherLabelEmoji.center.x = superiorView.bounds.width * (1/5) WeatherLabelEmoji.center.y = superiorView.bounds.height * 0.4 superiorView.addSubview(WeatherLabelEmoji) } //MARK: - Handle Actions func addButtonActionTapped(sender: UIButton) { print("Hay que rico!") //MARK: this piece of code is fucking awesome !!!! let searchTableVC = NextSevenDaysTableViewController() //let navigationController = UINavigationController(rootViewController: searchTableVC)// THIS is fucking awesome!!!! this create a new navigation controller that allows the modal view animation !!!!!!!!!!!!! searchTableVC.cityData = cityData //searchTableVC.delegator = self // 3 nescessary to get the value from the popover // navigationController?.pushViewController(searchTableVC, animated: true) //presentViewController(searchTableVC, animated: true, completion: nil)// it shows like a modal view //presentViewController(navigationController, animated: true, completion: nil) navigationController?.pushViewController(searchTableVC, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
f1360cab2d6c1671635003e77ffb8125
43.30854
253
0.664947
4.978025
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Input/Photos/Camera/LiveCameraCellPresenterFactory.swift
1
2349
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 AVFoundation public protocol LiveCameraCellPresenterFactoryProtocol { func makeLiveCameraCellPresenter() -> LiveCameraCellPresenterProtocol } public struct LiveCameraCellPresenterFactory: LiveCameraCellPresenterFactoryProtocol { private let cameraSettings: LiveCameraSettings private let cellAppearance: LiveCameraCellAppearance private let authorizationStatusProvider: AVAuthorizationStatusProvider public init(cameraSettings: LiveCameraSettings = .init(cameraPosition: .unspecified), cellAppearance: LiveCameraCellAppearance = .createDefaultAppearance(), authorizationStatusProvider: @escaping AVAuthorizationStatusProvider = { AVCaptureDevice.authorizationStatus(for: .video) }) { self.cameraSettings = cameraSettings self.cellAppearance = cellAppearance self.authorizationStatusProvider = authorizationStatusProvider } public func makeLiveCameraCellPresenter() -> LiveCameraCellPresenterProtocol { return LiveCameraCellPresenter( cameraSettings: self.cameraSettings, cellAppearance: self.cellAppearance, authorizationStatusProvider: self.authorizationStatusProvider ) } }
mit
ffb01e2a2181012142e6249bac571961
44.173077
142
0.778629
5.660241
false
false
false
false
kperryua/swift
test/Constraints/bridging.swift
2
17400
// RUN: %target-swift-frontend -parse -verify %s // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a non-whitelisted type from another module. extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterIterator { let result: LazyFilterIterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { var hashValue: Int { return 0 } func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { var hashValue: Int { return 0 } } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { var hashValue: Int { return 0 } } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 var inferDouble2 = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}} let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{binary operator '*' cannot be applied to two 'Double' operands}} expected-note {{expected an argument list of type '(Int, Int)'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} // FIXME: there should be a fixit appending "as String?" to the line; for now // it's sufficient that it doesn't suggest appending "as String" // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} // FIXME: The following diagnostic is misleading and should not happen: expected-warning@-1{{cast from 'NSMutableArray' to unrelated type 'Array<_>' always fails}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{does not conform to 'AnyObject'}} z = b z = c // expected-error{{does not conform to 'AnyObject'}} z = d // expected-error{{does not conform to 'AnyObject'}} z = e z = f z = g z = h // expected-error{{does not conform to 'AnyObject'}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y }
apache-2.0
1d8e5f45be3906dc418c71c76b864194
47.199446
305
0.695115
4.099906
false
false
false
false
sdaheng/Biceps
BicepsOperation.swift
1
2452
// // BicepsOperation.swift // HomeNAS // // Created by SDH on 2018/5/24. // Copyright © 2018 sdaheng. All rights reserved. // import Foundation class BicepsOperationQueue { let operationQueue: OperationQueue let operationUnderlyingQueue: DispatchQueue static let shared = BicepsOperationQueue() init() { let underlyingQueue = DispatchQueue(label: "com.body.biceps.operationQueue.underlyingQueue") self.operationUnderlyingQueue = underlyingQueue self.operationQueue = OperationQueue() self.operationQueue.underlyingQueue = underlyingQueue self.operationQueue.qualityOfService = .userInitiated self.operationQueue.name = "com.body.biceps.operationQueue.request" } } class BicepsOperation: Operation { var biceps: Biceps var _finished: Bool = false { willSet { self.willChangeValue(forKey: "isFinished") } didSet { self.didChangeValue(forKey: "isFinished") } } var _executing: Bool = false { willSet { self.willChangeValue(forKey: "isExecuting") } didSet { self.didChangeValue(forKey: "isExecuting") } } init(_ biceps: Biceps) { self.biceps = biceps } override func start() { guard self.isReady else { return } let progress = biceps.internalProgressBlock let success = biceps.internalSuccessBlock let fail = biceps.internalFailBlock self.biceps.progress({ [unowned self] ( _progress) in self._finished = false self._executing = true progress(_progress) }).success { [unowned self] (result) in self._finished = true self._executing = false success(result) }.fail({ [unowned self] (error) in self._finished = true self._executing = false fail(error) }).dispatchRequest(for: self.biceps.internalType, paramaterEncodingType: self.biceps.internalParameterEncodingType, paramaters: self.biceps.internalParamaters) } override var isExecuting: Bool { return _executing } override var isFinished: Bool { return _finished } }
mit
202cb830c55495dec54835b54dfeb272
25.934066
100
0.577315
4.902
false
false
false
false
johnpatrickmorgan/URLPatterns
Sources/CountedMatching.swift
1
1153
// // CountedMatching.swift // Pods // // Created by John Morgan on 14/05/2016. // // import Foundation public protocol CountedMatching { associatedtype Value func matches(_ value: Counted<Value>) -> Bool } public func ~=<E: CountedMatching>(pattern: E, value: Counted<E.Value>) -> Bool where E.Value: PatternMatching { return pattern.matches(value) } public struct Begins<Element: PatternMatching>: CountedMatching { var patternElements: [Element] public init(_ elements: Element...) { self.patternElements = elements } public func matches(_ value: Counted<Element.MatchValue>) -> Bool { return patternElements ~= Array(value.elements.prefix(patternElements.count)) } } public struct Ends<Element: PatternMatching>: CountedMatching { var patternElements: [Element] public init(_ elements: Element...) { self.patternElements = elements } public func matches(_ value: Counted<Element.MatchValue>) -> Bool { return patternElements ~= Array(value.elements.suffix(patternElements.count)) } }
mit
0a553350fdbf006edf45cae29d0aa0bf
21.607843
112
0.648742
4.27037
false
false
false
false
crazypoo/PTools
Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UITextViewExtensions.swift
1
1135
// // UITextViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 9/28/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Methods public extension UITextView { /// SwifterSwift: Clear text. func clear() { text = "" attributedText = NSAttributedString(string: "") } /// SwifterSwift: Scroll to the bottom of text view func scrollToBottom() { // swiftlint:disable:next legacy_constructor let range = NSMakeRange((text as NSString).length - 1, 1) scrollRangeToVisible(range) } /// SwifterSwift: Scroll to the top of text view func scrollToTop() { // swiftlint:disable:next legacy_constructor let range = NSMakeRange(0, 1) scrollRangeToVisible(range) } /// SwifterSwift: Wrap to the content (Text / Attributed Text). func wrapToContent() { contentInset = .zero scrollIndicatorInsets = .zero contentOffset = .zero textContainerInset = .zero textContainer.lineFragmentPadding = 0 sizeToFit() } } #endif
mit
73fd85f015ce450706d6356131d7c6a7
23.12766
67
0.631393
4.628571
false
false
false
false
Archerlly/ACRouter
Example/ACRouter/ErrorPageViewController.swift
1
1651
// // ErrorPageViewController.swift // ACRouter // // Created by SnowCheng on 26/03/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import ACRouter class ErrorPageViewController: UIViewController, ACRouterable { static func registerAction(info: [String : AnyObject]) -> AnyObject { let newInstance = ErrorPageViewController() let infoString = info.map { "\($0) : \($1)" }.joined(separator: "\n") newInstance.infoLabel.text = infoString newInstance.infoLabel.bounds.size = newInstance.infoLabel.sizeThatFits(newInstance.view.bounds.size) newInstance.infoLabel.center = newInstance.view.center if let bgColor = info["bgColor"] as? UIColor { newInstance.view.backgroundColor = bgColor } if let faildURL = info[ACRouter.matchFailedKey] as? String { newInstance.errorPage.isHidden = faildURL.characters.count == 0 } return newInstance } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white } lazy var infoLabel: UILabel = { let infoLabel = UILabel() infoLabel.numberOfLines = 0 self.view.addSubview(infoLabel) return infoLabel }() lazy var errorPage: UIImageView = { let errorPage = UIImageView.init(image: #imageLiteral(resourceName: "error")) errorPage.isHidden = true errorPage.center.x = self.view.center.x errorPage.center.y = 150 self.view.addSubview(errorPage) return errorPage }() }
mit
bbf4bfbf72cc7bd16d8fd3b406c5d08a
29
108
0.631515
4.661017
false
false
false
false
swift-lang/swift-k
tests/language-behaviour/variables/084-declare-many-at-once.swift
2
394
type messagefile {} app (messagefile t) greeting() { echo "hello" stdout=@filename(t); } messagefile outfile = greeting(); messagefile o2 = greeting(), o4 = greeting(), o5, o6[], o7=greeting(); o6[0] = greeting(); o6[1] = greeting(); o5 = greeting(); o6[2] = greeting(); // can't check the output in present framework because don't know // what filename got chosen for outfile...
apache-2.0
e126e3f709a1dba1b25e44e59620e040
22.176471
70
0.654822
3.396552
false
false
false
false
PureSwift/Cairo
Sources/Cairo/Pattern.swift
1
3773
// // Pattern.swift // Cairo // // Created by Alsey Coleman Miller on 1/31/16. // Copyright © 2016 PureSwift. All rights reserved. // import CCairo /// Represents a source when drawing onto a surface. /// /// There are different subtypes of patterns, for different types of sources. public final class Pattern { // MARK: - Internal Properties internal var internalPointer: OpaquePointer // MARK: - Initialization deinit { cairo_pattern_destroy(internalPointer) } internal init(_ internalPointer: OpaquePointer) { self.internalPointer = internalPointer } public init(surface: Surface) { self.internalPointer = cairo_pattern_create_for_surface(surface.internalPointer) } public init(color: (red: Double, green: Double, blue: Double)) { self.internalPointer = cairo_pattern_create_rgb(color.red, color.green, color.blue) } public init(color: (red: Double, green: Double, blue: Double, alpha: Double)) { self.internalPointer = cairo_pattern_create_rgba(color.red, color.green, color.blue, color.alpha) } public init(linear: (origin: (x: Double, y: Double), destination: (x: Double, y: Double))) { self.internalPointer = cairo_pattern_create_linear(linear.origin.x, linear.origin.y, linear.destination.x, linear.destination.y) } public init(radial: (start: (center: (x: Double, y: Double), radius: Double), end: (center: (x: Double, y: Double), radius: Double))) { self.internalPointer = cairo_pattern_create_radial(radial.start.center.x, radial.start.center.y, radial.start.radius, radial.end.center.x, radial.end.center.y, radial.end.radius) } public static var mesh: Pattern { let internalPointer = cairo_pattern_create_mesh()! return self.init(internalPointer) } // MARK: - Accessors public var type: PatternType { let internalPattern = cairo_pattern_get_type(internalPointer) let pattern = PatternType(rawValue: internalPattern.rawValue)! return pattern } public var status: Status { return cairo_pattern_status(internalPointer) } public var matrix: Matrix { get { var matrix = Matrix() cairo_pattern_get_matrix(internalPointer, &matrix) return matrix } set { var newValue = newValue cairo_pattern_set_matrix(internalPointer, &newValue) } } public var extend: Extend { get { return Extend(rawValue: cairo_pattern_get_extend(internalPointer).rawValue)! } set { cairo_pattern_set_extend(internalPointer, cairo_extend_t(rawValue: newValue.rawValue)) } } // MARK: - Methods /// Adds an opaque color stop to a gradient pattern. public func addColorStop(_ offset: Double, red: Double, green: Double, blue: Double) { cairo_pattern_add_color_stop_rgb(internalPointer, offset, red, green, blue) } /// Adds an opaque color stop to a gradient pattern. public func addColorStop(_ offset: Double, red: Double, green: Double, blue: Double, alpha: Double) { cairo_pattern_add_color_stop_rgba(internalPointer, offset, red, green, blue, alpha) } } // MARK: - Supporting Types /// Subtypes of `Pattern` public enum PatternType: UInt32 { case solid, surface, linear, radial, mesh, rasterSource } public enum Extend: UInt32 { case none, `repeat`, reflect, pad }
mit
31a942accb0d0210865cdf5a0e3b51b5
27.149254
186
0.6079
4.416862
false
false
false
false
PureSwift/Cairo
Sources/Cairo/SurfacePNG.swift
1
3388
// // SurfacePNG.swift // Cairo // // Created by Alsey Coleman Miller on 6/5/17. // // import struct Foundation.Data import CCairo public extension Surface { /// Writes the surface's contents to a PNG file. func writePNG(atPath path: String) { cairo_surface_write_to_png(internalPointer, path) } func writePNG() throws -> Data { let dataProvider = PNGDataProvider() let unmanaged = Unmanaged.passUnretained(dataProvider) let pointer = unmanaged.toOpaque() if let error = cairo_surface_write_to_png_stream(internalPointer, pngWrite, pointer).toError() { throw error } return dataProvider.data } } public extension Surface.Image { /// Creates a new image surface from PNG data read incrementally via the read function. @inline(__always) private convenience init(png readFunction: @escaping cairo_read_func_t, closure: UnsafeMutableRawPointer) throws { let internalPointer = cairo_image_surface_create_from_png_stream(readFunction, closure)! try self.init(internalPointer) } convenience init(png data: Data) throws { let dataProvider = PNGDataProvider(data: data) let unmanaged = Unmanaged.passUnretained(dataProvider) let pointer = unmanaged.toOpaque() try self.init(png: pngRead, closure: pointer) } } // MARK: - Supporting Types private extension Surface { final class PNGDataProvider { private(set) var data: Data private(set) var readPosition: Int = 0 init(data: Data = Data()) { self.data = data } @inline(__always) func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, length: Int) -> cairo_status_t { var size = length if (readPosition + size) > data.count { size = data.count - readPosition; } let _ = data.copyBytes(to: pointer, from: readPosition ..< readPosition + size) readPosition += size return CAIRO_STATUS_SUCCESS } @inline(__always) func copyBytes(from pointer: UnsafePointer<UInt8>, length: Int) -> cairo_status_t { data.append(pointer, count: length) return CAIRO_STATUS_SUCCESS } } } // MARK: - Private Functions @_silgen_name("_cairo_swift_png_read_data") private func pngRead(_ closure: UnsafeMutableRawPointer?, _ data: UnsafeMutablePointer<UInt8>?, _ length: UInt32) -> cairo_status_t { let unmanaged = Unmanaged<Surface.PNGDataProvider>.fromOpaque(closure!) let dataProvider = unmanaged.takeUnretainedValue() return dataProvider.copyBytes(to: data!, length: Int(length)) } @_silgen_name("_cairo_swift_png_write_data") private func pngWrite(_ closure: UnsafeMutableRawPointer?, _ data: UnsafePointer<UInt8>?, _ length: UInt32) -> cairo_status_t { let unmanaged = Unmanaged<Surface.PNGDataProvider>.fromOpaque(closure!) let dataProvider = unmanaged.takeUnretainedValue() return dataProvider.copyBytes(from: data!, length: Int(length)) }
mit
500f0562fb1a66ab3d90ce8e4a056080
27.233333
133
0.598583
4.785311
false
false
false
false
furuyan/RadarChartView
Example/RadarChartView/ViewController.swift
1
1522
// // ViewController.swift // RadarChartView // // Created by furuyan on 08/18/2017. // Copyright (c) 2017 furuyan. All rights reserved. // import UIKit class ViewController: UIViewController { lazy var showChartButton: UIButton = { let btn = UIButton() btn.setTitle("Show Chart", for: .normal) btn.setTitleColor(.black, for: .normal) btn.addTarget(self, action: #selector(showChart), for: .touchUpInside) return btn }() lazy var showChartOnTableViewButton: UIButton = { let btn = UIButton() btn.setTitle("Show Chart on TableView", for: .normal) btn.setTitleColor(.black, for: .normal) btn.addTarget(self, action: #selector(showChartOnTableView), for: .touchUpInside) return btn }() override func viewDidLoad() { super.viewDidLoad() showChartButton.frame.size = CGSize(width: 300, height: 30) showChartButton.center = view.center showChartOnTableViewButton.frame.size = CGSize(width: 300, height: 30) showChartOnTableViewButton.center = CGPoint(x: view.center.x, y: view.center.y + 50) view.addSubview(showChartButton) view.addSubview(showChartOnTableViewButton) } @objc func showChart() { navigationController?.pushViewController(RadarChartViewController(), animated: true) } @objc func showChartOnTableView() { navigationController?.pushViewController(RadarChartViewController2(), animated: true) } }
mit
b79830400155521869ef444d88a9fe46
32.086957
93
0.664258
4.263305
false
false
false
false
kak-ios-codepath/everest
Everest/Everest/Controllers/AddAction/AddActionViewController.swift
1
7271
// // AddActionViewController.swift // Everest // // Created by Kavita Gaitonde on 10/13/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import LNICoverFlowLayout import Announce class AddActionViewController: UIViewController { @IBOutlet weak fileprivate var categoriesCollectionView: UICollectionView! @IBOutlet weak fileprivate var coverFlowLayout: LNICoverFlowLayout! @IBOutlet weak fileprivate var actsTableView: UITableView! @IBOutlet weak var categoryPicsHeight: NSLayoutConstraint! @IBOutlet weak var categoryCollectionTopConstraint: NSLayoutConstraint! private var originalItemSize = CGSize.zero private var originalCollectionViewSize = CGSize.zero fileprivate var currentUser:User! fileprivate var categoryIndex = 0 fileprivate var categoryPicsExpanded = true override func viewDidLoad() { super.viewDidLoad() categoriesCollectionView.delegate = self categoryPicsHeight.constant = self.view.frame.height actsTableView.delegate = self actsTableView.estimatedRowHeight = 30 actsTableView.rowHeight = UITableViewAutomaticDimension categoriesCollectionView.reloadData() actsTableView.reloadData() originalItemSize = coverFlowLayout.itemSize originalCollectionViewSize = categoriesCollectionView.bounds.size } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) // We should invalidate layout in case we are switching orientation. // If we won't do that we will receive warning from collection view's flow layout that cell size isn't correct. coverFlowLayout.invalidateLayout() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Now we should calculate new item size depending on new collection view size. coverFlowLayout.itemSize = CGSize( width: categoriesCollectionView.bounds.size.width * originalItemSize.width / originalCollectionViewSize.width, height: categoriesCollectionView.bounds.size.height * originalItemSize.height / originalCollectionViewSize.height ) setInitialValues() // Forcely tell collection view to reload current data. categoriesCollectionView.setNeedsLayout() categoriesCollectionView.layoutIfNeeded() categoriesCollectionView.reloadData() } fileprivate func setInitialValues() { // Setting some nice defaults, ignore if you don't like them coverFlowLayout.maxCoverDegree = 45 coverFlowLayout.coverDensity = 0.06 coverFlowLayout.minCoverScale = 0.80 coverFlowLayout.minCoverOpacity = 0.50 } } //Mark:- Collection View Delegates extension AddActionViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return MainManager.shared.availableCategories.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "categoryCollectionCell", for: indexPath) as? CategoryCollectionCell else {return UICollectionViewCell()} cell.categoryPhotoURL = MainManager.shared.availableCategories[indexPath.row].imageUrl cell.categoryTitle = MainManager.shared.availableCategories[indexPath.row].title return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if categoryPicsExpanded { categoryPicsHeight.constant = 50 categoryCollectionTopConstraint.constant = 20 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() self.categoryPicsExpanded = false }) } else { categoryPicsHeight.constant = self.view.frame.height categoryCollectionTopConstraint.constant = 0 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() self.categoryPicsExpanded = true }) } } } //Mark:- Table View Delegates extension AddActionViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let acts = MainManager.shared.availableCategories[categoryIndex].acts else {return 0} return acts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "actsCell", for: indexPath) as? ActsCell else {return UITableViewCell()} let act = MainManager.shared.availableCategories[categoryIndex].acts[indexPath.row] cell.actText = act.title if let actions = User.currentUser?.actions { for action in actions { if action.id == act.id { DispatchQueue.main.async { cell.accessoryType = .checkmark } } else { cell.accessoryType = .none } } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { actsTableView.deselectRow(at: indexPath, animated: true) MainManager.shared.createNewAction(id: (MainManager.shared.availableCategories[categoryIndex].acts[indexPath.row].id), completion:{(error) in let cell = tableView.cellForRow(at: indexPath) as! ActsCell if cell.accessoryType == .checkmark { //Fire a quick message with a theme! let message = Message(message: "You are already subscribed to this act", theme: .warning) announce(message, on: .view(cell), withMode: .timed(3.0)) } else { cell.accessoryType = .checkmark let message = Message(message: "You are now successfully subscribed to this act", theme: .warning) announce(message, on: .view(cell), withMode: .timed(3.0)) self.dismiss(animated: true, completion: nil) } FireBaseManager.shared.getUser(userID: (User.currentUser?.id)!, completion: { (user, error) in User.currentUser = user }) }) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let velocity = scrollView.panGestureRecognizer.velocity(in: self.view) if abs(velocity.x) > abs(velocity.y) { if velocity.x > 0 && categoryIndex > 0 { categoryIndex -= 1 } else if velocity.x < 0 && categoryIndex < MainManager.shared.availableCategories.count-1 { categoryIndex += 1 } actsTableView.reloadData() } } }
apache-2.0
585e2960985419052a483b90202a8bfd
40.073446
186
0.659147
5.466165
false
false
false
false
oddnetworks/odd-sample-apps
apple/ios/OddSampleApp/OddSampleApp/MediaInfoTableViewCell.swift
1
988
// // MediaInfoTableViewCell.swift // OddSampleApp // // Created by Matthew Barth on 2/17/16. // Copyright © 2016 Odd Networks. All rights reserved. // import UIKit import OddSDK class MediaInfoTableViewCell: UITableViewCell { @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var notesLabel: UILabel! func configureWithCollection(_ collection: OddMediaObjectCollection) { self.backgroundColor = UIColor.clear self.titleLabel.text = collection.title self.notesLabel.text = collection.notes self.titleLabel.textColor = ThemeManager.defaultManager.currentTheme().tableViewCellTitleLabelColor self.notesLabel.textColor = ThemeManager.defaultManager.currentTheme().tableViewCellTextLabelColor self.selectionStyle = .gray collection.thumbnail { (image) -> Void in DispatchQueue.main.async(execute: { () -> Void in self.thumbnailImageView.image = image }) } } }
apache-2.0
bfd4a88d472fcb8c606d08582e47137d
30.83871
103
0.744681
4.65566
false
false
false
false
eleks/rnd-nearables-wearables
iOS/BeaconMe/BeaconMe/User Interface/PersonTableViewCell.swift
1
3016
// // PersonTableViewCell.swift // BeaconMe // // Created by Bogdan Shubravyi on 7/17/15. // Copyright (c) 2015 Eleks. All rights reserved. // import UIKit class PersonTableViewCell: SWTableViewCell { @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var placeLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var timeWidth: NSLayoutConstraint! static let cellID = "PersonTableViewCellIdentifier" class func defaultHeight() -> CGFloat { if DeviceType.IS_IPHONE_6 { return 64 } else if DeviceType.IS_IPHONE_6P { return 68 } return 60 } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .None self.backgroundColor = UIColor.clearColor() self.titleLabel.font = Style.nameTextFont() self.placeLabel.font = Style.locationTextFont() self.timeLabel.font = Style.timeTextFont() self.placeLabel.textColor = Style.tintColor() self.timeLabel.textColor = Style.highlightedColor() if DeviceType.IS_IPHONE_6 { self.timeWidth.constant = 84 } else if DeviceType.IS_IPHONE_6P { self.timeWidth.constant = 90 } } func configure(item: RecentItem, isHighlighted: Bool, delegate: SWTableViewCellDelegate?, isFavorite: Bool) { self.delegate = delegate self.titleLabel.textColor = isHighlighted ? UIColor.whiteColor() : Style.textColor() self.titleLabel.text = item.employeeName self.placeLabel.text = item.location self.timeLabel.text = DataFormatter.humanReadableDateWithTimestamp(item.timestamp) self.timeLabel.adjustsFontSizeToFitWidth = true self.photoImageView.image = UIImage(named: "user_placeholder") if let employeeId = item.employeeId { ImageProvider.instance.getImageWithUserId(employeeId, completion: { (imageValue: UIImage?) -> (Void) in if let image = imageValue { self.photoImageView.image = image } }) } self.setRightUtilityButtons(self.createRightButtonsForFavoriteMode(isFavorite), withButtonWidth: isFavorite ? 90 : 78) } func createRightButtonsForFavoriteMode(isFavorite: Bool) -> [UIButton] { var array: [UIButton] = [] var button = UIButton.buttonWithType(.Custom) as! UIButton button.backgroundColor = Style.tintColor() button.setTitle(isFavorite ? "Unfavorite" : "Favorite", forState: .Normal) button.titleLabel?.font = Style.nameTextFont() button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.titleLabel?.adjustsFontSizeToFitWidth = true array.append(button) return array } }
mit
fcfc5fbe70b7ee309214db561fbc46a8
31.085106
126
0.626326
4.888169
false
false
false
false
alexdoloz/Gridy
Gridy/Source/Grid4.swift
1
5026
import Foundation import CoreGraphics /** Defines infinite rectangle grid, consisting of cells which have integer coordinates. First you assign parameters to it (`width`, `space`, etc.), then you use various methods (i.e. `rectForCell(_:)`) which perform all the necessary math.*/ public struct Grid4 { // MARK: Properties /// Width of the cell; must be >= 0; default is 1.0 public var width: CGFloat = 1.0 { didSet { precondition(width > 0, "width must be > 0") } } /// Height of the cell; must be >= 0; default is 1.0 public var height: CGFloat = 1.0 { didSet { precondition(height > 0, "height must be > 0") } } /// Horizontal space between cells. By default there is no space (0.0). public var spaceX: CGFloat = 0.0 { didSet { precondition(spaceX >= 0.0, "spaceX must be >= 0") } } /// Vertical space between cells. By default there is no space (0.0). public var spaceY: CGFloat = 0.0 { didSet { precondition(spaceY >= 0.0, "spaceY must be >= 0") } } /// Point to which `anchorCell` is anchored. See also `anchorMode`. public var anchorPoint: CGPoint = CGPointZero /// Defines a way how `anchorCell` is anchored public var anchorMode: AnchorMode = .origin /// Cell which is anchored to `anchorPoint`. public var anchorCell: Cell = Cell() // MARK: Methods /// Sets `width` and `height` to `dimension`. public mutating func setDimension(dimension: CGFloat) { precondition(dimension >= 0) width = dimension height = dimension } /// Sets `spaceX` and `spaceY` to `space`. public mutating func setSpace(space: CGFloat) { spaceX = space spaceY = space } /// Calculates rect for given cell. public func rectForCell(cell: Cell) -> CGRect { let size = CGSize(width: width, height: height) let originX = anchorPoint.x + anchorSpaceX + (cell.point.x - anchorCell.point.x) * (width + spaceX) let originY = anchorPoint.y + anchorSpaceY + (cell.point.y - anchorCell.point.y) * (height + spaceY) let origin = CGPoint(x: originX, y: originY) return CGRect(origin: origin, size: size) } /// Finds all cells that contain given point. If point belongs to space between cells, it returns empty array. public func cellsForPoint(point: CGPoint) -> [Cell] { let cx = width + spaceX let dx1 = anchorPoint.x + anchorSpaceX - cx * anchorCell.point.x let dx2 = dx1 + width let cy = height + spaceY let dy1 = anchorPoint.y + anchorSpaceY - cy * anchorCell.point.y let dy2 = dy1 + height let intervalForCellX = ((point.x - dx2) / cx) ... ((point.x - dx1) / cx) let intervalForCellY = ((point.y - dy2) / cy) ... ((point.y - dy1) / cy) guard let integerValuesX = intervalForCellX.intValues, let integerValuesY = intervalForCellY.intValues else { return [] } var result: [Cell] = [] for x in integerValuesX { for y in integerValuesY { let cell = Cell(x: x, y: y) result.append(cell) } } return result } // MARK: Subscripts public subscript(x: Int, y: Int) -> CGRect { get { return rectForCell(Cell(x: x, y: y)) } } public subscript(point: CGPoint) -> [Cell] { get { return cellsForPoint(point) } } } private extension Grid4 { /// Horizontal space from center of the `anchorCell` to the `anchorPoint`. var anchorSpaceX: CGFloat { switch anchorMode { case .center: return -0.5 * width case .origin: return 0.0 case .originWithSpace: return -0.5 * spaceX } } /// Vertical space from center of the `anchorCell` to the `anchorPoint`. var anchorSpaceY: CGFloat { switch anchorMode { case .center: return -0.5 * height case .origin: return 0.0 case .originWithSpace: return -0.5 * spaceY } } } public extension Grid4 { public enum AnchorMode: Int { /// Anchor cell is anchored to its center. case center /// Anchor cell is anchored to its origin. case origin /// The same as `origin` but also with respect to `spaceX` and `spaceY` case originWithSpace } } private extension IntervalType where Bound == CGFloat { /// Returns int values, containing in this closed `CGFloat` interval. If there are no such values, it returns `nil`. var intValues: Range<Int>? { let startValue = Int(ceil(self.start)) let endValue = Int(floor(self.end)) if startValue > endValue { return nil } return startValue...endValue } }
mit
bf2de78e5d0872e014329c5eeea0f63a
30.4125
242
0.577
4.181364
false
false
false
false
neoneye/SwiftyFORM
Source/Cells/SegmentedControlCell.swift
1
1278
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public struct SegmentedControlCellModel { var title: String = "" var items: [String] = ["a", "b", "c"] var value = 0 var valueDidChange: (Int) -> Void = { (value: Int) in SwiftyFormLog("value \(value)") } } public class SegmentedControlCell: UITableViewCell { public let model: SegmentedControlCellModel public let segmentedControl: UISegmentedControl public init(model: SegmentedControlCellModel) { self.model = model self.segmentedControl = UISegmentedControl(items: model.items) super.init(style: .default, reuseIdentifier: nil) selectionStyle = .none textLabel?.text = model.title segmentedControl.selectedSegmentIndex = model.value segmentedControl.addTarget(self, action: #selector(SegmentedControlCell.valueChanged), for: .valueChanged) accessoryView = segmentedControl } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc public func valueChanged() { SwiftyFormLog("value did change") model.valueDidChange(segmentedControl.selectedSegmentIndex) } public func setValueWithoutSync(_ value: Int) { SwiftyFormLog("set value \(value)") segmentedControl.selectedSegmentIndex = value } }
mit
f6d9662843c3696ac0306ade7184731b
28.72093
108
0.755869
4.083067
false
false
false
false
jorik041/mpv
video/out/mac/view.swift
8
9773
/* * This file is part of mpv. * * mpv is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa class View: NSView { unowned var common: Common var mpv: MPVHelper? { get { return common.mpv } } var tracker: NSTrackingArea? var hasMouseDown: Bool = false override var isFlipped: Bool { return true } override var acceptsFirstResponder: Bool { return true } init(frame: NSRect, common com: Common) { common = com super.init(frame: frame) autoresizingMask = [.width, .height] wantsBestResolutionOpenGLSurface = true registerForDraggedTypes([ .fileURLCompat, .URLCompat, .string ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateTrackingAreas() { if let tracker = self.tracker { removeTrackingArea(tracker) } tracker = NSTrackingArea(rect: bounds, options: [.activeAlways, .mouseEnteredAndExited, .mouseMoved, .enabledDuringMouseDrag], owner: self, userInfo: nil) // here tracker is guaranteed to be none-nil addTrackingArea(tracker!) if containsMouseLocation() { cocoa_put_key_with_modifiers(SWIFT_KEY_MOUSE_LEAVE, 0) } } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { guard let types = sender.draggingPasteboard.types else { return [] } if types.contains(.fileURLCompat) || types.contains(.URLCompat) || types.contains(.string) { return .copy } return [] } func isURL(_ str: String) -> Bool { // force unwrapping is fine here, regex is guarnteed to be valid let regex = try! NSRegularExpression(pattern: "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$", options: .caseInsensitive) let isURL = regex.numberOfMatches(in: str, options: [], range: NSRange(location: 0, length: str.count)) return isURL > 0 } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { let pb = sender.draggingPasteboard guard let types = pb.types else { return false } if types.contains(.fileURLCompat) || types.contains(.URLCompat) { if let urls = pb.readObjects(forClasses: [NSURL.self]) as? [URL] { let files = urls.map { $0.absoluteString } EventsResponder.sharedInstance().handleFilesArray(files) return true } } else if types.contains(.string) { guard let str = pb.string(forType: .string) else { return false } var filesArray: [String] = [] for val in str.components(separatedBy: "\n") { let url = val.trimmingCharacters(in: .whitespacesAndNewlines) let path = (url as NSString).expandingTildeInPath if isURL(url) { filesArray.append(url) } else if path.starts(with: "/") { filesArray.append(path) } } EventsResponder.sharedInstance().handleFilesArray(filesArray) return true } return false } override func acceptsFirstMouse(for event: NSEvent?) -> Bool { return true } override func becomeFirstResponder() -> Bool { return true } override func resignFirstResponder() -> Bool { return true } override func mouseEntered(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { cocoa_put_key_with_modifiers(SWIFT_KEY_MOUSE_ENTER, 0) } common.updateCursorVisibility() } override func mouseExited(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { cocoa_put_key_with_modifiers(SWIFT_KEY_MOUSE_LEAVE, 0) } common.titleBar?.hide() common.setCursorVisiblility(true) } override func mouseMoved(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseMovement(event) } common.titleBar?.show() } override func mouseDragged(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseMovement(event) } } override func mouseDown(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseDown(event) } } override func mouseUp(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseUp(event) } common.window?.isMoving = false } override func rightMouseDown(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseDown(event) } } override func rightMouseUp(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseUp(event) } } override func otherMouseDown(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseDown(event) } } override func otherMouseUp(with event: NSEvent) { if mpv?.mouseEnabled() ?? true { signalMouseUp(event) } } override func magnify(with event: NSEvent) { event.phase == .ended ? common.windowDidEndLiveResize() : common.windowWillStartLiveResize() common.window?.addWindowScale(Double(event.magnification)) } func signalMouseDown(_ event: NSEvent) { signalMouseEvent(event, MP_KEY_STATE_DOWN) if event.clickCount > 1 { signalMouseEvent(event, MP_KEY_STATE_UP) } } func signalMouseUp(_ event: NSEvent) { signalMouseEvent(event, MP_KEY_STATE_UP) } func signalMouseEvent(_ event: NSEvent, _ state: UInt32) { hasMouseDown = state == MP_KEY_STATE_DOWN let mpkey = getMpvButton(event) cocoa_put_key_with_modifiers((mpkey | Int32(state)), Int32(event.modifierFlags.rawValue)) } func signalMouseMovement(_ event: NSEvent) { var point = convert(event.locationInWindow, from: nil) point = convertToBacking(point) point.y = -point.y common.window?.updateMovableBackground(point) if !(common.window?.isMoving ?? false) { mpv?.setMousePosition(point) } } func preciseScroll(_ event: NSEvent) { var delta: Double var cmd: Int32 if abs(event.deltaY) >= abs(event.deltaX) { delta = Double(event.deltaY) * 0.1 cmd = delta > 0 ? SWIFT_WHEEL_UP : SWIFT_WHEEL_DOWN } else { delta = Double(event.deltaX) * 0.1 cmd = delta > 0 ? SWIFT_WHEEL_RIGHT : SWIFT_WHEEL_LEFT } mpv?.putAxis(cmd, delta: abs(delta)) } override func scrollWheel(with event: NSEvent) { if !(mpv?.mouseEnabled() ?? true) { return } if event.hasPreciseScrollingDeltas { preciseScroll(event) } else { let modifiers = event.modifierFlags let deltaX = modifiers.contains(.shift) ? event.scrollingDeltaY : event.scrollingDeltaX let deltaY = modifiers.contains(.shift) ? event.scrollingDeltaX : event.scrollingDeltaY var mpkey: Int32 if abs(deltaY) >= abs(deltaX) { mpkey = deltaY > 0 ? SWIFT_WHEEL_UP : SWIFT_WHEEL_DOWN } else { mpkey = deltaX > 0 ? SWIFT_WHEEL_RIGHT : SWIFT_WHEEL_LEFT } cocoa_put_key_with_modifiers(mpkey, Int32(modifiers.rawValue)) } } func containsMouseLocation() -> Bool { var topMargin: CGFloat = 0.0 let menuBarHeight = NSApp.mainMenu?.menuBarHeight ?? 23.0 guard let window = common.window else { return false } guard var vF = window.screen?.frame else { return false } if window.isInFullscreen && (menuBarHeight > 0) { topMargin = TitleBar.height + 1 + menuBarHeight } vF.size.height -= topMargin let vFW = window.convertFromScreen(vF) let vFV = convert(vFW, from: nil) let pt = convert(window.mouseLocationOutsideOfEventStream, from: nil) var clippedBounds = bounds.intersection(vFV) if !window.isInFullscreen { clippedBounds.origin.y += TitleBar.height clippedBounds.size.height -= TitleBar.height } return clippedBounds.contains(pt) } func canHideCursor() -> Bool { guard let window = common.window else { return false } return !hasMouseDown && containsMouseLocation() && window.isKeyWindow } func getMpvButton(_ event: NSEvent) -> Int32 { let buttonNumber = event.buttonNumber switch (buttonNumber) { case 0: return SWIFT_MBTN_LEFT case 1: return SWIFT_MBTN_RIGHT case 2: return SWIFT_MBTN_MID case 3: return SWIFT_MBTN_BACK case 4: return SWIFT_MBTN_FORWARD default: return SWIFT_MBTN9 + Int32(buttonNumber - 5) } } }
gpl-3.0
ebeaa5134e5d6d6cd682ab5cda546183
31.905724
100
0.593267
4.424174
false
false
false
false
Hidebush/McBlog
McBlog/McBlog/Classes/Module/NewFuture/NewFeautureController.swift
1
4434
// // NewFeautureController.swift // McBlog // // Created by admin on 16/4/29. // Copyright © 2016年 郭月辉. All rights reserved. // import UIKit private let reuseIdentifier = "NewFeatureCell" class NewFeautureController: UICollectionViewController { private let imageCount = 4 private let yhLayout = YHFlowLayout() init() { super.init(collectionViewLayout: yhLayout) } required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell cell.index = indexPath.item return cell } } class NewFeatureCell: UICollectionViewCell { var index: Int = 0 { didSet { imageView.image = UIImage(named: "new_feature_\(index + 1)") button.hidden = !(index == 3) (index == 3) ? buttonAnim() : () } } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) prepareUI() } private func prepareUI() { contentView.addSubview(imageView) contentView.addSubview(button) imageView.snp_makeConstraints { (make) in make.edges.equalTo(contentView) } button.snp_makeConstraints { (make) in make.centerX.equalTo(contentView.snp_centerX) make.bottom.equalTo(contentView.snp_bottom).offset(-100) } } private func buttonAnim() { button.userInteractionEnabled = false button.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(1.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { self.button.transform = CGAffineTransformIdentity }) { (_) in self.button.userInteractionEnabled = true } } @objc func startButtonClick() { print("start") NSNotificationCenter.defaultCenter().postNotificationName(YHRootViewControllerSwitchNotification, object: true) } private lazy var imageView = UIImageView() private lazy var button: UIButton = { let button = UIButton(type: .Custom) button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted) button.setTitle("开始体验", forState: UIControlState.Normal) button.sizeToFit() button.addTarget(self, action: #selector(startButtonClick), forControlEvents: UIControlEvents.TouchUpInside) return button }() } private class YHFlowLayout: UICollectionViewFlowLayout { private override func prepareLayout() { itemSize = collectionView!.bounds.size scrollDirection = .Horizontal minimumLineSpacing = 0 collectionView?.pagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.bounces = false } }
mit
0c51b79c92421b9ec9b9cb1671071947
29.888112
167
0.663346
5.308894
false
false
false
false
NEU-Coders/appcontest
SceneKit-Demo/SceneKit-Demo/GameViewController.swift
1
1769
// // GameViewController.swift // SceneKit-Demo // // Created by 张星宇 on 16/1/25. // Copyright (c) 2016年 zxy. All rights reserved. // import UIKit import QuartzCore import SceneKit class GameViewController: UIViewController { let scene = SCNScene(named: "art.scnassets/main.scn")! override func viewDidLoad() { super.viewDidLoad() sceneSetup() } func sceneSetup() { //从四面八方照向scene的环境光 let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLightTypeAmbient ambientLightNode.light!.color = UIColor(white: 0.67, alpha: 1.0) scene.rootNode.addChildNode(ambientLightNode) // 从远点向外发射的点光源 let omniLightNode = SCNNode() omniLightNode.light = SCNLight() omniLightNode.light!.type = SCNLightTypeOmni omniLightNode.light!.color = UIColor(white: 0.75, alpha: 1.0) scene.rootNode.addChildNode(omniLightNode) let sceneView = self.view as! SCNView sceneView.allowsCameraControl = true sceneView.scene = scene } override func shouldAutorotate() -> Bool { return true } override func prefersStatusBarHidden() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } }
gpl-2.0
dc8e221019e90f8251ee00e115ce943f
26.693548
82
0.630169
4.769444
false
false
false
false
moowahaha/Chuck
Chuck/GameViewController.swift
1
4521
// // GameViewController.swift // Chuck // // Created by Stephen Hardisty on 14/10/15. // Copyright (c) 2015 Mr. Stephen. All rights reserved. // import UIKit import SpriteKit let HighScoreKey = "HIGH_SCORE" class GameViewController: UIViewController { @IBOutlet weak var lastScoreLabel: UILabel! @IBOutlet weak var totalScoreLabel: UILabel! @IBOutlet weak var restartLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var titleLabel2: UILabel! @IBOutlet weak var titleLabel3: UILabel! @IBOutlet weak var labelContainer: UIView! @IBOutlet weak var scoreContainer: UIView! @IBOutlet weak var missLabel: UILabel! @IBOutlet weak var gameOverReason: UILabel! @IBOutlet weak var highScore: UILabel! @IBOutlet weak var tapToRestart: UILabel! var defaults: NSUserDefaults! override func viewDidLoad() { // Configure the view. let skView = self.view as! SKView skView.allowsTransparency = false skView.frameInterval = 1 skView.ignoresSiblingOrder = true self.showTitleLabels() self.startGame() self.defaults = NSUserDefaults.standardUserDefaults() UIView.animateWithDuration( 0.2, delay: 2.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.titleLabel.alpha = 0.0 }, completion: nil ) UIView.animateWithDuration( 0.2, delay: 2.5, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.titleLabel2.alpha = 0.0 self.titleLabel3.alpha = 0.0 }, completion: nil ) } override func shouldAutorotate() -> Bool { return false } override func prefersStatusBarHidden() -> Bool { return true } func startGame() { self.hideStatusLabels() let skView = self.view as! SKView let scene = GameScene(size: skView.frame.size) scene.controller = self scene.score = Score( scoreContainer: self.scoreContainer, totalScoreLabel: self.totalScoreLabel, lastScoreLabel: self.lastScoreLabel ) /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill scene.missLabel = self.missLabel skView.presentScene(scene) } func promptForRestart(score: Score, reason: String!) { self.scoreContainer.alpha = 0.0 self.hideTitleLabels() self.hideStatusLabels() self.restartLabel.text = "Scored \(score.totalScore)." self.gameOverReason.text = reason let currentHighScore = defaults.integerForKey(HighScoreKey) if score.totalScore > currentHighScore { defaults.setInteger(score.totalScore, forKey: HighScoreKey) self.restartLabel.text? += " New high score." self.highScore.text = "Last high score was \(currentHighScore)." } else if currentHighScore > 0 { self.highScore.text = "High score is \(currentHighScore)." } else { self.highScore.text = "No high score yet." } UIView.animateWithDuration( 0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.showStatusLabels() }, completion: nil ) } private func showTitleLabels() { self.labelContainer.center = CGPoint( x: self.view.frame.width / 2, y: (self.view.frame.height / 4) - Radius/2 ) self.titleLabel.alpha = 1.0 self.titleLabel2.alpha = 1.0 self.titleLabel3.alpha = 1.0 } private func showStatusLabels() { self.gameOverReason.alpha = 1.0 self.restartLabel.alpha = 1.0 self.highScore.alpha = 1.0 self.tapToRestart.alpha = 1.0 } private func hideTitleLabels() { self.titleLabel.alpha = 0.0 self.titleLabel2.alpha = 0.0 self.titleLabel3.alpha = 0.0 } private func hideStatusLabels() { self.restartLabel.alpha = 0.0 self.gameOverReason.alpha = 0.0 self.highScore.alpha = 0.0 self.tapToRestart.alpha = 0.0 } }
mit
cc702b47fb32cde073295e5f63b604ef
28.167742
76
0.583499
4.694704
false
false
false
false
iccub/freestyle-timer-ios
freestyle-timer-ios/settings/Settings.swift
1
5180
/* Copyright © 2017 Michał Buczek. This file is part of Freestyle Timer. Freestyle Timer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Freestyle Timer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Freestyle Timer. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import os.log /** Structure holding all things needed for settings: keyPath for UserDefaults and predefinied values which are filled after setting an option. Settings are split by timer modes: Battle and Qualifications. */ struct Settings: Codable { static let log = OSLog(subsystem: "com.michalbuczek.freestyle_timer_ios.logs", category: "Settings") /** SettingsOptions are used to fill SettingsOptionsTableVC with predefinied data. It holds two properties, display name to show as a label in table cell and its value. */ typealias SettingsOption = (name: String, value: Int) /** Keep track wheter settings were initialized with default data. */ static let settingsInitializedKey = "settingsInitialized" /** Shorthand method to get values from UserDefaults.default object. */ static func int(for key: String) -> Int { return UserDefaults.standard.integer(forKey: key) } struct Battle { struct Keys { static let players = "settingsBattlePlayers" static let roundDuration = "settingsBattleRoundDuration" static let numberOfRounds = "settingsBattleNumberOfRounds" static let preparationTime = "settingsBattlePreparationTime" } struct Options { static let playerOptions = [SettingsOption("2 players", 2), SettingsOption("3 players", 3), SettingsOption("4 players", 4)] static let roundDuration = [SettingsOption("30 seconds", 30), SettingsOption("45 seconds", 45), SettingsOption("60 seconds", 60)] static let numberOfRounds = [SettingsOption("1 round", 1), SettingsOption("2 rounds", 2), SettingsOption("3 rounds", 3), SettingsOption("4 rounds", 4)] static let preparationTime = [SettingsOption("3 seconds", 3), SettingsOption("5 seconds", 5), SettingsOption("10 seconds", 10)] } } struct Qualification { struct Keys { static let duration = "settingsQualificationDuration" static let soundInterval = "settingsQualificationSoundInterval" static let preparationTime = "settingsQualificationPreparationTime" } struct Options { static let duration = [SettingsOption("30 seconds", 30), SettingsOption("45 seconds", 45), SettingsOption("60 seconds", 60), SettingsOption("75 seconds", 75), SettingsOption("90 seconds", 90), SettingsOption("120 seconds", 120), SettingsOption("180 seconds", 180)] static let soundInterval = [SettingsOption("15 seconds", 15), SettingsOption("30 seconds", 30), SettingsOption("45 seconds", 45), SettingsOption("60 seconds", 60)] static let preparationTime = [SettingsOption("3 seconds", 3), SettingsOption("5 seconds", 5), SettingsOption("10 seconds", 10)] } } /** Defaults used for first use of the app */ static func initializeDefaults() { os_log("initializing defaults", log: Settings.log) let settings = UserDefaults.standard settings.set(2, forKey: Battle.Keys.players) settings.set(30, forKey: Battle.Keys.roundDuration) settings.set(3, forKey: Battle.Keys.numberOfRounds) settings.set(10, forKey: Battle.Keys.preparationTime) settings.set(90, forKey: Qualification.Keys.duration) settings.set(30, forKey: Qualification.Keys.soundInterval) settings.set(10, forKey: Qualification.Keys.preparationTime) settings.set(true, forKey: Settings.settingsInitializedKey) settings.synchronize() } }
gpl-3.0
89ac978032198ea82e8379882fd031cb
44.026087
115
0.577636
5.439076
false
false
false
false
BlenderSleuth/Circles
Circles/ViewControllers/GameViewController.swift
1
799
// // GameViewController.swift // Circles // // Created by Ben Sutherland on 15/05/2016. // Copyright (c) 2016 blendersleuthgraphics. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { //For testing var level: Level = Levels.sharedInstance.levels[0] @IBOutlet var skView: SKView! override func viewDidLoad() { super.viewDidLoad() skView.showsFPS = true skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: skView.bounds.size, level: level) scene.scaleMode = .resizeFill skView.presentScene(scene) } override var prefersStatusBarHidden: Bool { return true } }
gpl-3.0
82a41295ce9c4e832ba7e1a8d445a01b
21.194444
69
0.629537
4.755952
false
false
false
false
qinhaichuan/Microblog
microblog/microblog/Classes/Home/QRCode/QRCodeCreatViewController.swift
1
2402
// // QRCodeCreatViewController.swift // microblog // // Created by QHC on 6/17/16. // Copyright © 2016 秦海川. All rights reserved. // import UIKit class QRCodeCreatViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "我的名片" view.backgroundColor = UIColor.purpleColor() view.addSubview(imageV) creatQRCode() } private func creatQRCode() { let filter = CIFilter(name: "CIQRCodeGenerator")! filter.setDefaults() let data = "我的名片".dataUsingEncoding(NSUTF8StringEncoding) filter.setValue(data, forKey: "inputMessage") let ciImage = filter.outputImage! imageV.image = createNonInterpolatedUIImageFormCIImage(ciImage, size: 300) } /** 生成高清二维码 - parameter image: 需要生成原始图片 - parameter size: 生成的二维码的宽高 */ private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = CGRectIntegral(image.extent) let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)) // 1.创建bitmap; let width = CGRectGetWidth(extent) * scale let height = CGRectGetHeight(extent) * scale let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()! let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)! let context = CIContext(options: nil) let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent) CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None) CGContextScaleCTM(bitmapRef, scale, scale); CGContextDrawImage(bitmapRef, extent, bitmapImage); // 2.保存bitmap到图片 let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)! return UIImage(CGImage: scaledImage) } // MARK: ----- 懒加载 private lazy var imageV: UIImageView = { let imageV = UIImageView() imageV.bounds.size.width = 300 imageV.bounds.size.height = 300 imageV.center = self.view.center return imageV }() }
mit
b815ad1bb0b3bd71c922e55be5fbd195
27.182927
100
0.615751
4.969892
false
false
false
false
LiuSky/XBKit
Pods/RxExtension/RxExtension/Classes/UITableViewHeaderFooterView+Rx.swift
1
1420
// // UITableViewHeaderFooterView+Rx.swift // RxExtension // // Created by xiaobin liu on 2017/3/28. // Copyright © 2017年 Sky. All rights reserved. // import Foundation import UIKit import RxSwift private var prepareForReuseBag: Int8 = 0 public extension UITableViewHeaderFooterView { public var rx_prepareForReuse: Observable<Void> { return Observable.of(self.rx.sentMessage(#selector(UITableViewHeaderFooterView.prepareForReuse)).map { _ in () }, self.rx.deallocated).merge() } public var rx_prepareForReuseBag: DisposeBag { MainScheduler.ensureExecutingOnScheduler() if let bag = objc_getAssociatedObject(self, &prepareForReuseBag) as? DisposeBag { return bag } let bag = DisposeBag() objc_setAssociatedObject(self, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) _ = self.rx.sentMessage(#selector(UITableViewHeaderFooterView.prepareForReuse)).subscribe(onNext: { [weak self] _ in let newBag = DisposeBag() objc_setAssociatedObject(self, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }) return bag } } public extension Reactive where Base: UITableViewHeaderFooterView { public var prepareForReuseBag: DisposeBag { return base.rx_prepareForReuseBag } }
mit
844827edb4eb6866a995c3c95beb1a41
29.148936
150
0.685251
4.97193
false
false
false
false
benjaminsnorris/SharedHelpers
Sources/Nameable.swift
1
871
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit public protocol Nameable { } public extension Nameable { static var name: String { return String(describing: Self.self) } func addAccessibilityIdentifiers() { for (label, object) in Mirror(reflecting: self).children { guard let label = label else { continue } let accessibleObject: UIAccessibilityIdentification if let view = object as? UIView { accessibleObject = view } else if let barItem = object as? UIBarItem { accessibleObject = barItem } else { continue } accessibleObject.accessibilityIdentifier = Self.name + "." + label } } }
mit
e8d9c19f83cf62ec08f4ecc1ea536a75
24.484848
78
0.500595
4.595628
false
false
false
false
csjlengxiang/RealmHelper-ReamDataAble
RealmHelperDemo/Pods/HandyJSON/HandyJSON/Deserializer.swift
5
8832
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // Created by zhouzhuo on 7/7/16. // import Foundation fileprivate func getSubObject(inside jsonObject: NSObject?, by designatedPath: String?) -> NSObject? { var nodeValue: NSObject? = jsonObject var abort = false if let paths = designatedPath?.components(separatedBy: "."), paths.count > 0 { paths.forEach({ (seg) in if seg.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" || abort { return } if let next = (nodeValue as? NSDictionary)?.object(forKey: seg) as? NSObject { nodeValue = next } else { abort = true } }) } return abort ? nil : nodeValue } extension _PropertiesMappable { static func _transform(rawPointer: UnsafeMutableRawPointer, property: Property.Description, dict: NSDictionary, mapper: HelpingMapper) { var key = property.key if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { key = key.lowercased() } let mutablePointer = rawPointer.advanced(by: property.offset) InternalLogger.logVerbose(key, "address at: ", mutablePointer.hashValue) if mapper.propertyExcluded(key: mutablePointer.hashValue) { InternalLogger.logDebug("Exclude property: \(key)") return } var maybeValue: Any? = nil if let mappingHandler = mapper.getMappingHandler(key: mutablePointer.hashValue) { if let mappingNames = mappingHandler.mappingNames, mappingNames.count > 0 { for mappingName in mappingNames { if let _value = dict[mappingName] { maybeValue = _value break } } } else { maybeValue = dict[key] } if let transformer = mappingHandler.assignmentClosure { // execute the transform closure transformer(maybeValue) return } } else { maybeValue = dict[key] } guard let rawValue = maybeValue as? NSObject else { InternalLogger.logDebug("Can not find a value from dictionary for property: \(key)") return } if let transformableType = property.type as? _JSONTransformable.Type { if let sv = transformableType.transform(from: rawValue) { extensions(of: transformableType).write(sv, to: mutablePointer) return } } else { if let sv = extensions(of: property.type).takeValue(from: rawValue) { extensions(of: property.type).write(sv, to: mutablePointer) return } } InternalLogger.logDebug("Property: \(property.key) hasn't been written in") } static func _transform(dict: NSDictionary, toType: _PropertiesMappable.Type) -> _PropertiesMappable? { var instance = toType.init() guard let properties = getProperties(forType: toType) else { InternalLogger.logDebug("Failed when try to get properties from type: \(type(of: toType))") return nil } let mapper = HelpingMapper() // do user-specified mapping first instance.mapping(mapper: mapper) let rawPointer: UnsafeMutableRawPointer if toType is AnyClass { rawPointer = UnsafeMutableRawPointer(instance.headPointerOfClass()) } else { rawPointer = UnsafeMutableRawPointer(instance.headPointerOfStruct()) } InternalLogger.logVerbose("instance start at: ", rawPointer.hashValue) var _dict = dict if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { let newDict = NSMutableDictionary() dict.allKeys.forEach({ (key) in if let sKey = key as? String { newDict[sKey.lowercased()] = dict[key] } else { newDict[key] = dict[key] } }) _dict = newDict } properties.forEach { (property) in _transform(rawPointer: rawPointer, property: property, dict: _dict, mapper: mapper) InternalLogger.logVerbose("field: ", property.key, " offset: ", property.offset) } return instance } } public extension HandyJSON { /// Finds the internal NSDictionary in `dict` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer public static func deserialize(from dict: NSDictionary?, designatedPath: String? = nil) -> Self? { return JSONDeserializer<Self>.deserializeFrom(dict: dict, designatedPath: designatedPath) } /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer public static func deserialize(from json: String?, designatedPath: String? = nil) -> Self? { return JSONDeserializer<Self>.deserializeFrom(json: json, designatedPath: designatedPath) } } public extension Array where Element: HandyJSON { /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, /// this method converts it to a Models array public static func deserialize(from json: String?, designatedPath: String? = nil) -> [Element?]? { return JSONDeserializer<Element>.deserializeModelArrayFrom(json: json, designatedPath: designatedPath) } } public class JSONDeserializer<T: HandyJSON> { /// Finds the internal NSDictionary in `dict` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil public static func deserializeFrom(dict: NSDictionary?, designatedPath: String? = nil) -> T? { var targetDict = dict if let path = designatedPath { targetDict = getSubObject(inside: targetDict, by: path) as? NSDictionary } if let _dict = targetDict { return T._transform(dict: _dict, toType: T.self) as? T } return nil } /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil public static func deserializeFrom(json: String?, designatedPath: String? = nil) -> T? { guard let _json = json else { return nil } do { let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) if let jsonDict = jsonObject as? NSDictionary { return self.deserializeFrom(dict: jsonDict, designatedPath: designatedPath) } } catch let error { InternalLogger.logError(error) } return nil } /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, /// this method converts it to a Models array public static func deserializeModelArrayFrom(json: String?, designatedPath: String? = nil) -> [T?]? { guard let _json = json else { return nil } do { let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) if let jsonArray = getSubObject(inside: jsonObject as? NSObject, by: designatedPath) as? NSArray { return jsonArray.map({ (jsonDict) -> T? in return self.deserializeFrom(dict: jsonDict as? NSDictionary) }) } } catch let error { InternalLogger.logError(error) } return nil } }
mit
3fa15706182839ece4f13fce533e7b82
39.888889
140
0.620697
4.758621
false
false
false
false
gaoleegin/SwiftLianxi
SDECollectionViewAlbumTransition-PinchPopTransition/Example/SDEAlbumViewController.swift
1
2308
// // SDEAlbumViewController.swift // Albums // // Created by seedante on 15/7/8. // Copyright © 2015年 seedante. All rights reserved. // import UIKit import Photos private let ImageIdentifier = "ImageCell" private let VideoIdentifier = "VideoCell" class SDEAlbumViewController: UICollectionViewController { var assetCollection:PHAssetCollection?{ willSet{ self.navigationItem.title = newValue!.localizedTitle let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] fetchResult = PHAsset.fetchAssetsInAssetCollection(newValue!, options: fetchOptions) } } var fetchResult:PHFetchResult?{ didSet{ self.collectionView?.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if fetchResult != nil{ return fetchResult!.count } return 0 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var identifier = ImageIdentifier let asset = fetchResult?.getAssetAtIndex(indexPath.row) switch asset!.mediaType{ case .Image: identifier = ImageIdentifier case .Video: identifier = VideoIdentifier default: identifier = ImageIdentifier } let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) if let imageView = cell.viewWithTag(-10) as? UIImageView{ fetchResult?.fetchImageAtIndex(indexPath.row, imageView: imageView, targetSize: CGSizeMake(150, 150)) } if let timeLabel = cell.viewWithTag(-30) as? UILabel{ timeLabel.text = asset!.duration.humanOutput } if identifier == VideoIdentifier{ let adaptiveCell = cell as! SDEAdaptiveAssetCell adaptiveCell.adjustLogoAndDurationLocation() } return cell } }
apache-2.0
f32e0d035e3e2b7aeed433f523ea6532
31.013889
139
0.657701
5.691358
false
false
false
false
davidtucker/WaterCooler-Demo
EnterpriseMessenger/ViewControllerExtensions.swift
1
1537
// // ViewControllerExtensions.swift // EnterpriseMessenger // // Created by David Tucker on 3/1/15. // Copyright (c) 2015 Universal Mind. All rights reserved. // import Foundation extension UIViewController { /* The following method leverages MBProgressHUD to present an indeterminite message to the user. The instance of MBProgressHUD is returned (which is required so that it can be closed when needed). */ func presentIndeterminiteMessage(message:String) -> MBProgressHUD { let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.mode = MBProgressHUDModeIndeterminate hud.labelText = message hud.dimBackground = false return hud } /* The following method leverages UIAlertController to present a message to the end user based on an NSError instance. This is a bit of a shortcut as we would usually like to put a lot more thought into how / when error messages are presented to the end user. However, for a demo application this is adequate. The message that is presented is the localizedDescription of the error. */ func presentErrorMessage(error:NSError) { let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in alert.dismissViewControllerAnimated(true, completion: nil) })) } }
mit
2226f648ee74c01faacefa54e05f29a7
37.425
114
0.688354
4.773292
false
false
false
false
leoru/Brainstorage
Brainstorage-iOS/Classes/Lib/HTMLBuilder.swift
1
1635
// // HTMLBulder.swift // Brainstorage // // Created by Kirill Kunst on 10.02.15. // Copyright (c) 2015 Kirill Kunst. All rights reserved. // import Foundation import UIKit class HTMLBuilder : NSObject { class func CSS() -> String { var css = "" css += "body {font-family: Helvetica Neue; background-color:transparent; margin: 0; margin-left: 10px; margin-right: 10px; color: #33485E; font-size: 11pt; }" css += " a { color: #EC6259; text-decoration : none; }" css += ".instructions { background: #fff8e6; color: #8e856d; margin: 20px -20px 0; padding: 20px 20px; }" css += ".instructions .title { font-weight: bold; margin-bottom: 10px; }" css += ".about { padding-bottom: 10px; }" css += ".about .subtitle { font-weight: bold; margin-top: 10px; }" css += ".about .contacts { margin-top: 10px;}" css += "" return css } class func htmlForJob(job : Job) -> String { println(job.requirements) var html : String = "" html += "<html>" html += " <head>" html += " <title></title>" html += " <style>\(self.CSS())</style></head>" html += " <body>" html += " \(job.requirements) " html += " \(job.bonuses) " html += " \(job.instructions) " html += " \(job.companyInfo) " html += " </body>" html += "</html>" return html } }
mit
bf9239006dafd8f2ca4ee2138ab6288e
37.023256
170
0.474618
3.793503
false
false
false
false
rizumita/CTFeedbackSwift
CTFeedbackSwift/Items/Attachment/Media.swift
1
829
// // Created by 和泉田 領一 on 2017/09/22. // Copyright (c) 2017 CAPH TECH. All rights reserved. // import UIKit public enum Media: Equatable { var jpegData: Data? { guard case let .image(image) = self else { return .none } return image.jpegData(compressionQuality: 0.5) } var videoData: Data? { guard case let .video(_, url) = self else { return .none } return try? Data(contentsOf: url) } case image(UIImage) case video(UIImage, URL) public static func ==(lhs: Media, rhs: Media) -> Bool { switch (lhs, rhs) { case (.image(let lImage), .image(let rImage)): return lImage == rImage case (.video(_, let lUrl), .video(_, let rUrl)): return lUrl == rUrl default: return false } } }
mit
264cf7cd41a97b65dc26540711ed6903
26.3
66
0.567766
3.809302
false
false
false
false
skladek/SKWebServiceController
Pods/Nimble/Sources/Nimble/Matchers/Async.swift
8
8358
import Foundation /// If you are running on a slower machine, it could be useful to increase the default timeout value /// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01. public struct AsyncDefaults { public static var Timeout: TimeInterval = 1 public static var PollInterval: TimeInterval = 0.01 } private func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: TimeInterval, poll: TimeInterval, fnName: String) -> Predicate<T> { return Predicate { actualExpression in let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).\(fnName)(...)" var lastPredicateResult: PredicateResult? let result = pollBlock( pollInterval: poll, timeoutInterval: timeout, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { lastPredicateResult = try predicate.satisfies(uncachedExpression) return lastPredicateResult!.toBoolean(expectation: style) } switch result { case .completed: return lastPredicateResult! case .timedOut: return PredicateResult(status: .fail, message: lastPredicateResult!.message) case let .errorThrown(error): return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>")) case let .raisedException(exception): return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)")) case .blockedRunLoop: // swiftlint:disable:next line_length return PredicateResult(status: .fail, message: lastPredicateResult!.message.appended(message: " (timed out, but main thread was unresponsive).")) case .incomplete: internalError("Reached .incomplete state for \(fnName)(...).") } } } private let toEventuallyRequiresClosureError = FailureMessage( // swiftlint:disable:next line_length stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function" ) extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toMatch, async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"), to: "to eventually", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toNotMatch, async( style: .toNotMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventuallyNot" ), to: "to eventually not", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description) } } // Deprecated extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = execute( expression, .toMatch, async( style: .toMatch, predicate: matcher.predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually" ), to: "to eventually", description: description, captureExceptions: false ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = expressionDoesNotMatch( expression, matcher: async( style: .toNotMatch, predicate: matcher.predicate, timeout: timeout, poll: pollInterval, fnName: "toEventuallyNot" ), toNot: "to eventually not", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description) } }
mit
537047e08acaa61e6c28f6c098d1d229
46.76
209
0.647523
5.455614
false
false
false
false
KaushalElsewhere/AllHandsOn
CleanSwiftTry2.3/CleanSwiftTry/Scenes/CreateOrder/CreateOrderViewController.swift
1
3706
// // CreateOrderViewController.swift // CleanSwiftTry // // Created by Kaushal Elsewhere on 10/05/2017. // Copyright (c) 2017 Elsewhere. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol CreateOrderViewControllerInput { func displayPrice(viewModel: CreateOrder_Price_ViewModel) func displaySomething(viewModel: CreateOrder.Something.ViewModel) } protocol CreateOrderViewControllerOutput { var shippingMethods: [String] { get } func calculatePrice(request: CreateOrder_Price_Request) func doSomething(request: CreateOrder.Something.Request) //func getPaymentOptions() } class CreateOrderViewController: UIViewController, CreateOrderViewControllerInput { var output: CreateOrderViewControllerOutput! var router: CreateOrderRouter! lazy var shippingTextField: UITextField = { let textField = UITextField() //textField.center = self.view.center textField.textColor = .blackColor() textField.font = UIFont(name: "HelveticaNeue", size: 20) textField.textAlignment = .Center //textField.backgroundColor = .lightGrayColor() textField.layer.cornerRadius = 4.0 textField.layer.borderWidth = 1.0 textField.layer.masksToBounds = false return textField }() var pickerView: UIPickerView = { let picker = UIPickerView() return picker }() init() { super.init(nibName: nil, bundle: nil) CreateOrderConfigurator.sharedInstance.configure(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() } func configurePicker() { pickerView.delegate = self pickerView.dataSource = self pickerView.frame = CGRect(x: 0, y: view.bounds.height-250, width: view.bounds.width, height: 250) view.addSubview(pickerView) } func setupViews() { view.backgroundColor = .whiteColor() shippingTextField.frame = CGRect(x:0, y: 0, width: 250, height: 40) shippingTextField.center = CGPoint(x: view.center.x, y: 100) view.addSubview(shippingTextField) configurePicker() setDefaultValue() } func setDefaultValue() { pickerView.selectRow(0, inComponent: 0, animated: false) let request = CreateOrder_Price_Request(selectedIndex: 0) output.calculatePrice(request) } // MARK: - Display logic func displaySomething(viewModel: CreateOrder.Something.ViewModel) { } func displayPrice(viewModel: CreateOrder_Price_ViewModel) { shippingTextField.text = viewModel.price print(viewModel.price) } } extension CreateOrderViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return output.shippingMethods.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return output.shippingMethods[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let request = CreateOrder_Price_Request(selectedIndex: row) output.calculatePrice(request) } }
mit
d81815afb03b26ac1d698a770c526fdc
30.142857
109
0.674042
4.961178
false
false
false
false
hulinSun/Better
better/Pods/SnapKit/Source/ConstraintViewDSL.swift
1
4538
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public struct ConstraintViewDSL: ConstraintAttributesDSL { @discardableResult public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { return ConstraintMaker.prepareConstraints(view: self.view, closure: closure) } public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.makeConstraints(view: self.view, closure: closure) } public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.remakeConstraints(view: self.view, closure: closure) } public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.updateConstraints(view: self.view, closure: closure) } public func removeConstraints() { ConstraintMaker.removeConstraints(view: self.view) } public var contentHuggingHorizontalPriority: Float { get { return self.view.contentHuggingPriority(for: .horizontal) } set { self.view.setContentHuggingPriority(newValue, for: .horizontal) } } public var contentHuggingVerticalPriority: Float { get { return self.view.contentHuggingPriority(for: .vertical) } set { self.view.setContentHuggingPriority(newValue, for: .vertical) } } public var contentCompressionResistanceHorizontalPriority: Float { get { return self.view.contentCompressionResistancePriority(for: .horizontal) } set { self.view.setContentHuggingPriority(newValue, for: .horizontal) } } public var contentCompressionResistanceVerticalPriority: Float { get { return self.view.contentCompressionResistancePriority(for: .vertical) } set { self.view.setContentCompressionResistancePriority(newValue, for: .vertical) } } public var target: AnyObject? { return self.view } internal let view: ConstraintView internal init(view: ConstraintView) { self.view = view } internal var constraints: [Constraint] { return self.constraintsHashTable.allObjects } internal func add(_ constraints: [Constraint]) { let hashTable = self.constraintsHashTable for constraint in constraints { hashTable.add(constraint) } } internal func remove(_ constraints: [Constraint]) { let hashTable = self.constraintsHashTable for constraint in constraints { hashTable.remove(constraint) } } fileprivate var constraintsHashTable: NSHashTable<Constraint> { let constraints: NSHashTable<Constraint> if let existing = objc_getAssociatedObject(self.view, &constraintsKey) as? NSHashTable<Constraint> { constraints = existing } else { constraints = NSHashTable<Constraint>() objc_setAssociatedObject(self.view, &constraintsKey, constraints, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraints } } private var constraintsKey: UInt8 = 0
mit
05ea4b3c9215c0dbd7df306c168df1b1
32.614815
113
0.663067
5.087444
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/01509-bool.swift
11
570
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse ance(x) { self.c] var b { } case .d<T>, U, (c == { return self.h == e? = { } for c : Sequence where f: C { func b: Int } } } protocol a { func b(Any] = "a<T) { typealias A : A {
apache-2.0
981e1cb5926a51c5748d0f535e9fe329
24.909091
78
0.677193
3.114754
false
false
false
false
romankisil/eqMac2
native/driver/Source/Helpers.swift
1
8482
// //Misc.swift //eqMac // //Created by Nodeful on 16/08/2021. //Copyright © 2021 Bitgapp. All rights reserved. // import Foundation import CoreAudio.AudioServerPlugIn // MARK: - Pure Functions func log (_ msg: String) { if DEBUG { let message = "coreaudiod: eqMac - \(msg)" NSLog(message) } } // Debug helpers func propertyName (_ property: AudioObjectPropertySelector) -> String { var props: [String] = AudioProperties.filter { $0.0 == property }.map { $0.1 } if props.count == 0 { props.append(property.code) } return "\(props.joined(separator: " | "))" } func scopeName (_ scope: AudioObjectPropertyScope) -> String { return AudioPropertyScopes[scope] ?? "Unknown" } let AudioPropertyScopes: [AudioObjectPropertyScope: String] = [ kAudioObjectPropertyScopeGlobal: "Global", kAudioObjectPropertyScopeInput: "Input", kAudioObjectPropertyScopeOutput: "Output" ] // This is a hashmap of all properties for debug loggin purposes var AudioProperties: [(AudioObjectPropertySelector, String)] = [ // Shared (kAudioObjectPropertyBaseClass, "kAudioObjectPropertyBaseClass"), (kAudioObjectPropertyClass, "kAudioObjectPropertyClass"), (kAudioObjectPropertyOwner, "kAudioObjectPropertyOwner"), (kAudioObjectPropertyName, "kAudioObjectPropertyName"), (kAudioObjectPropertyModelName, "kAudioObjectPropertyModelName"), (kAudioObjectPropertyManufacturer, "kAudioObjectPropertyManufacturer"), (kAudioObjectPropertyElementName, "kAudioObjectPropertyElementName"), (kAudioObjectPropertyElementCategoryName, "kAudioObjectPropertyElementCategoryName"), (kAudioObjectPropertyElementNumberName, "kAudioObjectPropertyElementNumberName"), (kAudioObjectPropertyOwnedObjects, "kAudioObjectPropertyOwnedObjects"), (kAudioObjectPropertyIdentify, "kAudioObjectPropertyIdentify"), (kAudioObjectPropertySerialNumber, "kAudioObjectPropertySerialNumber"), (kAudioObjectPropertyFirmwareVersion, "kAudioObjectPropertyFirmwareVersion"), (kAudioObjectPropertyCustomPropertyInfoList, "kAudioObjectPropertyCustomPropertyInfoList"), // Plug-in (kAudioPlugInPropertyBundleID, "kAudioPlugInPropertyBundleID"), (kAudioPlugInPropertyDeviceList, "kAudioPlugInPropertyDeviceList"), (kAudioPlugInPropertyTranslateUIDToDevice, "kAudioPlugInPropertyTranslateUIDToDevice"), (kAudioPlugInPropertyBoxList, "kAudioPlugInPropertyBoxList"), (kAudioPlugInPropertyTranslateUIDToBox, "kAudioPlugInPropertyTranslateUIDToBox"), (kAudioPlugInPropertyClockDeviceList, "kAudioPlugInPropertyClockDeviceList"), (kAudioPlugInPropertyTranslateUIDToClockDevice, "kAudioPlugInPropertyTranslateUIDToClockDevice"), (kAudioPlugInPropertyResourceBundle, "kAudioPlugInPropertyResourceBundle"), // Transport Manager (kAudioTransportManagerPropertyEndPointList, "kAudioTransportManagerPropertyEndPointList"), (kAudioTransportManagerPropertyTranslateUIDToEndPoint, "kAudioTransportManagerPropertyTranslateUIDToEndPoint"), (kAudioTransportManagerPropertyTransportType, "kAudioTransportManagerPropertyTransportType"), // Box (kAudioBoxPropertyBoxUID, "kAudioBoxPropertyBoxUID"), (kAudioBoxPropertyTransportType, "kAudioBoxPropertyTransportType"), (kAudioBoxPropertyHasAudio, "kAudioBoxPropertyHasAudio"), (kAudioBoxPropertyHasVideo, "kAudioBoxPropertyHasVideo"), (kAudioBoxPropertyHasMIDI, "kAudioBoxPropertyHasMIDI"), (kAudioBoxPropertyIsProtected, "kAudioBoxPropertyIsProtected"), (kAudioBoxPropertyAcquired, "kAudioBoxPropertyAcquired"), (kAudioBoxPropertyAcquisitionFailed, "kAudioBoxPropertyAcquisitionFailed"), (kAudioBoxPropertyDeviceList, "kAudioBoxPropertyDeviceList"), (kAudioBoxPropertyClockDeviceList, "kAudioBoxPropertyClockDeviceList"), // Device (kAudioDevicePropertyConfigurationApplication, "kAudioDevicePropertyConfigurationApplication"), (kAudioDevicePropertyDeviceUID, "kAudioDevicePropertyDeviceUID"), (kAudioDevicePropertyModelUID, "kAudioDevicePropertyModelUID"), (kAudioDevicePropertyTransportType, "kAudioDevicePropertyTransportType"), (kAudioDevicePropertyRelatedDevices, "kAudioDevicePropertyRelatedDevices"), (kAudioDevicePropertyClockDomain, "kAudioDevicePropertyClockDomain"), (kAudioDevicePropertyDeviceIsAlive, "kAudioDevicePropertyDeviceIsAlive"), (kAudioDevicePropertyDeviceIsRunning, "kAudioDevicePropertyDeviceIsRunning"), (kAudioDevicePropertyDeviceCanBeDefaultDevice, "kAudioDevicePropertyDeviceCanBeDefaultDevice"), (kAudioDevicePropertyDeviceCanBeDefaultSystemDevice, "kAudioDevicePropertyDeviceCanBeDefaultSystemDevice"), (kAudioDevicePropertyLatency, "kAudioDevicePropertyLatency"), (kAudioDevicePropertyStreams, "kAudioDevicePropertyStreams"), (kAudioObjectPropertyControlList, "kAudioObjectPropertyControlList"), (kAudioDevicePropertySafetyOffset, "kAudioDevicePropertySafetyOffset"), (kAudioDevicePropertyNominalSampleRate, "kAudioDevicePropertyNominalSampleRate"), (kAudioDevicePropertyAvailableNominalSampleRates, "kAudioDevicePropertyAvailableNominalSampleRates"), (kAudioDevicePropertyIcon, "kAudioDevicePropertyIcon"), (kAudioDevicePropertyIsHidden, "kAudioDevicePropertyIsHidden"), (kAudioDevicePropertyPreferredChannelsForStereo, "kAudioDevicePropertyPreferredChannelsForStereo"), (kAudioDevicePropertyPreferredChannelLayout, "kAudioDevicePropertyPreferredChannelLayout"), // Clock Device (kAudioClockDevicePropertyDeviceUID, "kAudioClockDevicePropertyDeviceUID"), (kAudioClockDevicePropertyTransportType, "kAudioClockDevicePropertyTransportType"), (kAudioClockDevicePropertyClockDomain, "kAudioClockDevicePropertyClockDomain"), (kAudioClockDevicePropertyDeviceIsAlive, "kAudioClockDevicePropertyDeviceIsAlive"), (kAudioClockDevicePropertyDeviceIsRunning, "kAudioClockDevicePropertyDeviceIsRunning"), (kAudioClockDevicePropertyLatency, "kAudioClockDevicePropertyLatency"), (kAudioClockDevicePropertyControlList, "kAudioClockDevicePropertyControlList"), (kAudioClockDevicePropertyNominalSampleRate, "kAudioClockDevicePropertyNominalSampleRate"), (kAudioClockDevicePropertyAvailableNominalSampleRates, "kAudioClockDevicePropertyAvailableNominalSampleRates"), // End Point Device (kAudioEndPointDevicePropertyComposition, "kAudioEndPointDevicePropertyComposition"), (kAudioEndPointDevicePropertyEndPointList, "kAudioEndPointDevicePropertyEndPointList"), (kAudioEndPointDevicePropertyIsPrivate, "kAudioEndPointDevicePropertyIsPrivate"), // Stream (kAudioStreamPropertyIsActive, "kAudioStreamPropertyIsActive"), (kAudioStreamPropertyDirection, "kAudioStreamPropertyDirection"), (kAudioStreamPropertyTerminalType, "kAudioStreamPropertyTerminalType"), (kAudioStreamPropertyStartingChannel, "kAudioStreamPropertyStartingChannel"), (kAudioStreamPropertyLatency, "kAudioStreamPropertyLatency"), (kAudioStreamPropertyVirtualFormat, "kAudioStreamPropertyVirtualFormat"), (kAudioStreamPropertyAvailableVirtualFormats, "kAudioStreamPropertyAvailableVirtualFormats"), (kAudioStreamPropertyPhysicalFormat, "kAudioStreamPropertyPhysicalFormat"), (kAudioStreamPropertyAvailablePhysicalFormats, "kAudioStreamPropertyAvailablePhysicalFormats"), // Control (kAudioControlPropertyScope, "kAudioControlPropertyScope"), (kAudioControlPropertyElement, "kAudioControlPropertyElement"), (kAudioSliderControlPropertyValue, "kAudioSliderControlPropertyValue"), (kAudioSliderControlPropertyRange, "kAudioSliderControlPropertyRange"), (kAudioLevelControlPropertyScalarValue, "kAudioLevelControlPropertyScalarValue"), (kAudioLevelControlPropertyDecibelValue, "kAudioLevelControlPropertyDecibelValue"), (kAudioLevelControlPropertyDecibelRange, "kAudioLevelControlPropertyDecibelRange"), (kAudioLevelControlPropertyConvertScalarToDecibels, "kAudioLevelControlPropertyConvertScalarToDecibels"), (kAudioLevelControlPropertyConvertDecibelsToScalar, "kAudioLevelControlPropertyConvertDecibelsToScalar"), (kAudioBooleanControlPropertyValue, "kAudioBooleanControlPropertyValue"), (kAudioSelectorControlPropertyCurrentItem, "kAudioSelectorControlPropertyCurrentItem"), (kAudioSelectorControlPropertyAvailableItems, "kAudioSelectorControlPropertyAvailableItems"), (kAudioSelectorControlPropertyItemName, "kAudioSelectorControlPropertyItemName"), (kAudioSelectorControlPropertyItemKind, "kAudioSelectorControlPropertyItemKind"), (kAudioStereoPanControlPropertyValue, "kAudioStereoPanControlPropertyValue"), (kAudioStereoPanControlPropertyPanningChannels, "kAudioStereoPanControlPropertyPanningChannels") ]
mit
7baed1f1dd75295496d56f99599efae3
55.919463
113
0.849074
4.896651
false
false
false
false
mlilback/rc2SwiftClient
MacClient/session/TextViewWithContextualMenu.swift
1
3146
// // TextViewWithContextualMenu.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import AppKit @objc protocol TextViewMenuDelegate: NSObjectProtocol { func additionalContextMenuItems() -> [NSMenuItem]? } ///common base class for NSTextView that supports a customized contextual menu. Used for editor and console. class TextViewWithContextualMenu: NSTextView { @IBOutlet weak var menuDelegate: TextViewMenuDelegate? @IBOutlet var textFinder: NSTextFinder! override func awakeFromNib() { super.awakeFromNib() textFinder = NSTextFinder() textFinder.findBarContainer = self.enclosingScrollView usesFindBar = true } override func menu(for event: NSEvent) -> NSMenu? { let defaultMenu = super.menu(for: event) let menu = NSMenu(title: "") //debugging code to show what items are in the default contextual menu //for anItem in (defaultMenu?.items)! { // let targetd = (anItem.target as? NSObject)?.description ?? "" // os_log("context item %{public}@ = %{public}@.%{public}@ (%{public}@)", log: .app, type: .info, anItem.title, targetd, anItem.action?.description ?? "<noaction>", anItem.tag) //} //add items for subclass if let otherItems = menuDelegate?.additionalContextMenuItems(), otherItems.count > 0 { otherItems.forEach { menu.addItem($0) } menu.addItem(NSMenuItem.separator()) } //copy look up xxx and search with Google menu items if let lookupItem = defaultMenu?.items.first(where: { $0.title.hasPrefix("Look Up") }) { menu.addItem(copyMenuItem(lookupItem)) if let searchItem = defaultMenu?.items.first(where: { $0.title.hasPrefix("Search with") }) { menu.addItem(copyMenuItem(searchItem)) } menu.addItem(NSMenuItem.separator()) } let preEditCount = menu.items.count //add the cut/copy/paste menu items if self.isEditable, let item = defaultMenu?.itemWithAction(#selector(NSText.cut(_:)), recursive: false) { menu.addItem(copyMenuItem(item)) } if let item = defaultMenu?.itemWithAction(#selector(NSText.copy(_:)), recursive: false) { menu.addItem(copyMenuItem(item)) } if let item = defaultMenu?.itemWithAction(#selector(NSText.paste(_:)), recursive: false) { menu.addItem(copyMenuItem(item)) } if menu.items.count > preEditCount { menu.addItem(NSMenuItem.separator()) } //add our font and size menus if let fontItem = NSApp.mainMenu?.itemWithAction(#selector(ManageFontMenu.showFonts(_:)), recursive: true) { menu.addItem(copyMenuItem(fontItem)) } if let sizeItem = NSApp.mainMenu?.itemWithAction(#selector(ManageFontMenu.showFontSizes(_:)), recursive: true) { sizeItem.title = NSLocalizedString("Font Size", comment: "") menu.addItem(copyMenuItem(sizeItem)) } //add speak menu if there if let speak = defaultMenu?.itemWithAction(#selector(NSTextView.startSpeaking(_:)), recursive: true) { menu.addItem(NSMenuItem.separator()) menu.addItem(copyMenuItem(speak.parent!)) } return menu } // only need to force_cast it once private func copyMenuItem(_ item: NSMenuItem) -> NSMenuItem { return item.copy() as! NSMenuItem // swiftlint:disable:this force_cast } }
isc
f91381243dfd1cb62dddefb267014898
38.3125
178
0.722099
3.678363
false
false
false
false
temoki/Exift
exift/ViewController.swift
1
7218
// // Created by temoki on 2015/11/01. // Copyright (c) 2015 temoki. All rights reserved. // import Cocoa class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSComboBoxDelegate, FileDragAndDropViewDelegate { @IBOutlet private var dateCheck: NSButton! @IBOutlet private var timeCheck: NSButton! @IBOutlet private var datePicker: NSDatePicker! @IBOutlet private var timePicker: NSDatePicker! @IBOutlet private var applyButton: NSButton! @IBOutlet private var fileDandDView: FileDragAndDropView! @IBOutlet private var tableView: NSTableView! private let kFilePath: NSString = "FilePath" private let kDateTimeOriginal: NSString = "DateTimeOriginal" private var tableRowDataArray = NSMutableArray() // NSMutableArray<NSMutableDictionary<NSUserInterfaceItemIdentifier, String>> override func viewDidLoad() { super.viewDidLoad() fileDandDView.delegate = self datePicker.timeZone = TimeZone(secondsFromGMT: 0) timePicker.timeZone = TimeZone(secondsFromGMT: 0) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: - NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { return tableRowDataArray.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { if let tableColumn = tableColumn { return (tableRowDataArray.object(at: row) as? NSDictionary)?.object(forKey: tableColumn.identifier) } return nil } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { tableRowDataArray.sort(using: tableView.sortDescriptors) tableView.reloadData() } // MARK: NSTableViewDelegate func tableViewSelectionDidChange(_ notification: Notification) { applyButton.isEnabled = tableView.selectedRowIndexes.count > 0 } // MARK: - FileDragAndDropViewDelegate func filesDropped(_ filePaths: [String]) { tableView.deselectAll(self) tableRowDataArray.removeAllObjects() let fileManager = FileManager.default for filePath in filePaths { var isDirectory = ObjCBool(true) let fileExists = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) if !fileExists || isDirectory.boolValue { continue } let ext = (filePath as NSString).pathExtension.lowercased() if !(ext == "jpg" || ext == "jpeg" || ext == "tif" || ext == "tiff") { continue } let tableRowData = NSMutableDictionary() tableRowData.setObject(filePath, forKey: kFilePath) tableRowData.setObject("", forKey: kDateTimeOriginal) tableRowDataArray.add(tableRowData) } reloadExifData() } // MARK: - Action @IBAction func applyButtonAction(_ sender: NSButton) { saveExifDataWithDateTime() //saveExifDataWithOffset() } @IBAction func dateCheckAction(_ sender: NSButton) { self.datePicker.isEnabled = (sender.state == .on) } @IBAction func timeCheckAction(_ sender: NSButton) { self.timePicker.isEnabled = (sender.state == .on) } // MARK: - Private private func reloadExifData() { for tableRowData in tableRowDataArray { guard let tableRowData = tableRowData as? NSMutableDictionary else { continue } tableRowData.setObject("", forKey: kDateTimeOriginal) guard let filePath = tableRowData.object(forKey: kFilePath) as? String else { continue } guard let exifDateTime = ExifDateTimeIO.readImageExifDateTime(filePath) else { continue } tableRowData.setObject(exifDateTime, forKey: kDateTimeOriginal) } tableView.reloadData() } private func saveExifDataWithDateTime() { var dateStr: String? = nil if dateCheck.state == .on { let dateFormatter = DateFormatter() dateFormatter.timeZone = datePicker.timeZone dateFormatter.locale = datePicker.locale dateFormatter.dateFormat = "yyyy:MM:dd" dateStr = dateFormatter.string(from: datePicker.dateValue) } var timeStr: String? = nil if timeCheck.state == .on { let timeFormatter = DateFormatter() timeFormatter.timeZone = timePicker.timeZone timeFormatter.locale = timePicker.locale timeFormatter.dateFormat = "HH:mm:ss" timeStr = timeFormatter.string(from: timePicker.dateValue) } for rowIndex in tableView.selectedRowIndexes { guard let tableRowData = tableRowDataArray.object(at: rowIndex) as? NSDictionary else { continue } guard let filePath = tableRowData.object(forKey: kFilePath) as? String else { continue } ExifDateTimeIO.writeImageExifDateTime(filePath, dateStr: dateStr, timeStr: timeStr) } reloadExifData() } // TODO: 中途半端 private func saveExifDataWithOffset() { let offset = timePicker.dateValue.timeIntervalSince1970 let dateTimeFormatter = DateFormatter() dateTimeFormatter.timeZone = timePicker.timeZone dateTimeFormatter.locale = timePicker.locale dateTimeFormatter.dateFormat = "yyyy:MM:dd HH:mm:ss" let dateFormatter = DateFormatter() dateFormatter.timeZone = timePicker.timeZone dateFormatter.locale = timePicker.locale dateFormatter.dateFormat = "yyyy:MM:dd" let timeFormatter = DateFormatter() timeFormatter.timeZone = timePicker.timeZone timeFormatter.locale = timePicker.locale timeFormatter.dateFormat = "HH:mm:ss" for rowIndex in tableView.selectedRowIndexes { guard let tableRowData = tableRowDataArray.object(at: rowIndex) as? NSDictionary else { continue } guard let dateTimeStr = tableRowData.object(forKey: kDateTimeOriginal) as? String else { continue } guard let dateTime = dateTimeFormatter.date(from: dateTimeStr) else { continue } let newDateTime = dateTime.addingTimeInterval(offset) let newDateStr = dateFormatter.string(from: newDateTime) let newTimeStr = timeFormatter.string(from: newDateTime) guard let filePath = tableRowData.object(forKey: kFilePath) as? String else { continue } ExifDateTimeIO.writeImageExifDateTime(filePath, dateStr: newDateStr, timeStr: newTimeStr) } reloadExifData() } }
mit
51e26610c87e206e2f663bd816fb57b0
34
133
0.622191
5.433308
false
false
false
false
zhouxj6112/ARKit
ARHome/ARHome/Virtual Objects/VirtualObjectLoader.swift
1
8211
/* See LICENSE folder for this sample’s licensing information. Abstract: A type which loads and tracks virtual objects. */ import Foundation import ARKit import SwiftyJSON /** Loads multiple `VirtualObject`s on a background queue to be able to display the objects quickly once they are needed. */ class VirtualObjectLoader { // 单例模式 static let `default` = VirtualObjectLoader() /// 已经加载过的模型数组 private(set) var loadedObjects = [VirtualObject]() private(set) var isLoading = false private(set) var isRelease = false // 整体缩放比例 (所有模型统一缩放) private(set) var globalScale:Float = 1.000000 // 当前选中模型 public var selectedObject:VirtualObject?; /// 模型选中后底部选中标示 (跟随选中模型的,并且当前永远只有一个) public lazy var selectionModel:VirtualObject = { let modelURL = Bundle.main.url(forResource: "Models.scnassets/selection/selection.scn", withExtension: nil)! let obj = VirtualObject(url: modelURL)! DispatchQueue.global(qos: .userInitiated).async { obj.reset() obj.load() } if !loadedObjects.contains(obj) { loadedObjects.insert(obj, at: 0) } return obj }() // MARK: - Loading object /** Loads a `VirtualObject` on a background queue. `loadedHandler` is invoked on a background queue once `object` has been loaded. */ func loadVirtualObject(_ objectFileUrl: URL, loadedHandler: @escaping (VirtualObject?, VirtualObject?) -> Void) { if (objectFileUrl.isFileURL) { isLoading = true; let obj = VirtualObject.init(url: objectFileUrl) // Load the content asynchronously. DispatchQueue.global(qos: .userInitiated).async { obj?.reset() obj?.load() obj?.isShadowObj = false self.isLoading = false /// loadedHandler(obj, nil) } return; } // 加载网络模型 isLoading = true let urlString = objectFileUrl.absoluteString // zip文件下载url(已经处理过中文的了) NetworkingHelper.download(url: urlString, parameters: nil) { (fileUrl:JSON?, error:NSError?) in if self.isRelease { return; } if error != nil { self.isLoading = false loadedHandler(nil, nil) return; } let respData = fileUrl!["data"] let filePath = respData["file"] let localFilePath = filePath.stringValue // 注意路径中包含中文的问题 let enFilePath = localFilePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let en = enFilePath?.replacingOccurrences(of: "%25", with: "%") // 很是奇怪,为什么会多了25 let url = URL.init(string: en!) let object = VirtualObject.init(url: url!) let obj = object! as VirtualObject // obj.simdScale = float3(self.globalScale, self.globalScale, self.globalScale); debugPrint("本地模型: \(obj)") self.loadedObjects.append(obj) let zipFileUrl = urlString.removingPercentEncoding // 将中文编码转换回去,存储原始数据 obj.zipFileUrl = zipFileUrl! // 加载阴影模型 var shadowObj = VirtualObject() let shadowPath = respData["shadow"] let sLocalFilePath = shadowPath.stringValue // 注意路径中包含中文的问题 if sLocalFilePath.count > 0 { let enFilePath = sLocalFilePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let en = enFilePath?.replacingOccurrences(of: "%25", with: "%") // 很是奇怪,为什么会多了25 let sUrl = URL.init(string: en!) let sObject = VirtualObject.init(url: sUrl!) let sObj = sObject! as VirtualObject // sObj.simdScale = float3(self.globalScale, self.globalScale, self.globalScale); debugPrint("阴影模型: \(sObj)") self.loadedObjects.append(sObj) sObj.zipFileUrl = zipFileUrl! // 保持跟主模型文件一致 shadowObj = sObj // obj.shadowObject = shadowObj } else { obj.shadowObject = nil } // Load the content asynchronously. DispatchQueue.global(qos: .userInitiated).async { obj.reset() obj.load() obj.isShadowObj = false self.isLoading = false // shadowObj.reset() shadowObj.load() shadowObj.isShadowObj = true /// 回调通知外部 loadedHandler(obj, shadowObj) } } } // MARK: - Removing Objects func removeAllVirtualObjects() { // Reverse the indicies so we don't trample over indicies as objects are removed. for index in loadedObjects.indices.reversed() { if index == 0 { // selectionModel不能删除了 let obj = loadedObjects[index] obj.isHidden = true continue; } removeVirtualObject(at: index) } } private func removeVirtualObject(at index: Int) { guard loadedObjects.indices.contains(index) else { return } // loadedObjects.remove(at: index) } public func removeSelectedObject() { if self.selectedObject == nil { return } for index in loadedObjects.indices.reversed() { let obj = loadedObjects[index] if obj == self.selectedObject { removeVirtualObject(at: index) break } } // removeSelectionObject() } /// 移除选中效果的底部圆圈 public func removeSelectionObject() { selectedObject = nil self.selectionModel.isHidden = true } public func resetSelectionObject(_ object:VirtualObject?) { debugPrint("selectionModel: \(selectionModel)") self.selectedObject = object // 模型抖动动画效果 object?.startShakeInSelection() self.selectionModel.isHidden = false if ((object?.shadowObject) != nil) { self.selectionModel.simdPosition = (object?.shadowObject?.simdPosition)! //// // 等比缩放选中框 (按照阴影模型大小等大) //// let shadowObj = object?.shadowObject; //// let fScale = (shadowObj?.boundingBox.max.x)! / self.selectionModel.boundingBox.max.x * 1.2; //// self.selectionModel.simdScale = float3(fScale, fScale, 1); } else { self.selectionModel.simdPosition = (object?.beforShakePosition)!; //// // 等比缩放选中框 (按照模型自身大小等大) //// let fScale = (object?.boundingBox.max.x)! / self.selectionModel.boundingBox.max.x * 1.2; //// self.selectionModel.simdScale = float3(fScale, fScale, 1); } } func release() { isRelease = true } // 析构函数 deinit { debugPrint("VirtualObjectLoader释放") } /// Loads all the model objects within `Models.scnassets`. static let availableObjectUrls: [URL] = { let modelsURL = Bundle.main.url(forResource: "LocalTest.scnassets", withExtension: nil)! let fileEnumerator = FileManager().enumerator(at: modelsURL, includingPropertiesForKeys: [])! // return fileEnumerator.compactMap { element in let url = element as! URL // guard url.pathExtension=="scn"||url.pathExtension=="obj"||url.pathExtension=="dae"||url.pathExtension=="DAE" else { return nil } return url; } }( ); }
apache-2.0
52865fdec176897c676af8546eba21df
34.654378
127
0.568696
4.569994
false
false
false
false
mcudich/TemplateKit
Examples/TodoMVC/Source/ViewController.swift
1
1225
// // ViewController.swift // Example // // Created by Matias Cudich on 8/7/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import UIKit import TemplateKit class ViewController: UIViewController, Context { lazy var templateService: TemplateService = { let templateService = XMLTemplateService(liveReload: false) templateService.cachePolicy = .never return templateService }() var updateQueue: DispatchQueue { return UIKitRenderer.defaultContext.updateQueue } private var app: App? override func viewDidLoad() { super.viewDidLoad() var properties = AppProperties() properties.core.layout.width = Float(view.bounds.size.width) properties.core.layout.height = Float(view.bounds.size.height) properties.model = Todos() let templateURLs = [ App.headerTemplateURL, Footer.templateURL, Todo.templateURL ] NodeRegistry.shared.registerComponent(CountText.self, CountTextProperties.self) templateService.fetchTemplates(withURLs: templateURLs) { result in UIKitRenderer.render(component(App.self, properties), container: self.view, context: self) { component in self.app = component as? App } } } }
mit
caf2e1ecd9a1f82e27eee77a21c8dc44
25.042553
111
0.716503
4.22069
false
false
false
false
iOS-mamu/SS
P/Potatso/ProxyListViewController.swift
1
3797
// // ProxyListViewController.swift // Potatso // // Created by LEI on 5/31/16. // Copyright © 2016 TouchingApp. All rights reserved. // import Foundation import PotatsoModel import Cartography import Eureka private let rowHeight: CGFloat = 107 private let kProxyCellIdentifier = "proxy" class ProxyListViewController: FormViewController { var proxies: [Proxy?] = [] let allowNone: Bool let chooseCallback: ((Proxy?) -> Void)? init(allowNone: Bool = false, chooseCallback: ((Proxy?) -> Void)? = nil) { self.chooseCallback = chooseCallback self.allowNone = allowNone super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.title = "Proxy".localized() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) reloadData() } func add() { let vc = ProxyConfigurationViewController() navigationController?.pushViewController(vc, animated: true) } func reloadData() { proxies = DBUtils.allNotDeleted(Proxy.self, sorted: "createAt").map({ $0 }) if allowNone { proxies.insert(nil, at: 0) } form.delegate = nil form.removeAll() let section = Section() for proxy in proxies { section <<< ProxyRow () { $0.value = proxy }.cellSetup({ (cell, row) -> () in cell.selectionStyle = .none }).onCellSelection({ [unowned self] (cell, row) in cell.setSelected(false, animated: true) let proxy = row.value if let cb = self.chooseCallback { cb(proxy) self.close() }else { if proxy?.type != .none { self.showProxyConfiguration(proxy) } } }) } form +++ section form.delegate = self tableView?.reloadData() } func showProxyConfiguration(_ proxy: Proxy?) { let vc = ProxyConfigurationViewController(upstreamProxy: proxy) navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool { if allowNone && indexPath.row == 0 { return false } return true } func tableView(_ tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) { if editingStyle == .delete { guard indexPath.row < proxies.count, let item = (form[indexPath] as? ProxyRow)?.value else { return } do { try DBUtils.softDelete(item.uuid, type: Proxy.self) proxies.remove(at: indexPath.row) form[indexPath].hidden = true form[indexPath].evaluateHidden() }catch { self.showTextHUD("\("Fail to delete item".localized()): \((error as NSError).localizedDescription)", dismissAfterDelay: 1.5) } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView?.tableFooterView = UIView() tableView?.tableHeaderView = UIView() } }
mit
657cd1d4a73b53e3dfdd11a5f03526ae
32.008696
148
0.580348
5.207133
false
false
false
false
keithito/SimpleAnimation
Source/UIView+SimpleAnimation.swift
1
15801
// // UIView+SimpleAnimation.swift // SimpleAnimation.swift // // Created by Keith Ito on 4/19/16. // import UIKit /** Edge of the view's parent that the animation should involve - none: involves no edge - top: involves the top edge of the parent - bottom: involves the bottom edge of the parent - left: involves the left edge of the parent - right: involves the right edge of the parent */ public enum SimpleAnimationEdge { case none case top case bottom case left case right } /** A UIView extension that makes adding basic animations, like fades and bounces, simple. */ public extension UIView { /** Fades this view in. This method can be chained with other animations to combine a fade with the other animation, for instance: ``` view.fadeIn().slideIn(from: .left) ``` - Parameters: - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeIn(duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { isHidden = false alpha = 0 UIView.animate( withDuration: duration, delay: delay, options: .curveEaseInOut, animations: { self.alpha = 1 }, completion: completion) return self } /** Fades this view out. This method can be chained with other animations to combine a fade with the other animation, for instance: ``` view.fadeOut().slideOut(to: .right) ``` - Parameters: - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeOut(duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { UIView.animate( withDuration: duration, delay: delay, options: .curveEaseOut, animations: { self.alpha = 0 }, completion: completion) return self } /** Fades the background color of a view from existing bg color to a specified color without using alpha values. - Parameters: - toColor: the final color you want to fade to - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeColor(toColor: UIColor = UIColor.red, duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { UIView.animate( withDuration: duration, delay: delay, options: .curveEaseIn, animations: { self.backgroundColor = toColor }, completion: completion) return self } /** Slides this view into position, from an edge of the parent (if "from" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - from: edge of the parent view that should be used as the starting point of the animation - x: horizontal offset that should be used for the starting point of the animation - y: vertical offset that should be used for the starting point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func slideIn(from edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.4, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) transform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) isHidden = false UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 1, initialSpringVelocity: 2, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Slides this view out of its position, toward an edge of the parent (if "to" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - to: edge of the parent view that should be used as the ending point of the animation - x: horizontal offset that should be used for the ending point of the animation - y: vertical offset that should be used for the ending point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func slideOut(to edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) let endTransform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) UIView.animate( withDuration: duration, delay: delay, options: .curveEaseOut, animations: { self.transform = endTransform }, completion: completion) return self } /** Moves this view into position, with a bounce at the end, either from an edge of the parent (if "from" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - from: edge of the parent view that should be used as the starting point of the animation - x: horizontal offset that should be used for the starting point of the animation - y: vertical offset that should be used for the starting point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func bounceIn(from edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.5, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) transform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) isHidden = false UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 0.58, initialSpringVelocity: 3, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Moves this view out of its position, starting with a bounce. The view moves toward an edge of the parent (if "to" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - to: edge of the parent view that should be used as the ending point of the animation - x: horizontal offset that should be used for the ending point of the animation - y: vertical offset that should be used for the ending point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func bounceOut(to edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.35, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) let delta = CGPoint(x: offset.x + x, y: offset.y + y) let endTransform = CGAffineTransform(translationX: delta.x, y: delta.y) let prepareTransform = CGAffineTransform(translationX: -delta.x * 0.2, y: -delta.y * 0.2) UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.6) { self.transform = endTransform } }, completion: completion) return self } /** Moves this view into position, as though it were popping out of the screen. - Parameters: - fromScale: starting scale for the view, should be between 0 and 1 - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func popIn(fromScale: CGFloat = 0.5, duration: TimeInterval = 0.5, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { isHidden = false alpha = 0 transform = CGAffineTransform(scaleX: fromScale, y: fromScale) UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 0.55, initialSpringVelocity: 3, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Moves this view out of position, as though it were withdrawing into the screen. - Parameters: - toScale: ending scale for the view, should be between 0 and 1 - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func popOut(toScale: CGFloat = 0.5, duration: TimeInterval = 0.3, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let endTransform = CGAffineTransform(scaleX: toScale, y: toScale) let prepareTransform = CGAffineTransform(scaleX: 1.1, y: 1.1) UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.3) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) { self.transform = endTransform self.alpha = 0 } }, completion: completion) return self } /** Causes the view to hop, either toward a particular edge or out of the screen (if "toward" is .None). - Parameters: - toward: the edge to hop toward, or .None to hop out - amount: distance to hop, expressed as a fraction of the view's size - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func hop(toward edge: SimpleAnimationEdge = .none, amount: CGFloat = 0.4, duration: TimeInterval = 0.6, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { var dx: CGFloat = 0, dy: CGFloat = 0, ds: CGFloat = 0 if edge == .none { ds = amount / 2 } else if edge == .left || edge == .right { dx = (edge == .left ? -1 : 1) * self.bounds.size.width * amount; dy = 0 } else { dx = 0 dy = (edge == .top ? -1 : 1) * self.bounds.size.height * amount; } UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeLinear, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.28) { let t = CGAffineTransform(translationX: dx, y: dy) self.transform = t.scaledBy(x: 1 + ds, y: 1 + ds) } UIView.addKeyframe(withRelativeStartTime: 0.28, relativeDuration: 0.28) { self.transform = .identity } UIView.addKeyframe(withRelativeStartTime: 0.56, relativeDuration: 0.28) { let t = CGAffineTransform(translationX: dx * 0.5, y: dy * 0.5) self.transform = t.scaledBy(x: 1 + ds * 0.5, y: 1 + ds * 0.5) } UIView.addKeyframe(withRelativeStartTime: 0.84, relativeDuration: 0.16) { self.transform = .identity } }, completion: completion) return self } /** Causes the view to shake, either toward a particular edge or in all directions (if "toward" is .None). - Parameters: - toward: the edge to shake toward, or .None to shake in all directions - amount: distance to shake, expressed as a fraction of the view's size - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func shake(toward edge: SimpleAnimationEdge = .none, amount: CGFloat = 0.15, duration: TimeInterval = 0.6, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let steps = 8 let timeStep = 1.0 / Double(steps) var dx: CGFloat, dy: CGFloat if edge == .left || edge == .right { dx = (edge == .left ? -1 : 1) * self.bounds.size.width * amount; dy = 0 } else { dx = 0 dy = (edge == .top ? -1 : 1) * self.bounds.size.height * amount; } UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { var start = 0.0 for i in 0..<(steps - 1) { UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: timeStep) { self.transform = CGAffineTransform(translationX: dx, y: dy) } if (edge == .none && i % 2 == 0) { swap(&dx, &dy) // Change direction dy *= -1 } dx *= -0.85 dy *= -0.85 start += timeStep } UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: timeStep) { self.transform = .identity } }, completion: completion) return self } private func offsetFor(edge: SimpleAnimationEdge) -> CGPoint { if let parentSize = self.superview?.frame.size { switch edge { case .none: return CGPoint.zero case .top: return CGPoint(x: 0, y: -frame.maxY) case .bottom: return CGPoint(x: 0, y: parentSize.height - frame.minY) case .left: return CGPoint(x: -frame.maxX, y: 0) case .right: return CGPoint(x: parentSize.width - frame.minX, y: 0) } } return .zero } }
mit
f7f424ec8f73d315ce7a6dc571de377a
41.36193
111
0.603633
4.613431
false
false
false
false
SwiftKit/Cuckoo
Generator/Source/CuckooGeneratorFramework/Tokens/FileRepresentation.swift
1
2330
// // FileRepresentation.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // import SourceKittenFramework public struct FileRepresentation { public let sourceFile: File public let declarations: [Token] public init(sourceFile: File, declarations: [Token]) { self.sourceFile = sourceFile self.declarations = declarations } } public extension FileRepresentation { func mergeInheritance(with files: [FileRepresentation]) -> FileRepresentation { let tokens = self.declarations.reduce([Token]()) { list, token in let mergeToken = token.mergeInheritance(with: files) return list + [mergeToken] } return FileRepresentation(sourceFile: self.sourceFile, declarations: tokens) } } extension Token { func mergeInheritance(with files: [FileRepresentation]) -> Token { guard let typeToken = self as? ContainerToken else { return self } let inheritedRepresentations: [Token] = typeToken.inheritedTypes .compactMap { Self.findToken(forClassOrProtocol: $0.name, in: files) } .compactMap { $0.mergeInheritance(with: files) } // Merge super declarations let mergedTokens = inheritedRepresentations.filter { $0.isClassOrProtocolDeclaration } .map { $0 as! ContainerToken } .flatMap { $0.children } .reduce(typeToken.children) { tokens, inheritedToken in if tokens.contains(where: { $0 == inheritedToken }) { return tokens } return tokens + [inheritedToken] } switch typeToken { case let classToken as ClassDeclaration: return classToken.replace(children: mergedTokens) case let protocolToken as ProtocolDeclaration: return protocolToken.replace(children: mergedTokens) default: return typeToken } } static func findToken(forClassOrProtocol name: String, in files: [FileRepresentation]) -> Token? { return files.flatMap { $0.declarations } .filter { $0.isClassOrProtocolDeclaration } .map { $0 as! ContainerToken } .first { $0.name == name } } }
mit
b0f7f4eceb81fa7a8511377ee0b77e33
33.25
102
0.630743
4.762781
false
false
false
false
pawanpoudel/AppMenu
AppMenuTests/Common/AppDelegateTests.swift
1
3164
// // AppDelegateTests.swift // AppMenu // // Created by Pawan Poudel on 9/1/14. // Copyright (c) 2014 Pawan Poudel. All rights reserved. // import UIKit import XCTest class FakeAppMenuManager: AppMenuManager { override func menuViewController() -> MenuViewController? { return MenuViewController() } } class FakeObjectConfigurator : ObjectConfigurator { override func appMenuManager() -> AppMenuManager { return FakeAppMenuManager() } } class AppDelegateTests: XCTestCase { var window: UIWindow? var navController: UINavigationController? var appDelegate: AppDelegate? var objectConfigurator: ObjectConfigurator? var didFinishLaunchingWithOptionsReturnValue: Bool? override func setUp() { super.setUp() window = UIWindow() navController = UINavigationController() appDelegate = AppDelegate() appDelegate?.window = window appDelegate?.navController = navController } func testRootVCForWindowIsNotSetIfMenuViewControllerCannotBeCreated() { class FakeAppMenuManager: AppMenuManager { override func menuViewController() -> MenuViewController? { return nil } } class FakeObjectConfigurator : ObjectConfigurator { override func appMenuManager() -> AppMenuManager { return FakeAppMenuManager() } } appDelegate?.objectConfigurator = FakeObjectConfigurator() appDelegate?.application(nil, didFinishLaunchingWithOptions: nil) XCTAssertNil(window!.rootViewController, "Window's root view controller shouldn't be set if menu view controller can't be created") } func testWindowHasRootViewControllerIfMenuViewControllerIsCreated() { appDelegate?.objectConfigurator = FakeObjectConfigurator() appDelegate?.application(nil, didFinishLaunchingWithOptions: nil) XCTAssertEqual(window!.rootViewController, navController!, "App delegate's nav controller should be the root view controller") } func testMenuViewControllerIsRootVCForNavigationController() { appDelegate?.objectConfigurator = FakeObjectConfigurator() appDelegate?.application(nil, didFinishLaunchingWithOptions: nil) let topViewController = appDelegate?.navController?.topViewController XCTAssertTrue(topViewController is MenuViewController, "Menu view controlelr is root VC for nav controller") } func testWindowIsKeyAfterAppIsLaunched() { appDelegate?.application(nil, didFinishLaunchingWithOptions: nil) XCTAssertTrue(window!.keyWindow, "App delegate's window should be the key window for the app") } func testAppDidFinishLaunchingDelegateMethodAlwaysReturnsTrue() { didFinishLaunchingWithOptionsReturnValue = appDelegate?.application(nil, didFinishLaunchingWithOptions: nil) XCTAssertTrue(didFinishLaunchingWithOptionsReturnValue!, "Did finish launching delegate method should return true") } }
mit
823547ad2699069cac7adc599c5125e4
34.550562
102
0.69469
6.015209
false
true
false
false
Chaatz/SocketIOChatClient
Example/Tests/Tests.swift
1
1185
// https://github.com/Quick/Quick import Quick import Nimble import SocketIOChatClient class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
d79cd9d26cf084bc946c75cf7cad9e3b
22.58
63
0.368109
5.509346
false
false
false
false
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Pages/Custom Sequences Challenge.xcplaygroundpage/Contents.swift
1
1629
//: [Previous](@previous) import UIKit import PlaygroundSupport // Challenge // // Uncomment out run below and look at the view to see the balls // bouncing around. // Modify Arena.swift and add an implementation for handle collisions. // You will want to use the pairs() operation to compare each pair // of the balls. The Ball class has an overlaps(_ other:) method // to determine if two balls touch and a collide method to do the // appropriate collision handling. // // Arena.swift can be found in the compiled sources by showing the // navigator and then opening the Sources folder. func run() { let size = CGSize(width: 400, height: 400) let colors: [UIColor] = [.red, .green, .blue, .orange, .yellow] let radius: CGFloat = 20 var balls: [Ball] = [] for _ in 1...10 { let randomX = (radius...(size.width-radius)).random let randomY = (radius...(size.height-radius)).random let position = CGPoint(x: randomX, y: randomY) let randomVelocity = CGFloat(-15) ... CGFloat(15) let velocity = CGPoint(x: randomVelocity.random, y: randomVelocity.random ) let color = colors.random let ball = Ball(position: position, velocity: velocity, color: color, radius: radius) balls.append(ball) } var arena = Arena(size: size, balls: balls) let view = CircleRenderView(frame: CGRect(origin: .zero, size: size)) for _ in 1 ... 1000 { arena.simulationStep() view.circles = arena.balls.map { return Circle(position: $0.position, radius: $0.radius, color: $0.color) } // Poke the eye to see the view view } } // Comment the run() function back in to watch it go. run() //: [Next](@next)
mit
a0748372ec37dbcdb9c941211b0a41dd
28.618182
87
0.691835
3.443975
false
false
false
false
lhc70000/iina
iina/SleepPreventer.swift
2
1145
// // SleepPreventer.swift // iina // // Created by lhc on 6/1/2017. // Copyright © 2017 lhc. All rights reserved. // import IOKit.pwr_mgt class SleepPreventer: NSObject { static private let reason = "IINA is playing video" as CFString static private var assertionID = IOPMAssertionID() static private var preventedSleep = false static func preventSleep() { if preventedSleep { return } let success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep as NSString, IOPMAssertionLevel(kIOPMAssertionLevelOn), reason, &assertionID) if success == kIOReturnSuccess { preventedSleep = true } else { Utility.showAlert("sleep") } } static func allowSleep() { if !preventedSleep { return } else { let success = IOPMAssertionRelease(assertionID) if success == kIOReturnSuccess { preventedSleep = false } else { Logger.log("Cannot allow display sleep", level: .warning) } } } }
gpl-3.0
4948a53763ec4985afa2ea0696777722
22.346939
91
0.588287
4.576
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Widgets/LoginTableViewCell.swift
1
13846
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage protocol LoginTableViewCellDelegate: class { func didSelectOpenAndFillForCell(_ cell: LoginTableViewCell) func shouldReturnAfterEditingDescription(_ cell: LoginTableViewCell) -> Bool func infoItemForCell(_ cell: LoginTableViewCell) -> InfoItem? } private struct LoginTableViewCellUX { static let highlightedLabelFont = UIFont.systemFont(ofSize: 12) static let highlightedLabelTextColor = UIConstants.SystemBlueColor static let highlightedLabelEditingTextColor = SettingsUX.TableViewHeaderTextColor static let descriptionLabelFont = UIFont.systemFont(ofSize: 16) static let descriptionLabelTextColor = UIColor.black static let HorizontalMargin: CGFloat = 14 static let IconImageSize: CGFloat = 34 static let indentWidth: CGFloat = 44 static let IndentAnimationDuration: TimeInterval = 0.2 static let editingDescriptionIndent: CGFloat = IconImageSize + HorizontalMargin } enum LoginTableViewCellStyle { case iconAndBothLabels case noIconAndBothLabels case iconAndDescriptionLabel } class LoginTableViewCell: UITableViewCell { fileprivate let labelContainer = UIView() weak var delegate: LoginTableViewCellDelegate? // In order for context menu handling, this is required override var canBecomeFirstResponder: Bool { return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { guard let item = delegate?.infoItemForCell(self) else { return false } // Menu actions for password if item == .passwordItem { let showRevealOption = self.descriptionLabel.isSecureTextEntry ? (action == MenuHelper.SelectorReveal) : (action == MenuHelper.SelectorHide) return action == MenuHelper.SelectorCopy || showRevealOption } // Menu actions for Website if item == .websiteItem { return action == MenuHelper.SelectorCopy || action == MenuHelper.SelectorOpenAndFill } // Menu actions for Username if item == .usernameItem { return action == MenuHelper.SelectorCopy } return false } lazy var descriptionLabel: UITextField = { let label = UITextField() label.font = LoginTableViewCellUX.descriptionLabelFont label.textColor = LoginTableViewCellUX.descriptionLabelTextColor label.backgroundColor = UIColor.white label.isUserInteractionEnabled = false label.autocapitalizationType = .none label.autocorrectionType = .no label.accessibilityElementsHidden = true label.adjustsFontSizeToFitWidth = false label.delegate = self label.isAccessibilityElement = true return label }() // Exposing this label as internal/public causes the Xcode 7.2.1 compiler optimizer to // produce a EX_BAD_ACCESS error when dequeuing the cell. For now, this label is made private // and the text property is exposed using a get/set property below. fileprivate lazy var highlightedLabel: UILabel = { let label = UILabel() label.font = LoginTableViewCellUX.highlightedLabelFont label.textColor = LoginTableViewCellUX.highlightedLabelTextColor label.backgroundColor = UIColor.white label.numberOfLines = 1 return label }() fileprivate lazy var iconImageView: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = UIColor.white imageView.contentMode = .scaleAspectFit return imageView }() fileprivate var showingIndent: Bool = false fileprivate var customIndentView = UIView() fileprivate var customCheckmarkIcon = UIImageView(image: UIImage(named: "loginUnselected")) /// Override the default accessibility label since it won't include the description by default /// since it's a UITextField acting as a label. override var accessibilityLabel: String? { get { if descriptionLabel.isSecureTextEntry { return highlightedLabel.text ?? "" } else { return "\(highlightedLabel.text ?? ""), \(descriptionLabel.text ?? "")" } } set { // Ignore sets } } var style: LoginTableViewCellStyle = .iconAndBothLabels { didSet { if style != oldValue { configureLayoutForStyle(style) } } } var descriptionTextSize: CGSize? { guard let descriptionText = descriptionLabel.text else { return nil } let attributes = [ NSAttributedStringKey.font: LoginTableViewCellUX.descriptionLabelFont ] return descriptionText.size(withAttributes: attributes) } var displayDescriptionAsPassword: Bool = false { didSet { descriptionLabel.isSecureTextEntry = displayDescriptionAsPassword } } var editingDescription: Bool = false { didSet { if editingDescription != oldValue { descriptionLabel.isUserInteractionEnabled = editingDescription highlightedLabel.textColor = editingDescription ? LoginTableViewCellUX.highlightedLabelEditingTextColor : LoginTableViewCellUX.highlightedLabelTextColor // Trigger a layout configuration if we changed to editing/not editing the description. configureLayoutForStyle(self.style) } } } var highlightedLabelTitle: String? { get { return highlightedLabel.text } set(newTitle) { highlightedLabel.text = newTitle } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) indentationWidth = 0 selectionStyle = .none contentView.backgroundColor = UIColor.white labelContainer.backgroundColor = UIColor.white labelContainer.addSubview(highlightedLabel) labelContainer.addSubview(descriptionLabel) contentView.addSubview(iconImageView) contentView.addSubview(labelContainer) customIndentView.addSubview(customCheckmarkIcon) addSubview(customIndentView) configureLayoutForStyle(self.style) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() delegate = nil descriptionLabel.isSecureTextEntry = false descriptionLabel.keyboardType = .default descriptionLabel.returnKeyType = .default descriptionLabel.isUserInteractionEnabled = false } override func layoutSubviews() { super.layoutSubviews() // Adjust indent frame var indentFrame = CGRect(width: LoginTableViewCellUX.indentWidth, height: frame.height) if !showingIndent { indentFrame.origin.x = -LoginTableViewCellUX.indentWidth } customIndentView.frame = indentFrame customCheckmarkIcon.frame.center = CGPoint(x: indentFrame.width / 2, y: indentFrame.height / 2) // Adjust content view frame based on indent var contentFrame = self.contentView.frame contentFrame.origin.x += showingIndent ? LoginTableViewCellUX.indentWidth : 0 contentView.frame = contentFrame } fileprivate func configureLayoutForStyle(_ style: LoginTableViewCellStyle) { switch style { case .iconAndBothLabels: iconImageView.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin) make.height.width.equalTo(LoginTableViewCellUX.IconImageSize) } labelContainer.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin) make.leading.equalTo(iconImageView.snp.trailing).offset(LoginTableViewCellUX.HorizontalMargin) } highlightedLabel.snp.remakeConstraints { make in make.leading.top.equalTo(labelContainer) make.bottom.equalTo(descriptionLabel.snp.top) make.width.equalTo(labelContainer) } descriptionLabel.snp.remakeConstraints { make in make.leading.bottom.equalTo(labelContainer) make.top.equalTo(highlightedLabel.snp.bottom) make.width.equalTo(labelContainer) } case .iconAndDescriptionLabel: iconImageView.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin) make.height.width.equalTo(LoginTableViewCellUX.IconImageSize) } labelContainer.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin) make.leading.equalTo(iconImageView.snp.trailing).offset(LoginTableViewCellUX.HorizontalMargin) } highlightedLabel.snp.remakeConstraints { make in make.height.width.equalTo(0) } descriptionLabel.snp.remakeConstraints { make in make.top.leading.bottom.equalTo(labelContainer) make.width.equalTo(labelContainer) } case .noIconAndBothLabels: // Currently we only support modifying the description for this layout which is why // we factor in the editingOffset when calculating the constraints. let editingOffset = editingDescription ? LoginTableViewCellUX.editingDescriptionIndent : 0 iconImageView.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.leading.equalTo(contentView).offset(LoginTableViewCellUX.HorizontalMargin) make.height.width.equalTo(0) } labelContainer.snp.remakeConstraints { make in make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).offset(-LoginTableViewCellUX.HorizontalMargin) make.leading.equalTo(iconImageView.snp.trailing).offset(editingOffset) } highlightedLabel.snp.remakeConstraints { make in make.leading.top.equalTo(labelContainer) make.bottom.equalTo(descriptionLabel.snp.top) make.width.equalTo(labelContainer) } descriptionLabel.snp.remakeConstraints { make in make.leading.bottom.equalTo(labelContainer) make.top.equalTo(highlightedLabel.snp.bottom) make.width.equalTo(labelContainer) } } setNeedsUpdateConstraints() } override func setEditing(_ editing: Bool, animated: Bool) { showingIndent = editing let adjustConstraints = { [unowned self] in // Shift over content view var contentFrame = self.contentView.frame contentFrame.origin.x += editing ? LoginTableViewCellUX.indentWidth : -LoginTableViewCellUX.indentWidth self.contentView.frame = contentFrame // Shift over custom indent view var indentFrame = self.customIndentView.frame indentFrame.origin.x += editing ? LoginTableViewCellUX.indentWidth : -LoginTableViewCellUX.indentWidth self.customIndentView.frame = indentFrame } animated ? UIView.animate(withDuration: LoginTableViewCellUX.IndentAnimationDuration, animations: adjustConstraints) : adjustConstraints() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) customCheckmarkIcon.image = UIImage(named: selected ? "loginSelected" : "loginUnselected") } } // MARK: - Menu Selectors extension LoginTableViewCell: MenuHelperInterface { func menuHelperReveal() { displayDescriptionAsPassword = false } func menuHelperSecure() { displayDescriptionAsPassword = true } func menuHelperCopy() { // Copy description text to clipboard UIPasteboard.general.string = descriptionLabel.text } func menuHelperOpenAndFill() { delegate?.didSelectOpenAndFillForCell(self) } } // MARK: - Cell Decorators extension LoginTableViewCell { func updateCellWithLogin(_ login: LoginData) { descriptionLabel.text = login.hostname highlightedLabel.text = login.username iconImageView.image = UIImage(named: "faviconFox") } } extension LoginTableViewCell: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { return self.delegate?.shouldReturnAfterEditingDescription(self) ?? true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if descriptionLabel.isSecureTextEntry { displayDescriptionAsPassword = false } return true } func textFieldDidEndEditing(_ textField: UITextField) { if descriptionLabel.isSecureTextEntry { displayDescriptionAsPassword = true } } }
mpl-2.0
7222f24765127443fd54944bfca62ae1
35.246073
152
0.667196
5.596605
false
false
false
false
nodes-ios/Serializable
Serpent/Example/SerpentExample/Classes/User Interface/HomeVC.swift
2
2558
// // HomeVC.swift // Serpent Example // // Created by Dominik Hádl on 17/04/16. // Copyright © 2016 Nodes ApS. All rights reserved. // import UIKit class HomeVC: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var users: [User] = [] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: UserListCell.reuseIdentifier, bundle: nil), forCellReuseIdentifier: UserListCell.reuseIdentifier) reloadData() } // MARK: - Callbacks - func reloadData() { ConnectionManager.fetchRandomUsers { (response) in switch response.result { case .success(let users): self.users = users self.tableView.reloadData() case .failure(let error): let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } @IBAction func refreshPressed(_ sender: UIBarButtonItem) { reloadData() } // MARK: - UITableView Data Source & Delegate - func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UserListCell.staticHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UserListCell.reuseIdentifier, for: indexPath) as? UserListCell ?? UserListCell() cell.populateWithUser(users[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "ShowUserDetails", sender: indexPath) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowUserDetails" { if let userVC = segue.destination as? UserDetailsVC, let indexPath = sender as? IndexPath { userVC.user = users[indexPath.row] } } } }
mit
e7949542ae0e890a7bc2582a96c94b52
31.769231
145
0.641628
5.051383
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CartCost.swift
1
11369
// // CartCost.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The costs that the buyer will pay at checkout. The cart cost uses /// [`CartBuyerIdentity`](https://shopify.dev/api/storefront/reference/cart/cartbuyeridentity) /// to determine [international /// pricing](https://shopify.dev/custom-storefronts/internationalization/international-pricing). open class CartCostQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CartCost /// The estimated amount, before taxes and discounts, for the customer to pay /// at checkout. The checkout charge amount doesn't include any deferred /// payments that'll be paid at a later date. If the cart has no deferred /// payments, then the checkout charge amount is equivalent to /// `subtotalAmount`. @discardableResult open func checkoutChargeAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCostQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "checkoutChargeAmount", aliasSuffix: alias, subfields: subquery) return self } /// The amount, before taxes and cart-level discounts, for the customer to pay. @discardableResult open func subtotalAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCostQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "subtotalAmount", aliasSuffix: alias, subfields: subquery) return self } /// Whether the subtotal amount is estimated. @discardableResult open func subtotalAmountEstimated(alias: String? = nil) -> CartCostQuery { addField(field: "subtotalAmountEstimated", aliasSuffix: alias) return self } /// The total amount for the customer to pay. @discardableResult open func totalAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCostQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "totalAmount", aliasSuffix: alias, subfields: subquery) return self } /// Whether the total amount is estimated. @discardableResult open func totalAmountEstimated(alias: String? = nil) -> CartCostQuery { addField(field: "totalAmountEstimated", aliasSuffix: alias) return self } /// The duty amount for the customer to pay at checkout. @discardableResult open func totalDutyAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCostQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "totalDutyAmount", aliasSuffix: alias, subfields: subquery) return self } /// Whether the total duty amount is estimated. @discardableResult open func totalDutyAmountEstimated(alias: String? = nil) -> CartCostQuery { addField(field: "totalDutyAmountEstimated", aliasSuffix: alias) return self } /// The tax amount for the customer to pay at checkout. @discardableResult open func totalTaxAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCostQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "totalTaxAmount", aliasSuffix: alias, subfields: subquery) return self } /// Whether the total tax amount is estimated. @discardableResult open func totalTaxAmountEstimated(alias: String? = nil) -> CartCostQuery { addField(field: "totalTaxAmountEstimated", aliasSuffix: alias) return self } } /// The costs that the buyer will pay at checkout. The cart cost uses /// [`CartBuyerIdentity`](https://shopify.dev/api/storefront/reference/cart/cartbuyeridentity) /// to determine [international /// pricing](https://shopify.dev/custom-storefronts/internationalization/international-pricing). open class CartCost: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CartCostQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "checkoutChargeAmount": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "subtotalAmount": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "subtotalAmountEstimated": guard let value = value as? Bool else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return value case "totalAmount": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "totalAmountEstimated": guard let value = value as? Bool else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return value case "totalDutyAmount": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "totalDutyAmountEstimated": guard let value = value as? Bool else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return value case "totalTaxAmount": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) case "totalTaxAmountEstimated": guard let value = value as? Bool else { throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } return value default: throw SchemaViolationError(type: CartCost.self, field: fieldName, value: fieldValue) } } /// The estimated amount, before taxes and discounts, for the customer to pay /// at checkout. The checkout charge amount doesn't include any deferred /// payments that'll be paid at a later date. If the cart has no deferred /// payments, then the checkout charge amount is equivalent to /// `subtotalAmount`. open var checkoutChargeAmount: Storefront.MoneyV2 { return internalGetCheckoutChargeAmount() } func internalGetCheckoutChargeAmount(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "checkoutChargeAmount", aliasSuffix: alias) as! Storefront.MoneyV2 } /// The amount, before taxes and cart-level discounts, for the customer to pay. open var subtotalAmount: Storefront.MoneyV2 { return internalGetSubtotalAmount() } func internalGetSubtotalAmount(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "subtotalAmount", aliasSuffix: alias) as! Storefront.MoneyV2 } /// Whether the subtotal amount is estimated. open var subtotalAmountEstimated: Bool { return internalGetSubtotalAmountEstimated() } func internalGetSubtotalAmountEstimated(alias: String? = nil) -> Bool { return field(field: "subtotalAmountEstimated", aliasSuffix: alias) as! Bool } /// The total amount for the customer to pay. open var totalAmount: Storefront.MoneyV2 { return internalGetTotalAmount() } func internalGetTotalAmount(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "totalAmount", aliasSuffix: alias) as! Storefront.MoneyV2 } /// Whether the total amount is estimated. open var totalAmountEstimated: Bool { return internalGetTotalAmountEstimated() } func internalGetTotalAmountEstimated(alias: String? = nil) -> Bool { return field(field: "totalAmountEstimated", aliasSuffix: alias) as! Bool } /// The duty amount for the customer to pay at checkout. open var totalDutyAmount: Storefront.MoneyV2? { return internalGetTotalDutyAmount() } func internalGetTotalDutyAmount(alias: String? = nil) -> Storefront.MoneyV2? { return field(field: "totalDutyAmount", aliasSuffix: alias) as! Storefront.MoneyV2? } /// Whether the total duty amount is estimated. open var totalDutyAmountEstimated: Bool { return internalGetTotalDutyAmountEstimated() } func internalGetTotalDutyAmountEstimated(alias: String? = nil) -> Bool { return field(field: "totalDutyAmountEstimated", aliasSuffix: alias) as! Bool } /// The tax amount for the customer to pay at checkout. open var totalTaxAmount: Storefront.MoneyV2? { return internalGetTotalTaxAmount() } func internalGetTotalTaxAmount(alias: String? = nil) -> Storefront.MoneyV2? { return field(field: "totalTaxAmount", aliasSuffix: alias) as! Storefront.MoneyV2? } /// Whether the total tax amount is estimated. open var totalTaxAmountEstimated: Bool { return internalGetTotalTaxAmountEstimated() } func internalGetTotalTaxAmountEstimated(alias: String? = nil) -> Bool { return field(field: "totalTaxAmountEstimated", aliasSuffix: alias) as! Bool } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "checkoutChargeAmount": response.append(internalGetCheckoutChargeAmount()) response.append(contentsOf: internalGetCheckoutChargeAmount().childResponseObjectMap()) case "subtotalAmount": response.append(internalGetSubtotalAmount()) response.append(contentsOf: internalGetSubtotalAmount().childResponseObjectMap()) case "totalAmount": response.append(internalGetTotalAmount()) response.append(contentsOf: internalGetTotalAmount().childResponseObjectMap()) case "totalDutyAmount": if let value = internalGetTotalDutyAmount() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "totalTaxAmount": if let value = internalGetTotalTaxAmount() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } default: break } } return response } } }
mit
bc08070c04ae68b84a18a39f6545828e
35.55627
110
0.726977
3.94483
false
true
false
false
NobodyNada/SwiftStack
Sources/SwiftStack/RequestsQuestions.swift
1
27721
// // RequestsQuestions.swift // SwiftStack // // Created by NobodyNada on 17.12.16. // // import Foundation import Dispatch /** This extension contains all requests in the QUESTIONS section of the StackExchange API Documentation. - author: NobodyNada, FelixSFD */ public extension APIClient { // - MARK: /questions /** Fetches all questions on the site synchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - returns: The list of questions as `APIResponse<Question>` - author: FelixSFD */ func fetchQuestions( parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try performAPIRequest( "questions", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches all questions on the site asynchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - parameter completion - author: FelixSFD */ func fetchQuestions( parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchQuestions( parameters: parameters, backoffBehavior: backoffBehavior ) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } // - MARK: /questions/{ids} /** Fetches questions synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - returns: The list of sites as `APIResponse<Question>` - author: NobodyNada */ func fetchQuestions( _ ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches questions asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - parameter completion - author: NobodyNada */ func fetchQuestions( _ ids: [Int], parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchQuestions( ids, parameters: parameters, backoffBehavior: backoffBehavior ) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches a question synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - returns: The list of sites as `APIResponse<Question>` - author: NobodyNada */ func fetchQuestion( _ id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try fetchQuestions([id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches a question asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an APIRequest has a backoff - parameter completion - author: NobodyNada */ func fetchQuestion( _ id: Int, parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { fetchQuestions([id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/{ids}/answers /** Fetches `Answer`s on `Question`s synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of answers as `APIResponse<Answer>` - authors: NobodyNada, FelixSFD */ func fetchAnswersOn( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Answer> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))/answers", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches `Answer`s on `Question`s asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchAnswersOn( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Answer>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Answer> = try self.fetchAnswersOn(questions: ids, parameters: parameters, backoffBehavior: backoffBehavior) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches `Answer`s on a single `Question` synchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of answers as `APIResponse<Answer>` - authors: NobodyNada, FelixSFD */ func fetchAnswersOn( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Answer> { return try fetchAnswersOn(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches `Answer`s on a single `Question` asynchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchAnswersOn( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Answer>?, Error?) -> ()) { fetchAnswersOn(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/{ids}/comments /** Fetches `Comment`s on `Question`s synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of comments as `APIResponse<Comment>` - authors: NobodyNada, FelixSFD */ func fetchCommentsOn( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Comment> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))/comments", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches `Comment`s on `Question`s asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchCommentsOn( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Comment>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Comment> = try self.fetchCommentsOn(questions: ids, parameters: parameters, backoffBehavior: backoffBehavior) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches `Comment`s on a single `Question` synchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of comments as `APIResponse<Comment>` - authors: NobodyNada, FelixSFD */ func fetchCommentsOn( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Comment> { return try fetchCommentsOn(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches `Comment`s on a single `Question` asynchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchCommentsOn( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Comment>?, Error?) -> ()) { fetchCommentsOn(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/{ids}/linked /** Fetches linked `Question`s to `Question`s synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - authors: NobodyNada, FelixSFD */ func fetchLinkedQuestionsTo( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))/linked", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches linked `Question`s to `Question`s asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchLinkedQuestionsTo( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchLinkedQuestionsTo(questions: ids, parameters: parameters, backoffBehavior: backoffBehavior) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches linked `Question`s to a single `Question` synchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - authors: NobodyNada, FelixSFD */ func fetchLinkedQuestionsTo( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try fetchLinkedQuestionsTo(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches linked `Question`s to a single `Question` asynchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchLinkedQuestionsTo( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { fetchLinkedQuestionsTo(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/{ids}/related /** Fetches related `Question`s to `Question`s synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - authors: NobodyNada, FelixSFD */ func fetchRelatedQuestionsTo( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))/related", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches related `Question`s to `Question`s asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchRelatedQuestionsTo( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchRelatedQuestionsTo(questions: ids, parameters: parameters, backoffBehavior: backoffBehavior) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches related `Question`s to a single `Question` synchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - authors: NobodyNada, FelixSFD */ func fetchRelatedQuestionsTo( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try fetchRelatedQuestionsTo(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches related `Question`s to a single `Question` asynchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchRelatedQuestionsTo( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { fetchRelatedQuestionsTo(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/{ids}/timeline /** Fetches the `Question.Timeline` events of `Question`s synchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question.Timeline>` - authors: NobodyNada, FelixSFD */ func fetchTimelineOf( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question.Timeline> { guard !ids.isEmpty else { fatalError("ids is empty") } return try performAPIRequest( "questions/\(ids.map {String($0)}.joined(separator: ";"))/timeline", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches the `Question.Timeline` events of `Question`s asynchronously. - parameter ids: The question IDs to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchTimelineOf( questions ids: [Int], parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question.Timeline>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question.Timeline> = try self.fetchTimelineOf(questions: ids, parameters: parameters, backoffBehavior: backoffBehavior) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } /** Fetches the `Question.Timeline` events of a single `Question` synchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question.Timeline>` - authors: NobodyNada, FelixSFD */ func fetchTimelineOf( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question.Timeline> { return try fetchTimelineOf(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior) } /** Fetches the `Question.Timeline` events of a single `Question` asynchronously. - parameter id: The question ID to fetch. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completionHandler: - authors: NobodyNada, FelixSFD */ func fetchTimelineOf( question id: Int, parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question.Timeline>?, Error?) -> ()) { fetchTimelineOf(questions: [id], parameters: parameters, backoffBehavior: backoffBehavior, completionHandler: completionHandler) } // - MARK: /questions/featured /** Fetches all questions with active bounties on the site synchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - author: FelixSFD */ func fetchFeaturedQuestions( parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try performAPIRequest( "questions/featured", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches all questions with active bounties on the site asynchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completion - author: FelixSFD */ func fetchFeaturedQuestions( parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchQuestions( parameters: parameters, backoffBehavior: backoffBehavior ) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } // - MARK: /questions/no-answers /** Fetches all questions with no answers on the site synchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - seealso: fetchUnansweredQuestions(parameters:backoffBehavior:) - author: FelixSFD */ func fetchQuestionsWithNoAnswers( parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try performAPIRequest( "questions/no-answers", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches all questions with no answers on the site asynchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completion - seealso: fetchUnansweredQuestions(parameters:backoffBehavior:completionHandler:) - author: FelixSFD */ func fetchQuestionsWithNoAnswers( parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchQuestions( parameters: parameters, backoffBehavior: backoffBehavior ) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } // - MARK: /questions/unanswered /** Fetches all questions the site considers unanswered synchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - returns: The list of questions as `APIResponse<Question>` - seealso: fetchQuestionsWithNoAnswers(parameters:backoffBehavior:) - author: FelixSFD */ func fetchUnansweredQuestions( parameters: [String:String] = [:], backoffBehavior: BackoffBehavior = .wait) throws -> APIResponse<Question> { return try performAPIRequest( "questions/unanswered", parameters: parameters, backoffBehavior: backoffBehavior ) } /** Fetches all questions the site considers unanswered asynchronously. - parameter parameters: The dictionary of parameters used in the request - parameter backoffBehavior: The behavior when an `APIRequest` has a backoff - parameter completion - seealso: fetchQuestionsWithNoAnswers(parameters:backoffBehavior:completionHandler:) - author: FelixSFD */ func fetchUnansweredQuestions( parameters: [String: String] = [:], backoffBehavior: BackoffBehavior = .wait, completionHandler: @escaping (APIResponse<Question>?, Error?) -> ()) { queue.async { do { let response: APIResponse<Question> = try self.fetchQuestions( parameters: parameters, backoffBehavior: backoffBehavior ) completionHandler(response, nil) } catch { completionHandler(nil, error) } } } }
mit
1cc9122d8ba09b5ba9d5d232dfacff7f
30.358597
161
0.612424
5.392142
false
false
false
false
git-hushuai/MOMO
MMHSMeterialProject/UINavigationController/BusinessFile/简历库Item/TKOptimizeCell.swift
1
11710
// // TKOptimizeCell.swift // MMHSMeterialProject // // Created by hushuaike on 16/4/12. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class TKOptimizeCell: UITableViewCell { var logoView:UIImageView = UIImageView(); var jobNameLabel:UILabel = UILabel(); var firstBaseInfoLabel:UILabel = UILabel(); var secondBaseInfoLabel:UILabel = UILabel(); var threeBaseInfoLabel :UILabel = UILabel(); var fourBaseInfoLabel:UILabel = UILabel(); var baseInfoLogoView:UIImageView = UIImageView(); var baseInfoPhoneView:UIImageView = UIImageView(); var baseInfoEmailView :UIImageView = UIImageView(); var baseInfoLogoLabel:UILabel = UILabel(); var baseInfoPhoneLabel:UILabel = UILabel(); var baseInfoEmailLabel:UILabel = UILabel.init(); var advisorContentButton:UIButton = UIButton.init(type:UIButtonType.Custom); var CaverView:UILabel = UILabel.init(); var topCaverView:UILabel = UILabel.init(); var bottomCaverView: UILabel = UILabel.init(); var resumeModel:TKJobItemModel?{ didSet{ self.setCellSubInfoWithModle(resumeModel!); } } func setCellSubInfoWithModle(resumeModel:TKJobItemModel){ self.logoView.sd_setImageWithURL(NSURL.init(string: resumeModel.logo), placeholderImage: UIImage.init(named: "缺X3"), options: SDWebImageOptions.RetryFailed); self.jobNameLabel.text = resumeModel.expected_job; self.jobNameLabel.sizeToFit(); if Int(resumeModel.sex) == 0{ self.firstBaseInfoLabel.text = "女"; }else if(Int(resumeModel.sex) == 1){ self.firstBaseInfoLabel.text = "男"; }else{ self.firstBaseInfoLabel.text = ""; } self.secondBaseInfoLabel.text = resumeModel.position; self.threeBaseInfoLabel.text = resumeModel.degree; self.fourBaseInfoLabel.text = String.init(format: "%@年工作年限", resumeModel.year_work); self.baseInfoLogoView.image = UIImage.init(named: "姓名@2x"); self.baseInfoLogoView.updateLayout(); self.baseInfoPhoneView.image = UIImage.init(named: "电话@2x"); self.baseInfoPhoneView.updateLayout(); self.baseInfoEmailView.image = UIImage.init(named: "邮箱@2x"); self.baseInfoEmailView.updateLayout(); self.baseInfoLogoLabel.text = resumeModel.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.name : "暂无"; let phoneStr = String.init(format: "%@", (resumeModel.phone)!); if phoneStr != "<null>" && resumeModel.phone.intValue > 0{ self.baseInfoPhoneLabel.text = phoneStr; }else{ self.baseInfoPhoneLabel.text = "暂无"; } if resumeModel.email != nil{ self.baseInfoEmailLabel.text = resumeModel.email.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.email : "暂无";}else{ self.baseInfoEmailLabel.text = "暂无"; } self.contentView.layoutSubviews(); } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.contentView.addSubview(self.topCaverView); self.topCaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0); self.topCaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topEqualToView(self.contentView); self.contentView.addSubview(self.logoView); self.logoView.sd_layout() .leftSpaceToView(self.contentView,14.0) .topSpaceToView(self.contentView,10) .widthIs(50) .heightIs(50); self.contentView.addSubview(self.jobNameLabel); self.jobNameLabel.sd_layout() .leftSpaceToView(self.logoView,14) .topSpaceToView(self.contentView,10) .heightIs(20); self.jobNameLabel.setSingleLineAutoResizeWithMaxWidth(200); self.jobNameLabel.textAlignment = .Left; self.jobNameLabel.textColor = RGBA(0xff, g: 0x8a, b: 0x00, a: 1.0); self.contentView.addSubview(self.firstBaseInfoLabel); self.firstBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.firstBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.firstBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.firstBaseInfoLabel.sd_layout() .leftEqualToView(self.jobNameLabel) .topSpaceToView(self.jobNameLabel,10) .heightIs(20.0); self.firstBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(40); self.firstBaseInfoLabel.isAttributedContent = false; self.firstBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.secondBaseInfoLabel); self.secondBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.secondBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.secondBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.secondBaseInfoLabel.sd_layout() .leftSpaceToView(self.firstBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.secondBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.secondBaseInfoLabel.isAttributedContent = false; self.secondBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.threeBaseInfoLabel); self.threeBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.threeBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.threeBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.threeBaseInfoLabel.sd_layout() .leftSpaceToView(self.secondBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.threeBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.threeBaseInfoLabel.isAttributedContent = false; self.threeBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.fourBaseInfoLabel); self.fourBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.fourBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.fourBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.fourBaseInfoLabel.sd_layout() .leftSpaceToView(self.threeBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.fourBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.fourBaseInfoLabel.isAttributedContent = false; self.fourBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.baseInfoLogoView); self.baseInfoLogoView.sd_layout() .leftSpaceToView(self.logoView,14.0) .topSpaceToView(self.firstBaseInfoLabel,10) .widthIs(16.0) .heightIs(16.0); self.contentView.addSubview(self.baseInfoLogoLabel); self.baseInfoLogoLabel.sd_layout() .leftSpaceToView(self.baseInfoLogoView,14) .topEqualToView(self.baseInfoLogoView) .heightIs(16) self.baseInfoLogoLabel.setSingleLineAutoResizeWithMaxWidth(100); self.baseInfoLogoLabel.textAlignment = .Left; self.baseInfoLogoLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoLogoLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.baseInfoPhoneView); self.baseInfoPhoneView.sd_layout() .leftSpaceToView(self.baseInfoLogoView,100) .topEqualToView(self.baseInfoLogoView) .widthIs(16) .heightIs(16); self.contentView.addSubview(self.baseInfoPhoneLabel); self.baseInfoPhoneLabel.sd_layout() .leftSpaceToView(self.baseInfoPhoneView,14) .topEqualToView(self.baseInfoLogoView) .heightIs(16); self.baseInfoPhoneLabel.setSingleLineAutoResizeWithMaxWidth(120); self.baseInfoPhoneLabel.textAlignment = .Left; self.baseInfoPhoneLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoPhoneLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.baseInfoEmailView); self.baseInfoEmailView.sd_layout() .leftEqualToView(self.baseInfoLogoView) .topSpaceToView(self.baseInfoLogoView,10) .widthIs(16.0) .heightIs(16.0); self.contentView.addSubview(self.baseInfoEmailLabel); self.baseInfoEmailLabel.sd_layout() .leftSpaceToView(self.baseInfoEmailView,14) .topEqualToView(self.baseInfoEmailView) .heightIs(16); self.baseInfoEmailLabel.setSingleLineAutoResizeWithMaxWidth(240); self.baseInfoEmailLabel.textAlignment = .Left; self.baseInfoEmailLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoEmailLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.CaverView); self.CaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topSpaceToView(self.baseInfoEmailView,6); self.CaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0); self.contentView.addSubview(self.advisorContentButton); self.advisorContentButton.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .topSpaceToView(self.CaverView,0) .heightIs(44); self.advisorContentButton.addTarget(self, action: "onClickCallPhoneBtn:", forControlEvents:.TouchUpInside) self.advisorContentButton.setTitle("拨打电话", forState: .Normal); self.advisorContentButton.titleLabel?.font = UIFont.systemFontOfSize(16); self.advisorContentButton.titleLabel?.textAlignment = .Center; self.advisorContentButton.setTitleColor(RGBA(0x3c, g: 0xb3, b: 0xec, a: 1.0), forState:.Normal); self.contentView.addSubview(self.bottomCaverView); self.bottomCaverView.backgroundColor = self.topCaverView.backgroundColor; self.bottomCaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topSpaceToView(self.advisorContentButton,0); self.setupAutoHeightWithBottomView(self.bottomCaverView, bottomMargin: 0); } func onClickCallPhoneBtn(sender:UIButton){ print("onClickCallPhoneBtn"); let phoneInfo = String.init(format: "tel:%@", (self.resumeModel?.phone)!); let webView = UIWebView.init(); webView.loadRequest(NSURLRequest.init(URL: NSURL.init(string: phoneInfo)!)); dispatch_async(dispatch_get_main_queue()) { () -> Void in self.superview?.addSubview(webView); } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: rgb color func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
cae8caf3e6b5381cbc69aaee0ef42b7a
43.826923
165
0.665809
4.606719
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Playback.playground/Pages/Drum Sequencer.xcplaygroundpage/Contents.swift
1
3393
//: ## Drums import AudioKitPlaygrounds import AudioKit let drums = AKMIDISampler() AudioKit.output = drums AudioKit.start() let bassDrumFile = try AKAudioFile(readFileName: "Samples/Drums/bass_drum_C1.wav") let clapFile = try AKAudioFile(readFileName: "Samples/Drums/clap_D#1.wav") let closedHiHatFile = try AKAudioFile(readFileName: "Samples/Drums/closed_hi_hat_F#1.wav") let hiTomFile = try AKAudioFile(readFileName: "Samples/Drums/hi_tom_D2.wav") let loTomFile = try AKAudioFile(readFileName: "Samples/Drums/lo_tom_F1.wav") let midTomFile = try AKAudioFile(readFileName: "Samples/Drums/mid_tom_B1.wav") let openHiHatFile = try AKAudioFile(readFileName: "Samples/Drums/open_hi_hat_A#1.wav") let snareDrumFile = try AKAudioFile(readFileName: "Samples/Drums/snare_D1.wav") try drums.loadAudioFiles([bassDrumFile, clapFile, closedHiHatFile, hiTomFile, loTomFile, midTomFile, openHiHatFile, snareDrumFile]) let sequencer = AKSequencer(filename: "4tracks") sequencer.clearRange(start: AKDuration(beats: 0), duration: AKDuration(beats: 100)) sequencer.debug() sequencer.setGlobalMIDIOutput(drums.midiIn) sequencer.enableLooping(AKDuration(beats: 4)) sequencer.setTempo(150) import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Drum Sequencer") addView(AKButton(title: "Play") { button in if sequencer.isPlaying { sequencer.stop() sequencer.rewind() button.title = "Play" } else { sequencer.play() button.title = "Stop" } }) sequencer.tracks[0].add(noteNumber: 24, velocity: 127, position: AKDuration(beats: 0), duration: AKDuration(beats: 1)) sequencer.tracks[0].add(noteNumber: 24, velocity: 127, position: AKDuration(beats: 2), duration: AKDuration(beats: 1)) sequencer.tracks[1].add(noteNumber: 26, velocity: 127, position: AKDuration(beats: 2), duration: AKDuration(beats: 1)) for i in 0 ... 7 { sequencer.tracks[2].add( noteNumber: 30, velocity: 80, position: AKDuration(beats: i / 2.0), duration: AKDuration(beats: 0.5)) } sequencer.tracks[3].add(noteNumber: 26, velocity: 127, position: AKDuration(beats: 2), duration: AKDuration(beats: 1)) addView(AKButton(title: "Randomize Hi-hats") { _ in sequencer.tracks[2].clearRange(start: AKDuration(beats: 0), duration: AKDuration(beats: 4)) for i in 0 ... 15 { sequencer.tracks[2].add( noteNumber: MIDINoteNumber(30 + Int(random(in: 0 ... 1.99))), velocity: MIDIVelocity(random(in: 80 ... 127)), position: AKDuration(beats: i / 4.0), duration: AKDuration(beats: 0.5)) } }) addView(AKSlider(property: "Tempo", value: 150, range: 60 ... 300, format: "%0.0f") { sliderValue in sequencer.setTempo(sliderValue) }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
mit
336f5582290b3a7cf9f8c7b359d76357
35.483871
126
0.612732
3.996466
false
false
false
false
soffes/RateLimit
RateLimit/TimedLimter.swift
2
1096
// // RateLimit.swift // RateLimit // // Created by Sam Soffes on 4/9/12. // Copyright © 2012-2015 Sam Soffes. All rights reserved. // import Foundation public final class TimedLimiter: SyncLimiter { // MARK: - Properties public let limit: TimeInterval public private(set) var lastExecutedAt: Date? private let syncQueue = DispatchQueue(label: "com.samsoffes.ratelimit", attributes: []) // MARK: - Initializers public init(limit: TimeInterval) { self.limit = limit } // MARK: - Limiter @discardableResult public func execute(_ block: () -> Void) -> Bool { let executed = syncQueue.sync { () -> Bool in let now = Date() // Lookup last executed let timeInterval = now.timeIntervalSince(lastExecutedAt ?? .distantPast) // If the time since last execution is greater than the limit, execute if timeInterval > limit { // Record execution lastExecutedAt = now // Execute return true } return false } if executed { block() } return executed } public func reset() { syncQueue.sync { lastExecutedAt = nil } } }
mit
876f731fd62bdaac3a01394029c68e77
16.95082
88
0.66758
3.566775
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Account.swift
1
4313
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation extension Account: NotificationContext { } extension Notification.Name { public static let AccountUnreadCountDidChangeNotification = Notification.Name("AccountUnreadCountDidChangeNotification") } /// An `Account` holds information related to a single account, /// such as the accounts users name, /// team name if there is any, picture and uuid. public final class Account: NSObject, Codable { public var userName: String public var teamName: String? public let userIdentifier: UUID public var imageData: Data? public var teamImageData: Data? public var loginCredentials: LoginCredentials? public var unreadConversationCount: Int = 0 { didSet { if oldValue != self.unreadConversationCount { NotificationInContext(name: .AccountUnreadCountDidChangeNotification, context: self).post() } } } enum CodingKeys: String, CodingKey { case userName = "name" case teamName = "team" case userIdentifier = "identifier" case imageData = "image" case teamImageData = "teamImage" case unreadConversationCount = "unreadConversationCount" case loginCredentials = "loginCredentials" } public required init(userName: String, userIdentifier: UUID, teamName: String? = nil, imageData: Data? = nil, teamImageData: Data? = nil, unreadConversationCount: Int = 0, loginCredentials: LoginCredentials? = nil) { self.userName = userName self.userIdentifier = userIdentifier self.teamName = teamName self.imageData = imageData self.teamImageData = teamImageData self.unreadConversationCount = unreadConversationCount self.loginCredentials = loginCredentials super.init() } /// Updates the properties of the receiver with the given account. Use this method /// when you wish to update an exisiting account object with newly fetched properties /// from the account store. /// public func updateWith(_ account: Account) { guard self.userIdentifier == account.userIdentifier else { return } self.userName = account.userName self.teamName = account.teamName self.imageData = account.imageData self.teamImageData = account.teamImageData self.loginCredentials = account.loginCredentials } public override func isEqual(_ object: Any?) -> Bool { guard let other = object as? Account else { return false } return userIdentifier == other.userIdentifier } public override var hash: Int { return userIdentifier.hashValue } public override var debugDescription: String { return "<Account>:\n\tname: \(userName)\n\tid: \(userIdentifier)\n\tcredentials:\n\t\(String(describing: loginCredentials?.debugDescription))\n\tteam: \(String(describing: teamName))\n\timage: \(String(describing: imageData?.count))\n\tteamImageData: \(String(describing: teamImageData?.count))\n" } } // MARK: - Serialization Helper extension Account { func write(to url: URL) throws { let encoder = JSONEncoder() let data = try encoder.encode(self) try data.write(to: url, options: [.atomic]) } static func load(from url: URL) -> Account? { let data = try? Data(contentsOf: url) let decoder = JSONDecoder() return data.flatMap { try? decoder.decode(Account.self, from: $0) } } }
gpl-3.0
ed937f65ff8e5559626e1ce55cdf94d6
35.243697
305
0.667749
4.80825
false
false
false
false
yangjw/LockScreenMedia
LockScreenMedia/LockScreenSf.swift
1
2991
// // LockScreenSf.swift // LockScreenMedia // // Created by njdby on 15/11/20. // Copyright © 2015年 njdby. All rights reserved. // import Foundation import UIKit import MediaPlayer class LockScreenSf: UIViewController { override func restoreUserActivityState(activity: NSUserActivity) { super.restoreUserActivityState(activity) } override func viewDidLoad() { super.viewDidLoad() create() } func create(){ let mpic = MPNowPlayingInfoCenter.defaultCenter() mpic.nowPlayingInfo = [ MPMediaItemPropertyTitle:"This Is a Test", MPMediaItemPropertyArtist:"Matt Neuburg" ] let dict = NSMutableDictionary() dict.setValue("alex", forKey: "name") dict.setValue("123456", forKey: "password") print("\(dict)") var airs = [String:AnyObject]() airs["name"] = "alex" // airs.removeValueForKey("name") // airs.updateValue("joke", forKey: "name") var ary = [String]() ary.append("粤菜") ary.append("淮扬菜") airs["ary"] = ary var json = [String:AnyObject]() json["data"] = airs var nums = [Int](count: 0, repeatedValue: 0) for var i = 1 ; i <= 9 ;i++ { nums.append(i) } print("\(nums)") json["nums"] = nums let local = UILocalizedIndexedCollation.currentCollation() print("\(local.sectionIndexTitles)") json["local"] = local.sectionIndexTitles print("\(json)") // let decimalInteger = 17 // let binaryInteger = 0b10001 // 17 in binary notation // let octalInteger = 0o12 // 17 in octal notation // let hexadecimalInteger = 0x11 // 17 in hexadecimal notation for num in 1..<9 { print("\(num)") } print("平均数\(avarage(nums))") print("平均数\(newAvarage(nums, sum: sums))") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func avarage(nums:[Int]) -> Int { func sum(nums:[Int]) -> Int { var sums = 0 for num in nums { sums = sums + num } print("\(sums)") return sums } return sum(nums)/(nums.count) } func newAvarage(nums:[Int], sum: [Int] -> Int) -> Int { return sum(nums)/nums.count } func sums(nums:[Int]) -> Int { var sums = 0 for num in nums { sums = sums + num } print("\(sums)") return sums } }
mit
e571db8b070b091bfdff761100395ae3
23.92437
81
0.517869
4.521341
false
false
false
false
jmgc/swift
test/IRGen/actor_class_forbid_objc_assoc_objects.swift
1
1105
// RUN: %target-swift-frontend -enable-experimental-concurrency -emit-ir %s | %FileCheck %s // REQUIRES: concurrency // REQUIRES: objc_interop import _Concurrency // CHECK: @_METACLASS_DATA__TtC37actor_class_forbid_objc_assoc_objects5Actor = internal constant { {{.*}} } { i32 [[METAFLAGS:1153]], // CHECK: @_DATA__TtC37actor_class_forbid_objc_assoc_objects5Actor = internal constant { {{.*}} } { i32 [[OBJECTFLAGS:1152|1216]], final actor class Actor { } // CHECK: @_METACLASS_DATA__TtC37actor_class_forbid_objc_assoc_objects6Actor2 = internal constant { {{.*}} } { i32 [[METAFLAGS]], // CHECK: @_DATA__TtC37actor_class_forbid_objc_assoc_objects6Actor2 = internal constant { {{.*}} } { i32 [[OBJECTFLAGS]], actor class Actor2 { } // CHECK: @_METACLASS_DATA__TtC37actor_class_forbid_objc_assoc_objects6Actor3 = internal constant { {{.*}} } { i32 [[METAFLAGS]], // CHECK: @_DATA__TtC37actor_class_forbid_objc_assoc_objects6Actor3 = internal constant { {{.*}} } { i32 [[OBJECTFLAGS]], class Actor3 : Actor2 {} actor class GenericActor<T> { var state: T init(state: T) { self.state = state } }
apache-2.0
5653cb2fe902351d3aac31748132604d
43.2
133
0.688688
3.269231
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/CoreData/FetchedProperty.swift
1
1278
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import Kanna extension CoreData { public struct FetchedProperty { public let name: String public let isOptional: Bool public let fetchRequest: FetchRequest public let userInfo: [String: Any] } } private enum XML { fileprivate enum Attributes { static let name = "name" static let isOptional = "optional" } static let fetchRequestPath = "fetchRequest" static let userInfoPath = "userInfo" } extension CoreData.FetchedProperty { init(with object: Kanna.XMLElement) throws { guard let name = object[XML.Attributes.name] else { throw CoreData.ParserError.invalidFormat(reason: "Missing required fetched property name.") } guard let fetchRequest = try object.at_xpath(XML.fetchRequestPath).map(CoreData.FetchRequest.init(with:)) else { throw CoreData.ParserError.invalidFormat(reason: "Missing required fetch request") } let isOptional = object[XML.Attributes.isOptional].flatMap(Bool.init(from:)) ?? false let userInfo = try object.at_xpath(XML.userInfoPath).map { try CoreData.UserInfo.parse(from: $0) } ?? [:] self.init(name: name, isOptional: isOptional, fetchRequest: fetchRequest, userInfo: userInfo) } }
mit
cb312986529d27d3c0432a4b2a1b9da5
28.022727
116
0.722005
4.299663
false
false
false
false
JustasL/mapbox-navigation-ios
MapboxNavigation/RouteTableViewHeaderView.swift
1
1862
import UIKit protocol RouteTableViewHeaderViewDelegate: class { func didTapCancel() } //This could be final @IBDesignable class RouteTableViewHeaderView: UIView { //Some of these could be private @IBOutlet weak var progressBarWidthConstraint: NSLayoutConstraint! @IBOutlet private var progressBar: ProgressBar! //Why did progressBar had outlet, even though was not used? @IBOutlet weak var distanceRemaining: SubtitleLabel! @IBOutlet weak var timeRemaining: TitleLabel! @IBOutlet weak var etaLabel: TitleLabel! @IBOutlet weak var dividerView: SeparatorView! weak var delegate: RouteTableViewHeaderViewDelegate? override func awakeFromNib() { super.awakeFromNib() //clear default values from the storyboard so user does not see a 'flash' of random values distanceRemaining.text = "" timeRemaining .text = "" etaLabel .text = "" //Don't care, just hide it (because sometimes progress bar 'unloads') //TODO: Investigate why modified steps have odd behaviour progressBar .isHidden = true distanceRemaining.isHidden = true timeRemaining .isHidden = true } override var intrinsicContentSize: CGSize { get { return CGSize(width: bounds.width, height: 80) } } // Set the progress between 0.0-1.0 @IBInspectable var progress: CGFloat = 0 { didSet { if (progressBarWidthConstraint != nil) { progressBarWidthConstraint.constant = bounds.width * progress UIView.animate(withDuration: 0.5) { [weak self] in self?.layoutIfNeeded() } } } } @IBAction func didTapCancel(_ sender: Any) { delegate?.didTapCancel() } }
isc
8a2899c3be57a81ecf7626e8258de64b
32.25
111
0.631579
5.18663
false
false
false
false
nathawes/swift
test/SILOptimizer/definite_init_failable_initializers_diagnostics.swift
20
4186
// RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module -verify %s // RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module -verify %s // High-level tests that DI rejects certain invalid idioms for early // return from initializers. // <rdar://problem/19267795> failable initializers that call noreturn function produces bogus diagnostics class FailableInitThatFailsReallyHard { init?() { // no diagnostics generated. fatalError("bad") } } // Failable initializers must produce correct diagnostics struct A { var x: Int // expected-note {{'self.x' not initialized}} init?(i: Int) { if i > 0 { self.x = i } } // expected-error {{return from initializer without initializing all stored properties}} } // Delegating, failable initializers that doesn't initialize along all paths must produce correct diagnostics. extension Int { init?(i: Int) { if i > 0 { self.init(i) } } // expected-error {{'self.init' isn't called on all paths before returning from initializer}} } class BaseClass {} final class DerivedClass : BaseClass { init(x : ()) { fatalError("bad") // no diagnostics. } } func something(_ x: Int) {} func something(_ x: inout Int) {} func something(_ x: AnyObject) {} func something(_ x: Any.Type) {} // <rdar://problem/22946400> DI needs to diagnose self usages in error block // // FIXME: bad QoI class ErrantBaseClass { init() throws {} } class ErrantClass : ErrantBaseClass { let x: Int var y: Int override init() throws { x = 10 y = 10 try super.init() } init(invalidEscapeDesignated: ()) { x = 10 y = 10 do { try super.init() } catch {} } // expected-error {{'self' used inside 'catch' block reachable from super.init call}} init(invalidEscapeDesignated2: ()) throws { x = 10 y = 10 do { try super.init() } catch { try super.init() // expected-error {{'self' used inside 'catch' block reachable from super.init call}} } } init(invalidEscapeDesignated3: ()) { x = 10 y = 10 do { try super.init() } catch { print(self.x) // expected-error {{'self' used inside 'catch' block reachable from super.init call}} self.y = 20 // expected-error {{'self' used inside 'catch' block reachable from super.init call}} } } // expected-error {{'self' used inside 'catch' block reachable from super.init call}} init(invalidEscapeDesignated4: ()) throws { x = 10 y = 10 do { try super.init() } catch let e { print(self.x) // expected-error {{'self' used inside 'catch' block reachable from super.init call}} throw e } } convenience init(invalidEscapeConvenience: ()) { do { try self.init() } catch {} } // expected-error {{'self.init' isn't called on all paths}} convenience init(okEscapeConvenience2: ()) throws { do { try self.init() } catch { try self.init() } } convenience init(invalidEscapeConvenience3: ()) throws { do { try self.init() } catch let e { print(self) // expected-error {{'self' used before 'self.init'}} throw e } } init(noEscapeDesignated: ()) throws { x = 10 y = 10 do { try super.init() } catch let e { throw e // ok } } convenience init(noEscapeConvenience: ()) throws { do { try self.init() } catch let e { throw e // ok } } convenience init(invalidAccess: ()) throws { do { try self.init() } catch let e { something(x) // expected-error {{'self' used before 'self.init'}} something(self.x) // expected-error {{'self' used before 'self.init'}} something(y) // expected-error {{'self' used before 'self.init'}} something(self.y) // expected-error {{'self' used before 'self.init'}} something(&y) // expected-error {{'self' used before 'self.init'}} something(&self.y) // expected-error {{'self' used before 'self.init'}} something(self) // expected-error {{'self' used before 'self.init'}} something(type(of: self)) throw e } } }
apache-2.0
be18db99ae84a277de122f29670f4197
24.216867
110
0.618729
3.764388
false
false
false
false
vinted/vinted-ab-ios
vinted-ab-iosTests/VNTABTestVariantTests.swift
2
1980
import Nimble import Quick @testable import vinted_ab_ios fileprivate enum ModelType: String { case full case required } class VNTABTestVariantTests: QuickSpec { override func spec() { let bundle = Bundle(for: type(of: self)) describe("Initialization") { it("initializes model") { let object = VNTABTestVariant.mappedObject(bundle: bundle, index: ModelType.required.rawValue) expect(object).toNot(beNil()) } it("sets required properties") { guard let object = VNTABTestVariant.mappedObject(bundle: bundle, index: ModelType.required.rawValue) else { fail() return } guard let dict = jsonFileDictionary(forType: VNTABTestVariant.self, bundle: bundle, index: ModelType.required.rawValue) else { fail() return } guard let dictChanceWeight = dict["chance_weight"] as? Int else { fail() return } expect(object.chanceWeight).to(equal(dictChanceWeight)) expect(object.name).to(beNil()) } it("sets optional properties") { guard let object = VNTABTestVariant.mappedObject(bundle: bundle, index: ModelType.full.rawValue) else { fail() return } guard let dict = jsonFileDictionary(forType: VNTABTestVariant.self, bundle: bundle, index: ModelType.full.rawValue) else { fail() return } guard let dictName = dict["name"] as? String else { fail() return } expect(object.name).to(equal(dictName)) } } } }
mit
2a0810b3b592ac92e966bf62ec9c9bdd
33.736842
142
0.49798
5.395095
false
true
false
false
sschiau/swift
stdlib/public/Darwin/Accelerate/vDSP_Convolution.swift
8
30269
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: One-dimensional convolution /// Returns one-dimensional convolution, single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter kernel: Single-precision convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, withKernel kernel: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let n = vector.count - kernel.count let result = Array<Float>(unsafeUninitializedCapacity: n) { buffer, initializedCount in convolve(vector, withKernel: kernel, result: &buffer) initializedCount = n } return result } /// One-dimensional convolution, single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, withKernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count >= n + kernel.count - 1, "Source vector count must be at least the sum of the result and kernel counts, minus one.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_conv(src.baseAddress!, 1, k.baseAddress!.advanced(by: kernel.count - 1), -1, dest.baseAddress!, 1, vDSP_Length(n), vDSP_Length(kernel.count)) } } } } /// Returns one-dimensional convolution, double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter kernel: Double-precision convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, withKernel kernel: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let n = vector.count - kernel.count let result = Array<Double>(unsafeUninitializedCapacity: n) { buffer, initializedCount in convolve(vector, withKernel: kernel, result: &buffer) initializedCount = n } return result } /// One-dimensional convolution, double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter kernel: Double-precision convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, withKernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count >= n + kernel.count - 1, "Source vector count must be at least the sum of the result and kernel counts, minus one.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_convD(src.baseAddress!, 1, k.baseAddress!.advanced(by: kernel.count - 1), -1, dest.baseAddress!, 1, vDSP_Length(n), vDSP_Length(kernel.count)) } } } } // MARK: One-dimensional correlation /// Returns one-dimensional correlation, single-precision. /// /// - Parameter vector: The vector to correlate. /// - Parameter kernel: Single-precision convolution kernel. /// - Returns: Correlation result. @inlinable public static func correlate<T, U>(_ vector: T, withKernel kernel: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let n = vector.count - kernel.count let result = Array<Float>(unsafeUninitializedCapacity: n) { buffer, initializedCount in correlate(vector, withKernel: kernel, result: &buffer) initializedCount = n } return result } /// One-dimensional correlation, single-precision. /// /// - Parameter vector: The vector to correlate. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func correlate<T, U, V>(_ vector: T, withKernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { let n = result.count precondition(vector.count >= n + kernel.count - 1, "Source vector count must be at least the sum of the result and kernel counts, minus one.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_conv(src.baseAddress!, 1, k.baseAddress!, 1, dest.baseAddress!, 1, vDSP_Length(n), vDSP_Length(kernel.count)) } } } } /// Returns one-dimensional correlation, double-precision. /// /// - Parameter vector: The vector to correlate. /// - Parameter kernel: Single-precision convolution kernel. /// - Returns: Correlation result. @inlinable public static func correlate<T, U>(_ vector: T, withKernel kernel: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let n = vector.count - kernel.count let result = Array<Double>(unsafeUninitializedCapacity: n) { buffer, initializedCount in correlate(vector, withKernel: kernel, result: &buffer) initializedCount = n } return result } /// One-dimensional correlation, double-precision. /// /// - Parameter vector: The vector to correlate. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func correlate<T, U, V>(_ vector: T, withKernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { let n = result.count precondition(vector.count >= n + kernel.count - 1, "Source vector count must be at least the sum of the result and kernel counts, minus one.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_convD(src.baseAddress!, 1, k.baseAddress!, 1, dest.baseAddress!, 1, vDSP_Length(n), vDSP_Length(kernel.count)) } } } } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { // MARK: Two-dimensional convolution /// Returns two-dimensional convolution with a 3 x 3 kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision 3x3 convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, with3x3Kernel kernel: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, with3x3Kernel: kernel, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with a 3 x 3 kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision 3x3 convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, with3x3Kernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernel.count == 9, "Kernel must contain 9 elements.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_f3x3(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!) } } } } /// Returns two-dimensional convolution with a 3 x 3 kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Double-precision 3x3 convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, with3x3Kernel kernel: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, with3x3Kernel: kernel, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with a 3 x 3 kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Double-precision 3x3 convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, with3x3Kernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernel.count == 9, "Kernel must contain 9 elements.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_f3x3D(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!) } } } } /// Returns two-dimensional convolution with a 5 x 5 kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision 5x5 convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, with5x5Kernel kernel: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, with5x5Kernel: kernel, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with a 5 x 5 kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision 5x5 convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, with5x5Kernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernel.count == 25, "Kernel must contain 25 elements.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_f5x5(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!) } } } } /// Returns two-dimensional convolution with a 5 x 5 kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Double-precision 3x3 convolution kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, with5x5Kernel kernel: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, with5x5Kernel: kernel, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with a 5 x 5 kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Double-precision 5x5 convolution kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, with5x5Kernel kernel: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernel.count == 25, "Kernel must contain 25 elements.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_f5x5D(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!) } } } } /// Returns two-dimensional convolution with arbitrarily sized kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter kernelRowCount: The number of rows in the kernel. /// - Parameter kernelColumnCount: The number of columns in the kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, withKernel kernel: U, kernelRowCount: Int, kernelColumnCount: Int) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, withKernel: kernel, kernelRowCount: kernelRowCount, kernelColumnCount: kernelColumnCount, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with arbitrarily sized kernel; single-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter kernelRowCount: The number of rows in the kernel. /// - Parameter kernelColumnCount: The number of columns in the kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, withKernel kernel: U, kernelRowCount: Int, kernelColumnCount: Int, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernelRowCount % 2 == 1, "Kernel row count must be odd.") precondition(kernelColumnCount % 2 == 1, "Kernel column count must be odd.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_imgfir(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!, vDSP_Length(kernelRowCount), vDSP_Length(kernelColumnCount)) } } } } /// Returns two-dimensional convolution with arbitrarily sized kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Single-precision convolution kernel. /// - Parameter kernelRowCount: The number of rows in the kernel. /// - Parameter kernelColumnCount: The number of columns in the kernel. /// - Returns: Convolution result. @inlinable public static func convolve<T, U>(_ vector: T, rowCount: Int, columnCount: Int, withKernel kernel: U, kernelRowCount: Int, kernelColumnCount: Int) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: vector.count) { buffer, initializedCount in convolve(vector, rowCount: rowCount, columnCount: columnCount, withKernel: kernel, kernelRowCount: kernelRowCount, kernelColumnCount: kernelColumnCount, result: &buffer) initializedCount = vector.count } return result } /// Two-dimensional convolution with arbitrarily sized kernel; double-precision. /// /// - Parameter vector: The vector to convolve. /// - Parameter rowCount: The number of rows in the input vector. /// - Parameter columnCount: The number of columns in the input vector. /// - Parameter kernel: Double-precision convolution kernel. /// - Parameter kernelRowCount: The number of rows in the kernel. /// - Parameter kernelColumnCount: The number of columns in the kernel. /// - Parameter result: Destination vector. @inlinable public static func convolve<T, U, V>(_ vector: T, rowCount: Int, columnCount: Int, withKernel kernel: U, kernelRowCount: Int, kernelColumnCount: Int, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { precondition(rowCount >= 3, "Row count must be greater than or equal to 3.") precondition(columnCount >= 4, "Column count must be even and greater than or equal to 4") precondition(rowCount * columnCount == vector.count, "Row count `x` column count must equal source vector count.") precondition(kernelRowCount % 2 == 1, "Kernel row count must be odd.") precondition(kernelColumnCount % 2 == 1, "Kernel column count must be odd.") result.withUnsafeMutableBufferPointer { dest in vector.withUnsafeBufferPointer { src in kernel.withUnsafeBufferPointer { k in vDSP_imgfirD(src.baseAddress!, vDSP_Length(rowCount), vDSP_Length(columnCount), k.baseAddress!, dest.baseAddress!, vDSP_Length(kernelRowCount), vDSP_Length(kernelColumnCount)) } } } } }
apache-2.0
d2cb42daf14f7359f98e014335b618b5
40.407661
116
0.50299
5.876335
false
false
false
false
belkevich/DTModelStorage
DTModelStorage/Memory/MemoryStorage.swift
1
16925
// // MemoryStorage.swift // DTModelStorageTests // // Created by Denys Telezhkin on 10.07.15. // Copyright (c) 2015 Denys Telezhkin. 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. /// This struct contains error types that can be thrown for various MemoryStorage errors public struct MemoryStorageErrors { /// Errors that can happen when inserting items into memory storage public enum Insertion: ErrorType { case IndexPathTooBig } /// Errors that can happen when replacing item in memory storage public enum Replacement: ErrorType { case ItemNotFound } /// Errors that can happen when removing item from memory storage public enum Removal : ErrorType { case ItemNotFound } } /// This class represents model storage in memory. /// /// `MemoryStorage` stores data models like array of `SectionModel` instances. It has various methods for changing storage contents - add, remove, insert, replace e.t.c. /// - Note: It also notifies it's delegate about underlying changes so that delegate can update interface accordingly /// - SeeAlso: `SectionModel` public class MemoryStorage: BaseStorage, StorageProtocol { /// sections of MemoryStorage public var sections: [Section] = [SectionModel]() /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func objectAtIndexPath(path: NSIndexPath) -> Any? { let sectionModel : SectionModel if path.section >= self.sections.count { return nil } else { sectionModel = self.sections[path.section] as! SectionModel if path.item >= sectionModel.numberOfObjects { return nil } } return sectionModel.objects[path.item] } /// Set section header model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section header at index /// - Parameter sectionIndex: index of section for setting header public func setSectionHeaderModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling setSectionHeaderModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryHeaderKind!) } /// Set section footer model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section footer at index /// - Parameter sectionIndex: index of section for setting footer public func setSectionFooterModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling setSectionFooterModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryFooterKind!) } /// Set supplementaries for specific kind. Usually it's header or footer kinds. /// - Parameter models: supplementary models for sections /// - Parameter kind: supplementary kind public func setSupplementaries<T>(models : [T], forKind kind: String) { self.startUpdate() if models.count == 0 { for index in 0..<self.sections.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(nil, forKind: kind) } return } self.getValidSection(models.count - 1) for index in 0..<models.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(models[index], forKind: kind) } self.finishUpdate() } /// Set section header models. /// - Note: `supplementaryHeaderKind` property should be set before calling this method. /// - Parameter models: section header models public func setSectionHeaderModels<T>(models : [T]) { assert(self.supplementaryHeaderKind != nil, "Please set supplementaryHeaderKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryHeaderKind!) } /// Set section footer models. /// - Note: `supplementaryFooterKind` property should be set before calling this method. /// - Parameter models: section footer models public func setSectionFooterModels<T>(models : [T]) { assert(self.supplementaryFooterKind != nil, "Please set supplementaryFooterKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryFooterKind!) } /// Set items for specific section. This will reload UI after updating. /// - Parameter items: items to set for section /// - Parameter forSectionIndex: index of section to update public func setItems<T>(items: [T], forSectionIndex index: Int) { let section = self.sectionAtIndex(index) section.objects.removeAll(keepCapacity: false) for item in items { section.objects.append(item) } self.delegate?.storageNeedsReloading() } /// Add items to section with `toSection` number. /// - Parameter items: items to add /// - Parameter toSection: index of section to add items public func addItems<T>(items: [T], toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) for item in items { let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) } self.finishUpdate() } /// Add item to section with `toSection` number. /// - Parameter item: item to add /// - Parameter toSection: index of section to add item public func addItem<T>(item: T, toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) self.finishUpdate() } /// Insert item to indexPath /// - Parameter item: item to insert /// - Parameter toIndexPath: indexPath to insert /// - Throws: if indexPath is too big, will throw MemoryStorageErrors.Insertion.IndexPathTooBig public func insertItem<T>(item: T, toIndexPath indexPath: NSIndexPath) throws { self.startUpdate() let section = self.getValidSection(indexPath.section) guard section.objects.count > indexPath.item else { throw MemoryStorageErrors.Insertion.IndexPathTooBig } section.objects.insert(item, atIndex: indexPath.item) self.currentUpdate?.insertedRowIndexPaths.append(indexPath) self.finishUpdate() } /// Reload item /// - Parameter item: item to reload. public func reloadItem<T:Equatable>(item: T) { self.startUpdate() if let indexPath = self.indexPathForItem(item) { self.currentUpdate?.updatedRowIndexPaths.append(indexPath) } self.finishUpdate() } /// Replace item `itemToReplace` with `replacingItem`. /// - Parameter itemToReplace: item to replace /// - Parameter replacingItem: replacing item /// - Throws: if `itemToReplace` is not found, will throw MemoryStorageErrors.Replacement.ItemNotFound public func replaceItem<T: Equatable, U:Equatable>(itemToReplace: T, replacingItem: U) throws { self.startUpdate() defer { self.finishUpdate() } guard let originalIndexPath = self.indexPathForItem(itemToReplace) else { throw MemoryStorageErrors.Replacement.ItemNotFound } let section = self.getValidSection(originalIndexPath.section) section.objects[originalIndexPath.item] = replacingItem self.currentUpdate?.updatedRowIndexPaths.append(originalIndexPath) } /// Remove item `item`. /// - Parameter item: item to remove /// - Throws: if item is not found, will throw MemoryStorageErrors.Removal.ItemNotFound public func removeItem<T:Equatable>(item: T) throws { self.startUpdate() defer { self.finishUpdate() } guard let indexPath = self.indexPathForItem(item) else { throw MemoryStorageErrors.Removal.ItemNotFound } self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } /// Remove items /// - Parameter items: items to remove /// - Note: Any items that were not found, will be skipped public func removeItems<T:Equatable>(items: [T]) { self.startUpdate() let indexPaths = self.indexPathArrayForItems(items) for item in items { if let indexPath = self.indexPathForItem(item) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) } } self.currentUpdate?.deletedRowIndexPaths.appendContentsOf(indexPaths) self.finishUpdate() } /// Remove items at index paths. /// - Parameter indexPaths: indexPaths to remove item from. Any indexPaths that will not be found, will be skipped public func removeItemsAtIndexPaths(indexPaths : [NSIndexPath]) { self.startUpdate() let reverseSortedIndexPaths = self.dynamicType.sortedArrayOfIndexPaths(indexPaths, ascending: false) for indexPath in reverseSortedIndexPaths { if let _ = self.objectAtIndexPath(indexPath) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } } self.finishUpdate() } /// Delete sections in indexSet /// - Parameter sections: sections to delete public func deleteSections(sections : NSIndexSet) { self.startUpdate() for var i = sections.lastIndex; i != NSNotFound; i = sections.indexLessThanIndex(i) { self.sections.removeAtIndex(i) } self.currentUpdate?.deletedSectionIndexes.addIndexes(sections) self.finishUpdate() } } // MARK: - Searching in storage extension MemoryStorage { /// Retrieve items in section /// - Parameter section: index of section /// - Returns array of items in section or nil, if section does not exist public func itemsInSection(section: Int) -> [Any]? { if self.sections.count > section { return self.sections[section].objects } return nil } /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func itemAtIndexPath(indexPath: NSIndexPath) -> Any? { return self.objectAtIndexPath(indexPath) } /// Find index path of specific item in MemoryStorage /// - Parameter searchableItem: item to find /// - Returns: index path for found item, nil if not found public func indexPathForItem<T: Equatable>(searchableItem : T) -> NSIndexPath? { for sectionIndex in 0..<self.sections.count { let rows = self.sections[sectionIndex].objects for rowIndex in 0..<rows.count { if let item = rows[rowIndex] as? T { if item == searchableItem { return NSIndexPath(forItem: rowIndex, inSection: sectionIndex) } } } } return nil } /// Retrieve section model for specific section. /// - Parameter sectionIndex: index of section /// - Note: if section did not exist prior to calling this, it will be created, and UI updated. public func sectionAtIndex(sectionIndex : Int) -> SectionModel { self.startUpdate() let section = self.getValidSection(sectionIndex) self.finishUpdate() return section } /// Find-or-create section func getValidSection(sectionIndex : Int) -> SectionModel { if sectionIndex < self.sections.count { return self.sections[sectionIndex] as! SectionModel } else { for i in self.sections.count...sectionIndex { self.sections.append(SectionModel()) self.currentUpdate?.insertedSectionIndexes.addIndex(i) } } return self.sections.last as! SectionModel } /// Index path array for items func indexPathArrayForItems<T:Equatable>(items:[T]) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for index in 0..<items.count { if let indexPath = self.indexPathForItem(items[index]) { indexPaths.append(indexPath) } } return indexPaths } /// Sorted array of index paths - useful for deletion. class func sortedArrayOfIndexPaths(indexPaths: [NSIndexPath], ascending: Bool) -> [NSIndexPath] { let unsorted = NSMutableArray(array: indexPaths) let descriptor = NSSortDescriptor(key: "self", ascending: ascending) return unsorted.sortedArrayUsingDescriptors([descriptor]) as! [NSIndexPath] } } // MARK: - HeaderFooterStorageProtocol extension MemoryStorage :HeaderFooterStorageProtocol { /// Header model for section. /// - Requires: supplementaryHeaderKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: header model for section, or nil if there are no model public func headerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling headerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryHeaderKind!, sectionIndex: index) } /// Footer model for section. /// - Requires: supplementaryFooterKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: footer model for section, or nil if there are no model public func footerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling footerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryFooterKind!, sectionIndex: index) } } // MARK: - SupplementaryStorageProtocol extension MemoryStorage : SupplementaryStorageProtocol { /// Retrieve supplementary model of specific kind for section. /// - Parameter kind: kind of supplementary model /// - Parameter sectionIndex: index of section /// - SeeAlso: `headerModelForSectionIndex` /// - SeeAlso: `footerModelForSectionIndex` public func supplementaryModelOfKind(kind: String, sectionIndex: Int) -> Any? { let sectionModel : SectionModel if sectionIndex >= self.sections.count { return nil } else { sectionModel = self.sections[sectionIndex] as! SectionModel } return sectionModel.supplementaryModelOfKind(kind) } }
mit
368f26d017b72705b845929bfcb8ea56
38.919811
170
0.664165
4.980871
false
false
false
false
PJayRushton/stats
Stats/ShowMessage.swift
1
790
// // ShowMessage.swift // Stats // // Created by Parker Rushton on 4/20/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import Whisper struct ShowMessage: Command { var title: String var barColor: UIColor var textColor: UIColor init(title: String, barColor: UIColor = UIColor.mainAppColor, textColor: UIColor = .white) { self.title = title self.barColor = barColor self.textColor = textColor } func execute(state: AppState, core: Core<AppState>) { let font = FontType.lemonMilk.font(withSize: 10) let murmur = Murmur(title: title, backgroundColor: barColor, titleColor: textColor, font: font, action: nil) show(whistle: murmur, action: WhistleAction.show(1)) } }
mit
c6fea8ac5af859c93ac35257105b6952
25.3
116
0.653992
3.984848
false
false
false
false
zhuli8com/SwiftPractice
SwiftPractice/SwiftPractice/Network/Network.swift
1
2750
// // Network.swift // SwiftPractice // https://lvwenhan.com/ios/456.html // // Created by lizhu on 15/11/11. // Copyright © 2015年 zhuli. All rights reserved. // import Foundation extension Network:CustomStringConvertible, CustomDebugStringConvertible { // var description:String{ return "Network遵循CustomStringConvertible" } var debugDescription:String{ return "Network遵循CustomDebugStringConvertible" } } class Network { static func request(method:String, url:String, params:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>(), callback:(data:NSData?,response:NSURLResponse?,error:NSError?) -> Void){ let session=NSURLSession.sharedSession() var newURL=url if method=="GET"{ newURL+="?"+Network().buildParams(params) } let request=NSMutableURLRequest(URL: NSURL(string: newURL)!) request.HTTPMethod=method if method == "POST" { request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.HTTPBody = Network().buildParams(params).dataUsingEncoding(NSUTF8StringEncoding) } let task=session.dataTaskWithRequest(request) { (data, response, error) -> Void in callback(data: data,response: response,error: error) } task.resume() } func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<){ let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return (components.map{"\($0)=\($1)"} as [String]).joinWithSeparator("&") } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.appendContentsOf([(escape(key), escape("\(value)"))]) } return components } func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } }
gpl-2.0
ce3f616e7506cbb15cb160f85a546864
33.670886
193
0.606791
4.865009
false
false
false
false
nathantannar4/InputBarAccessoryView
Example/Sources/InputBar Examples/NoTextViewInputBar.swift
1
1368
// // NoTextViewInputBar.swift // Example // // Created by Nathan Tannar on 2018-11-21. // Copyright © 2018 Nathan Tannar. All rights reserved. // import UIKit import InputBarAccessoryView final class NoTextViewInputBar: InputBarAccessoryView { let joinButton: UIButton = { let button = UIButton() button.setTitle("Join Chat", for: .normal) button.setTitleColor(.white, for: .normal) button.layer.cornerRadius = 10 button.backgroundColor = .systemBlue return button }() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { joinButton.heightAnchor.constraint(equalToConstant: 44).isActive = true setStackViewItems([], forStack: .right, animated: false) setRightStackViewWidthConstant(to: 0, animated: false) setMiddleContentView(joinButton, animated: false) joinButton.addTarget(self, action: #selector(joinPressed), for: .touchUpInside) } @objc func joinPressed() { setMiddleContentView(inputTextView, animated: false) setStackViewItems([sendButton], forStack: .right, animated: false) setRightStackViewWidthConstant(to: 52, animated: false) } }
mit
cb94f1a6e6ce786fbebd119926bdf817
28.085106
87
0.671544
4.46732
false
false
false
false
edstewbob/cs193p-winter-2015
GraphingCalculator/GraphingCalculator/CalculatorViewController.swift
2
5408
// // CalculatorViewController.swift // GraphingCalculator // // Created by jrm on 4/5/15. // Copyright (c) 2015 Riesam LLC. All rights reserved. // import UIKit class CalculatorViewController: UIViewController { @IBOutlet weak var history: UILabel! @IBOutlet weak var display: UILabel! var userIsInTheMiddleOfTypingANumber = false var numberHasADecimalPoint = false var brain = CalculatorBrain() @IBAction func back(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { if count(display.text!) > 0 { var text = display.text! text = dropLast(text) if count(text) > 0 { display.text = text }else{ display.text = " " } } }else{ //remove last item from program/brain opStack if let result = brain.removeLast() { displayValue = result } else { displayValue = 0 } updateUI() } //addToHistory("🔙") } @IBAction func plusMinus(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { //change the sign of the number and allow typing to continue var text = display.text! if(text[text.startIndex] == "-"){ display.text = dropFirst(text) }else{ display.text = "-" + text } //addToHistory("±") }else{ operate(sender) } } @IBAction func appendDigit(sender: UIButton) { if let digit = sender.currentTitle{ if( numberHasADecimalPoint && digit == "."){ // do nothing additional decimal point is not allowed }else { if (digit == "."){ numberHasADecimalPoint = true } if userIsInTheMiddleOfTypingANumber { var text = display.text! if(text[text.startIndex] == "0"){ text = dropFirst(text) } display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTypingANumber = true } } //println("digit = \(digit)") } updateUI() } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber { enter() } if let operation = sender.currentTitle { if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = nil } } updateUI() } @IBAction func clear(sender: UIButton) { display.text = " " brain.clear() brain.variableValues.removeValueForKey("M") updateUI() } @IBAction func enter() { userIsInTheMiddleOfTypingANumber = false if let value = displayValue{ if let result = brain.pushOperand(value) { displayValue = result } else { displayValue = nil } }else { displayValue = nil } updateUI() } @IBAction func saveMemory() { if let value = displayValue { brain.variableValues["M"] = value } userIsInTheMiddleOfTypingANumber = false if let result = brain.evaluate() { displayValue = result } else { displayValue = nil } updateUI() } @IBAction func loadMemory() { if let result = brain.pushOperand("M") { displayValue = result } else { displayValue = nil } updateUI() } var displayValue: Double? { get { return NSNumberFormatter().numberFromString(display.text!)?.doubleValue } set { if let value = newValue{ display.text = "\(value)" } else { //if let result = brain.evaluateAndReportErrors() as? String { // display.text = result //} else { display.text = " " //} } userIsInTheMiddleOfTypingANumber = false } } func updateUI(){ history.text = brain.description } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ var destination = segue.destinationViewController as? UIViewController if let navCon = destination as? UINavigationController { destination = navCon.visibleViewController } if let identifier = segue.identifier { switch identifier { case "Show Graph View": if let gvc = destination as? GraphViewController { //println("CVC.prepareForSegue: brain.program \(brain.program) ") gvc.program = brain.program } default: break } } } }
mit
ea5ded90dc22211b5e07936fde0e6461
26.85567
89
0.486306
5.706441
false
false
false
false
juliensagot/JSNavigationController
ExampleStoryboard/ExampleStoryboard/SecondVCBarViewController.swift
1
1401
import AppKit class SecondVCBarViewController: NSViewController { @IBOutlet var backButton: NSButton? @IBOutlet var titleLabel: NSTextField? @IBOutlet var thirdButton: NSButton? @IBOutlet var fourthButton: NSButton? // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true } override func viewDidAppear() { super.viewDidAppear() view.translatesAutoresizingMaskIntoConstraints = false view.superview?.addConstraints(viewConstraints()) } override func viewWillDisappear() { view.superview?.removeConstraints(viewConstraints()) } // MARK: - Layout fileprivate func viewConstraints() -> [NSLayoutConstraint] { let left = NSLayoutConstraint( item: view, attribute: .left, relatedBy: .equal, toItem: view.superview, attribute: .left, multiplier: 1.0, constant: 0.0 ) let right = NSLayoutConstraint( item: view, attribute: .right, relatedBy: .equal, toItem: view.superview, attribute: .right, multiplier: 1.0, constant: 0.0 ) let top = NSLayoutConstraint( item: view, attribute: .top, relatedBy: .equal, toItem: view.superview, attribute: .top, multiplier: 1.0, constant: 0.0 ) let bottom = NSLayoutConstraint( item: view, attribute: .bottom, relatedBy: .equal, toItem: view.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0 ) return [left, right, top, bottom] } }
mit
ea64c69fd33f1500ffc1356903cc3da4
27.591837
61
0.718772
3.677165
false
false
false
false
CodaFi/Parsimmon
Parsimmon/Parser.swift
1
2525
// // Parser.swift // Parsimmon // // Created by Robert Widmann on 1/14/15. // Copyright (c) 2015 TypeLift. All rights reserved. // public struct Parser<S, A, B> { let fun : Source<S, A> -> (Reply<B>, Source<S, A>) public func flatMap<C>(f : B -> Parser<S, A, C>) -> Parser<S, A, C> { return Parser<S, A, C>({ s in let (r, s) = self.fun(s) switch r { case .Consume: return (.Consume, s) case .Failure: return (.Failure, s) case let .Success(b): return f(b).fun(s) } }) } } public func current<S, A>() -> Parser<S, A, A> { return Parser({ s in return (.Success(s.cur), s) }) } public func lookAhead<S, A, B>(p : Parser<S, A, B>) -> Parser<S, A, B> { return Parser({ s in let (r, _) = p.fun(s) return (r, s) }) } public func negate<S, A, B>(p : Parser<S, A, B>) -> Parser<S, A, ()> { return Parser({ s in let (r, s) = p.fun(s) return (Reply.negate(r), s) }) } public func map<S, A, B, C>(p : Parser<S, A, B>, f : B -> C) -> Parser<S, A, C> { return Parser({ s in let (r, s) = p.fun(s) return (Reply.map(f, r: r), s) }) } public func choose<S, A, B, C>(p : Parser<S, A, B>, f : B -> Optional<C>) -> Parser<S, A, C> { return Parser({ s in let (r, s) = p.fun(s) return (Reply.choose(f, r: r), s) }) } public func <* <S, A, B, C>(p : Parser<S, A, B>, q : Parser<S, A, C>) -> Parser<S, A, B> { return Parser({ s in let (r, s) = p.fun(s) switch r { case .Consume: return (.Consume, s) case .Failure: return (.Failure, s) case let .Success(p): let (r, s) = q.fun(s) return (Reply.put(p, r: r), s) } }) } public func *> <S, A, B, C>(p : Parser<S, A, B>, q : Parser<S, A, C>) -> Parser<S, A, C> { return Parser({ s in let (r, s) = p.fun(s) switch r { case .Consume: return (.Consume, s) case .Failure: return (.Failure, s) case let .Success(_): return q.fun(s) } }) } public func both<S, A, B, C>(p : Parser<S, A, B>, q : Parser<S, A, C>) -> Parser<S, A, (B, C)> { return Parser({ s in let (r, s) = p.fun(s) switch r { case .Consume: return (.Consume, s) case .Failure: return (.Failure, s) case let .Success(p): let (r, s) = q.fun(s) return (Reply.map({ q in (p, q) }, r: r), s) } }) } public func <|> <S, A, B>(p : Parser<S, A, B>, q : Parser<S, A, B>) -> Parser<S, A, B> { return Parser({ s in let (r, sp) = p.fun(s) switch r { case .Consume: fallthrough case .Failure: return q.fun(s) case let .Success(p): return (.Success(p), sp) } }) }
mit
c463923c41ca71ae8f5334863c8d37ec
20.218487
96
0.525941
2.297543
false
false
false
false
sachinvas/Swifter
SwifterSwiftTests/CGFloatExtensionsTests.swift
1
1375
// // CGFloatExtensionsTests.swift // SwifterSwift // // Created by Omar Albeik on 8/27/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import XCTest @testable import SwifterSwift class CGFloatExtensionsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAbs() { XCTAssert(CGFloat(-9.3).abs == CGFloat(9.3), "Couldn't get correct value for \(#function)") } func testCeil() { XCTAssert(CGFloat(9.3).ceil == CGFloat(10.0), "Couldn't get correct value for \(#function)") } func testDegreesToRadians() { XCTAssert(CGFloat(180).degreesToRadians == CGFloat(M_PI), "Couldn't get correct value for \(#function)") } func testRandomBetween() { XCTAssert(CGFloat.randomBetween(min: 1, max: 5) > 0 && CGFloat.randomBetween(min: 1, max: 5) < 5, "Couldn't get correct value for \(#function)") } func testFloor() { XCTAssert(CGFloat(9.3).floor == CGFloat(9.0), "Couldn't get correct value for \(#function)") } func testRadiansToDegrees() { XCTAssert(CGFloat(M_PI).radiansToDegrees == CGFloat(180), "Couldn't get correct value for \(#function)") } }
mit
85956a460962066eab2ed67a5a40b015
28.234043
146
0.694323
3.587467
false
true
false
false
zjjzmw1/myGifSwift
Pods/SwiftDate/Sources/SwiftDate/CalendarName.swift
5
7832
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // 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: - CalendarName Shortcut /// This enum allows you set a valid calendar using swift's type safe support public enum CalendarName { case current, currentAutoUpdating case gregorian, buddhist, chinese, coptic, ethiopicAmeteMihret, ethiopicAmeteAlem, hebrew, iso8601, indian, islamic, islamicCivil, japanese, persian, republicOfChina, islamicTabular, islamicUmmAlQura /// Return a new `Calendar` instance from a given identifier public var calendar: Calendar { var identifier: Calendar.Identifier switch self { case .current: return Calendar.current case .currentAutoUpdating: return Calendar.autoupdatingCurrent case .gregorian: identifier = Calendar.Identifier.gregorian case .buddhist: identifier = Calendar.Identifier.buddhist case .chinese: identifier = Calendar.Identifier.chinese case .coptic: identifier = Calendar.Identifier.coptic case .ethiopicAmeteMihret: identifier = Calendar.Identifier.ethiopicAmeteMihret case .ethiopicAmeteAlem: identifier = Calendar.Identifier.ethiopicAmeteAlem case .hebrew: identifier = Calendar.Identifier.hebrew case .iso8601: identifier = Calendar.Identifier.iso8601 case .indian: identifier = Calendar.Identifier.indian case .islamic: identifier = Calendar.Identifier.islamic case .islamicCivil: identifier = Calendar.Identifier.islamicCivil case .japanese: identifier = Calendar.Identifier.japanese case .persian: identifier = Calendar.Identifier.persian case .republicOfChina: identifier = Calendar.Identifier.republicOfChina case .islamicTabular: identifier = Calendar.Identifier.islamicTabular case .islamicUmmAlQura: identifier = Calendar.Identifier.islamicUmmAlQura } return Calendar(identifier: identifier) } } //MARK: Calendar.Component Extension extension Calendar.Component { fileprivate var cfValue: CFCalendarUnit { return CFCalendarUnit(rawValue: self.rawValue) } } extension Calendar.Component { /// https://github.com/apple/swift-corelibs-foundation/blob/swift-DEVELOPMENT-SNAPSHOT-2016-09-10-a/CoreFoundation/Locale.subproj/CFCalendar.h#L68-L83 internal var rawValue: UInt { switch self { case .era: return 1 << 1 case .year: return 1 << 2 case .month: return 1 << 3 case .day: return 1 << 4 case .hour: return 1 << 5 case .minute: return 1 << 6 case .second: return 1 << 7 case .weekday: return 1 << 9 case .weekdayOrdinal: return 1 << 10 case .quarter: return 1 << 11 case .weekOfMonth: return 1 << 12 case .weekOfYear: return 1 << 13 case .yearForWeekOfYear: return 1 << 14 case .nanosecond: return 1 << 15 case .calendar: return 1 << 16 case .timeZone: return 1 << 17 } } internal init?(rawValue: UInt) { switch rawValue { case Calendar.Component.era.rawValue: self = .era case Calendar.Component.year.rawValue: self = .year case Calendar.Component.month.rawValue: self = .month case Calendar.Component.day.rawValue: self = .day case Calendar.Component.hour.rawValue: self = .hour case Calendar.Component.minute.rawValue: self = .minute case Calendar.Component.second.rawValue: self = .second case Calendar.Component.weekday.rawValue: self = .weekday case Calendar.Component.weekdayOrdinal.rawValue: self = .weekdayOrdinal case Calendar.Component.quarter.rawValue: self = .quarter case Calendar.Component.weekOfMonth.rawValue: self = .weekOfMonth case Calendar.Component.weekOfYear.rawValue: self = .weekOfYear case Calendar.Component.yearForWeekOfYear.rawValue: self = .yearForWeekOfYear case Calendar.Component.nanosecond.rawValue: self = .nanosecond case Calendar.Component.calendar.rawValue: self = .calendar case Calendar.Component.timeZone.rawValue: self = .timeZone default: return nil } } } //MARK: - Calendar Extension extension Calendar { // The code below is part of the Swift.org code. It is included as rangeOfUnit is a very useful // function for the startOf and endOf functions. // As always we would prefer using Foundation code rather than inventing code ourselves. typealias CFType = CFCalendar private var cfObject: CFType { return unsafeBitCast(self as NSCalendar, to: CFCalendar.self) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// `public func rangeOfUnit(unit: NSCalendarUnit, startDate datep: /// AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: /// UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool` /// which is not implementable on Linux due to the lack of being able to properly implement /// AutoreleasingUnsafeMutablePointer. /// /// - parameters: /// - component: the unit to determine the range for /// - date: the date to wrap the unit around /// - returns: the range (date interval) of the unit around the date /// /// - Experiment: This is a draft API currently under consideration for official import into /// Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the /// near future /// public func rangex(of component: Calendar.Component, for date: Date) -> DateTimeInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp -> Bool in return withUnsafeMutablePointer(to: &ti) { tip -> Bool in let startPtr: UnsafeMutablePointer<CFAbsoluteTime> = startp let tiPtr: UnsafeMutablePointer<CFTimeInterval> = tip return CFCalendarGetTimeRangeOfUnit(cfObject, component.cfValue, date.timeIntervalSinceReferenceDate, startPtr, tiPtr) } } if res { let startDate = Date(timeIntervalSinceReferenceDate: start) return DateTimeInterval(start: startDate, duration: ti) } return nil } /// Create a new NSCalendar instance from CalendarName structure. You can also use /// <CalendarName>.calendar to get a new instance of NSCalendar with picked type. /// /// - parameter type: type of the calendar /// /// - returns: instance of the new Calendar public static func fromType(_ type: CalendarName) -> Calendar { return type.calendar } }
mit
41e58bc5d11add0321c759f3fef1e82f
42.270718
151
0.718335
4.203972
false
false
false
false
justinhester/hacking-with-swift
src/Project33/Project33/AddCommentsViewController.swift
1
2598
// // AddCommentsViewController.swift // Project33 // // Created by Justin Lawrence Hester on 2/19/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // import UIKit class AddCommentsViewController: UIViewController, UITextViewDelegate { var genre: String! var comments: UITextView! let placeholder = "If you have any additional comments " + "that might help identify your tune, enter them here." override func loadView() { super.loadView() comments = UITextView() comments.translatesAutoresizingMaskIntoConstraints = false comments.delegate = self comments.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) view.addSubview(comments) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|[comments]|", options: .AlignAllCenterX, metrics: nil, views: ["comments": comments] ) ) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|[comments]|", options: .AlignAllCenterX, metrics: nil, views: ["comments": comments] ) ) } override func viewDidLoad() { super.viewDidLoad() title = "Comments" navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Submit", style: .Plain, target: self, action: "submitTapped" ) comments.text = placeholder } func submitTapped() { let vc = SubmitViewController() vc.genre = genre if comments.text == placeholder { vc.comments = "" } else { vc.comments = comments.text } navigationController?.pushViewController(vc, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textViewDidBeginEditing(textView: UITextView) { if textView.text == placeholder { textView.text = "" } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
b8940995eaa86345a71b7ee631e348e4
26.924731
106
0.601848
5.549145
false
false
false
false
santosli/100-Days-of-Swift-3
Project 02/Project 02/ViewController.swift
1
1828
// // ViewController.swift // Project 02 // // Created by Santos on 20/10/2016. // Copyright © 2016 santos. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var countNumber: UILabel! @IBOutlet weak var tapOrHoldButton: UIButton! var counter = 0 var timer = Timer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapOnce(_:))) let holdGestrue = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:))) tapGesture.numberOfTapsRequired = 1 tapOrHoldButton.addGestureRecognizer(tapGesture) tapOrHoldButton.addGestureRecognizer(holdGestrue) updateCountNumber() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tapOnce(_ sender: UIGestureRecognizer) { print("tap once") counter += 1 updateCountNumber() } func longTap(_ sender: UIGestureRecognizer) { print("long tap") if sender.state == .ended { timer.invalidate() } else if sender.state == .began { timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(countNumberPlusOne), userInfo: nil, repeats: true) } } func countNumberPlusOne() { counter += 1 updateCountNumber() } func updateCountNumber() { countNumber.text = String(counter) } @IBAction func resetCountNumber(_ sender: AnyObject) { counter = 0 updateCountNumber() } }
apache-2.0
2642d7735af5f819f74ebecc2df1ebd1
25.867647
144
0.6289
4.859043
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/Register/RegisterPickSkillsSelectSkillsTransitionManager.swift
1
2918
// // RegisterPickSkillsSelectSkillsTransitionManager.swift // Yep // // Created by NIX on 15/4/20. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit final class RegisterPickSkillsSelectSkillsTransitionManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var isPresentation = false // MARK: UIViewControllerTransitioningDelegate func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresentation = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresentation = false return self } // MARK: UIViewControllerAnimatedTransitioning func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.6 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) let toView = transitionContext.viewForKey(UITransitionContextToViewKey) let containerView = transitionContext.containerView() if isPresentation { if let view = toView { containerView?.addSubview(view) } } let animatingVC = isPresentation ? toVC! : fromVC! let animatingView = isPresentation ? toView! : fromView! let onScreenFrame = transitionContext.finalFrameForViewController(animatingVC) let offScreenFrame = CGRectOffset(onScreenFrame, 0, CGRectGetHeight(onScreenFrame)) let (initialFrame, finalFrame) = isPresentation ? (offScreenFrame, onScreenFrame) : (onScreenFrame, offScreenFrame) animatingView.frame = initialFrame if self.isPresentation { animatingView.alpha = 0 } else { animatingView.alpha = 1 } UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: [.AllowUserInteraction, .BeginFromCurrentState], animations: { [unowned self] in animatingView.frame = finalFrame if self.isPresentation { animatingView.alpha = 1 } else { animatingView.alpha = 0 } }, completion: { [unowned self] _ in if !self.isPresentation { fromView?.removeFromSuperview() } transitionContext.completeTransition(true) }) } }
mit
87b3d3623dd4d917b888deb4eb02a329
31.764045
217
0.700617
6.582393
false
false
false
false
ericwastaken/Xcode_Playgrounds
Playgrounds/Binary Tree Into List.playground/Contents.swift
1
1493
import Foundation public class BinaryTree<T: Equatable>: CustomStringConvertible { var value: T public var ln: BinaryTree<T>? var rn: BinaryTree<T>? public var description: String { return "(\(self.value)) -> [\(self.ln) - \(self.rn)]" } init (rootValue: T) { value = rootValue } // Implement Equatable static public func == (lhs:BinaryTree<T>, rhs:BinaryTree<T>) -> Bool { // Check the value if lhs.value != rhs.value { return false } // Check the left node and nil if (lhs.ln == nil && rhs.ln != nil) || (lhs.ln != nil && rhs.ln == nil) { return false } // Check the left node proper if let lhsnode = lhs.ln, let rhsnode = rhs.ln { if !(lhsnode == rhsnode) { return false } } // Check the right node and nil if (lhs.rn == nil && rhs.rn != nil) || (lhs.rn != nil && rhs.rn == nil) { return false } // Check the right node proper if let lhsnode = lhs.rn, let rhsnode = rhs.rn { if !(lhsnode == rhsnode) { return false } } return true } } func sibling<T>(tree: BinaryTree<T>, value:Int) { } let myTree = BinaryTree<Int>(rootValue: 10) let leftNode = BinaryTree<Int>(rootValue: 11) myTree.ln = leftNode myTree == myTree
unlicense
37800b76bd34de306d1da4db00835e60
20.637681
81
0.498995
4.112948
false
false
false
false
Jamonek/School-For-Me
School For Me/MapVCExt.swift
1
6986
// // MapVCExt.swift // School For Me // // Created by Jamone Alexander Kelly on 12/7/15. // Copyright © 2015 Jamone Kelly. All rights reserved. // import Foundation import UIKit import MapKit import CoreLocation import FontAwesomeKit import RealmSwift import Async extension MapVC: MKMapViewDelegate, UISearchBarDelegate { @objc func presentSearchView(_ sender: UIButton) { //self.navigationController!.navigationBarHidden = !self.navigationController!.navigationBarHidden //MVTopConstraint.constant = 45 self.performSegue(withIdentifier: "searchSegue", sender: self) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.navigationController!.isNavigationBarHidden = !self.navigationController!.isNavigationBarHidden MVTopConstraint.constant = 0 } @objc func dismissSearch(_ sender: AnyObject) { if self.searchBar.isFirstResponder { self.resignFirstResponder() } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } else if annotation.isKind(of: SchoolAnnotation.self) { if let pinView: MKPinAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView { pinView.annotation = annotation return pinView } else { let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin") pinView.pinTintColor = UIColor.red return pinView } } return nil } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { if mapView.viewWithTag(309) != nil { print(mapView.subviews) for subView in mapView.subviews { if subView.tag == 309 { subView.removeFromSuperview() } } } let (x, y) = (mapView.bounds.width, mapView.bounds.height) let specialView: UIView = UIView(frame: CGRect(x: 0, y: y*0.42, width: x, height: y*0.6)) let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = specialView.bounds specialView.addSubview(blurEffectView) specialView.tag = 309 let (sX, sY) = (specialView.bounds.width, specialView.bounds.height) // better way to do all of this too // get details var sData: [School]! var data: Results<School>! let realm = try! Realm() let sID = (view.annotation as! SchoolAnnotation).schoolID let filter: NSPredicate = NSPredicate(format: "%K = %@", "id", String(sID!)) data = realm.objects(School.self).filter(filter) sData = data.map{ $0 } // :< // Set our global var for passing selected location data Global.schoolID = (sData[0].id as NSString).integerValue // Preview Labels let schoolNameLabel = UILabel() schoolNameLabel.text = "School" let schoolNameLabelContent = UILabel() schoolNameLabelContent.text = sData[0].school_name let districtNameLabel = UILabel() districtNameLabel.text = "District" let districtNameLabelContent = UILabel() districtNameLabelContent.text = sData[0].district let gradesNameLabel = UILabel() gradesNameLabel.text = "Grades" let gradesLabelContent = UILabel() gradesLabelContent.text = "\(sData[0].low_grade) - \(sData[0].high_grade)" let phoneNumberLabel = UILabel() phoneNumberLabel.text = "Call" let phoneNumberLabelContent = UILabel() phoneNumberLabelContent.text = sData[0].phone // lil bit of number magic :o // definitely a better way to do this lol I'll come back to it as well schoolNameLabel.frame = CGRect(x: sX*0.22, y: sY * 0.1, width: 15, height: 20) schoolNameLabel.sizeToFit() schoolNameLabel.textColor = UIColor.gray specialView.addSubview(schoolNameLabel) schoolNameLabelContent.frame = CGRect(x: sX*0.4, y: sY*0.1, width: 15, height: 20) schoolNameLabelContent.sizeToFit() specialView.addSubview(schoolNameLabelContent) districtNameLabel.frame = CGRect(x: sX*0.22, y: sY * 0.2, width: 15, height: 20) districtNameLabel.sizeToFit() districtNameLabel.textColor = UIColor.gray specialView.addSubview(districtNameLabel) districtNameLabelContent.frame = CGRect(x: sX*0.4, y: sY*0.2, width: 150, height: 35) districtNameLabelContent.numberOfLines = 0 districtNameLabelContent.sizeToFit() specialView.addSubview(districtNameLabelContent) gradesNameLabel.frame = CGRect(x: sX*0.22, y: sY*0.39, width: 15, height: 20) gradesNameLabel.sizeToFit() gradesNameLabel.textColor = UIColor.gray specialView.addSubview(gradesNameLabel) gradesLabelContent.frame = CGRect(x: sX*0.4, y: sY*0.39, width: 15, height: 20) gradesLabelContent.sizeToFit() specialView.addSubview(gradesLabelContent) phoneNumberLabel.frame = CGRect(x: sX*0.22, y: sY*0.48, width: 15, height: 20) phoneNumberLabel.sizeToFit() phoneNumberLabel.textColor = UIColor.gray specialView.addSubview(phoneNumberLabel) phoneNumberLabelContent.frame = CGRect(x: sX*0.4, y: sY*0.48, width: 15, height: 20) phoneNumberLabelContent.sizeToFit() //phoneNumberLabelContent.editable = false // When I switch back to `UITextView` //phoneNumberLabelContent.dataDetectorTypes = .PhoneNumber specialView.addSubview(phoneNumberLabelContent) let seeMoreButton = UIButton() seeMoreButton.frame = CGRect(x: sX*0.22, y: sY*0.65, width: 200, height: 20) seeMoreButton.setAttributedTitle(NSAttributedString(string: "Expand", font: UIFont.boldSystemFont(ofSize: 16), kerning: 1.0, color: UIColor.flatSkyBlue()), for: []) seeMoreButton.backgroundColor = UIColor.clear seeMoreButton.addTarget(self, action: #selector(UIViewController.showDetailTV(_:)), for: .touchUpInside) specialView.addSubview(seeMoreButton) mapView.addSubview(specialView) } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { for subView in mapView.subviews { if subView.tag == 309 { UIView.animate(withDuration: 1.0, animations: { subView.removeFromSuperview() // So this didn't work how I expected.. I'll come back to it }) } } } }
apache-2.0
06e311586736a17f2803a7431ea178d4
39.375723
172
0.632498
4.754935
false
false
false
false
rhx/SwiftGtk
Sources/Gtk/Dialog.swift
1
12686
// // Dialog.swift // Gtk // // Created by Rene Hexel on 4/8/19. // Copyright © 2019, 2020 Rene Hexel. All rights reserved. // import CGtk import GtkCHelpers public extension Dialog { /// Convenience constructor to create a dialog with a single button. /// This creates a new GtkDialog with title `title` (or `NULL` for the default title; see gtk_window_set_title()). /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// The button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// @param title Title of the dialog /// @param parent parent window /// @param flags flags to use such as `GTK_DIALOG_MODAL` /// @param first_button_text text to display for the button /// @param response_type any positive number, or one of the values in the `GtkResponseType` enumeration. /// - Parameter title: Title of the dialog /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter text: title of the button /// - Parameter responseType: response type for the button (default: `.accept`) @inlinable convenience init(title: UnsafePointer<gchar>! = nil, flags: DialogFlags = .modal, text: String, responseType: ResponseType = .ok) { self.init(retainingCPointer: gtk_c_helper_dialog_new_with_button(title, nil, flags.value, text, responseType)) } /// Convenience constructor to create a dialog with a single button. /// This creates a new GtkDialog with title `title` (or `NULL` for the default title; see gtk_window_set_title()) /// and transient parent parent. /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// The button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// @param title /// @param parent /// @param flags flags to use such as `GTK_DIALOG_MODAL` /// @param first_button_text text to display for the button /// @param response_type any positive number, or one of the values in the `GtkResponseType` enumeration. /// - Parameter title: Title of the dialog /// - Parameter parent: parent window /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter text: title of the button /// - Parameter responseType: response type for the button @inlinable convenience init<W: WindowProtocol>(title: UnsafePointer<gchar>! = nil, parent: W, flags: DialogFlags = .modal, text: String, responseType: ResponseType = .ok) { let dialog = parent.window_ptr.withMemoryRebound(to: GtkWindow.self, capacity: 1) { gtk_c_helper_dialog_new_with_button(title, $0, flags.value, text, responseType)! } self.init(retainingCPointer: dialog) } /// Convenience constructor to create a dialog with two buttons. /// This creates a new GtkDialog with title `title` (or NULL for the default title; see gtk_window_set_title()) /// and transient parent parent. /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// Each button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// - Parameter title: Title of the dialog /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter firstText: title of the first button /// - Parameter firstResponseType: response type for the first button /// - Parameter secondText: title of the second button /// - Parameter secondResponseType: response type for the second button @inlinable convenience init(title: UnsafePointer<gchar>! = nil, flags: DialogFlags = .modal, firstText: String, firstResponseType: ResponseType = .cancel, secondText: String, secondResponseType: ResponseType = .ok) { self.init(retainingCPointer: gtk_c_helper_dialog_new_with_two_buttons(title, nil, flags.value, firstText, firstResponseType, secondText, secondResponseType)) } /// Convenience constructor to create a dialog with two buttons. /// This creates a new GtkDialog with title `title` (or NULL for the default title; see gtk_window_set_title()) /// and transient parent parent. /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// Each button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// - Parameter title: Title of the dialog /// - Parameter parent: parent window /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter firstText: title of the first button /// - Parameter firstResponseType: response type for the first button /// - Parameter secondText: title of the second button /// - Parameter secondResponseType: response type for the second button @inlinable convenience init<W: WindowProtocol>(title: UnsafePointer<gchar>! = nil, parent: W, flags: DialogFlags = .modal, firstText: String, firstResponseType: ResponseType = .cancel, secondText: String, secondResponseType: ResponseType = .ok) { let dialog = parent.window_ptr.withMemoryRebound(to: GtkWindow.self, capacity: 1) { gtk_c_helper_dialog_new_with_two_buttons(title, $0, flags.value, firstText, firstResponseType, secondText, secondResponseType)! } self.init(retainingCPointer: dialog) } /// Convenience constructor to create a dialog with three buttons. /// This creates a new GtkDialog with title `title` (or NULL for the default title; see gtk_window_set_title()) /// and transient parent parent. /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// Each button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// - Parameter title: Title of the dialog /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter firstText: title of the first button /// - Parameter firstResponseType: response type for the first button /// - Parameter secondText: title of the second button /// - Parameter secondResponseType: response type for the second button /// - Parameter thirdText: title of the third button /// - Parameter thirdResponseType: response type for the third button @inlinable convenience init(title: UnsafePointer<gchar>! = nil, flags: DialogFlags = .modal, firstText: String, firstResponseType: ResponseType = .help, secondText: String, secondResponseType: ResponseType = .cancel, thirdText: String, thirdResponseType: ResponseType = .ok) { self.init(retainingCPointer: gtk_c_helper_dialog_new_with_three_buttons(title, nil, flags.value, firstText, firstResponseType, secondText, secondResponseType, thirdText, thirdResponseType)) } /// Convenience constructor to create a dialog with three buttons. /// This creates a new GtkDialog with title `title` (or NULL for the default title; see gtk_window_set_title()) /// and transient parent parent. /// The `flags` argument can be used to make the dialog modal (GTK_DIALOG_MODAL) /// and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). /// After `flags`, the button text and response ID pairs should be listed. /// Each button text can be an arbitrary text. /// If the user clicks the dialog button, `GtkDialog` will emit the "response" signal /// with the corresponding response ID. /// If a GtkDialog receives the “delete-event” signal, it will emit ::response /// with a response ID of `GTK_RESPONSE_DELETE_EVENT`. /// However, destroying a dialog does not emit the ::response signal; /// so be careful relying on ::response when using the `GTK_DIALOG_DESTROY_WITH_PARENT` flag. /// Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog. /// - Parameter title: Title of the dialog /// - Parameter parent: parent window /// - Parameter flags: flags to use such as `.modal` (default) or `.destroy_with_parent` /// - Parameter firstText: title of the first button /// - Parameter firstResponseType: response type for the first button /// - Parameter secondText: title of the second button /// - Parameter secondResponseType: response type for the second button /// - Parameter thirdText: title of the third button /// - Parameter thirdResponseType: response type for the third button @inlinable convenience init<W: WindowProtocol>(title: UnsafePointer<gchar>! = nil, parent: W, flags: DialogFlags = .modal, firstText: String, firstResponseType: ResponseType = .help, secondText: String, secondResponseType: ResponseType = .cancel, thirdText: String, thirdResponseType: ResponseType = .ok) { let dialog = parent.window_ptr.withMemoryRebound(to: GtkWindow.self, capacity: 1) { gtk_c_helper_dialog_new_with_three_buttons(title, $0, flags.value, firstText, firstResponseType, secondText, secondResponseType, thirdText, thirdResponseType)! } self.init(retainingCPointer: dialog) } }
bsd-2-clause
869ced220ff2c877b46e10b128096891
70.9375
310
0.705474
4.177169
false
false
false
false
tuffz/pi-weather-app
Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftObjectInterfaceTests.swift
1
21947
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm import Foundation #if swift(>=3.0) class OuterClass { class InnerClass { } } class SwiftStringObjectSubclass : SwiftStringObject { var stringCol2 = "" } class SwiftSelfRefrencingSubclass: SwiftStringObject { dynamic var objects = RLMArray(objectClassName: SwiftSelfRefrencingSubclass.className()) } class SwiftDefaultObject: RLMObject { dynamic var intCol = 1 dynamic var boolCol = true override class func defaultPropertyValues() -> [AnyHashable : Any]? { return ["intCol": 2] } } class SwiftOptionalNumberObject: RLMObject { dynamic var intCol: NSNumber? = 1 dynamic var floatCol: NSNumber? = 2.2 as Float as NSNumber dynamic var doubleCol: NSNumber? = 3.3 dynamic var boolCol: NSNumber? = true } class SwiftObjectInterfaceTests: RLMTestCase { // Swift models func testSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = SwiftObject() realm.add(obj) obj.boolCol = true obj.intCol = 1234 obj.floatCol = 1.1 obj.doubleCol = 2.2 obj.stringCol = "abcd" obj.binaryCol = "abcd".data(using: String.Encoding.utf8) obj.dateCol = Date(timeIntervalSince1970: 123) obj.objectCol = SwiftBoolObject() obj.objectCol.boolCol = true obj.arrayCol.add(obj.objectCol) try! realm.commitWriteTransaction() let data = "abcd".data(using: String.Encoding.utf8) let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, true, "should be true") XCTAssertEqual(firstObj.intCol, 1234, "should be 1234") XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1") XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2") XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 123), "should be epoch + 123") XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true") XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1") XCTAssertEqual((obj.arrayCol.firstObject() as? SwiftBoolObject)!.boolCol, true, "should be true") } func testDefaultValueSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() realm.add(SwiftObject()) try! realm.commitWriteTransaction() let data = "a".data(using: String.Encoding.utf8) let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, false, "should be false") XCTAssertEqual(firstObj.intCol, 123, "should be 123") XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23") XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3") XCTAssertEqual(firstObj.stringCol, "a", "should be a") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 1), "should be epoch + 1") XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false") XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero") } func testMergedDefaultValuesSwiftObject() { let realm = self.realmWithTestPath() realm.beginWriteTransaction() _ = SwiftDefaultObject.create(in: realm, withValue: NSDictionary()) try! realm.commitWriteTransaction() let object = SwiftDefaultObject.allObjects(in: realm).firstObject() as! SwiftDefaultObject XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value") XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key") } func testSubclass() { // test className methods XCTAssertEqual("SwiftStringObject", SwiftStringObject.className()) XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className()) let realm = RLMRealm.default() realm.beginWriteTransaction() _ = SwiftStringObject.createInDefaultRealm(withValue: ["string"]) _ = SwiftStringObjectSubclass.createInDefaultRealm(withValue: ["string", "string2"]) try! realm.commitWriteTransaction() // ensure creation in proper table XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count) XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count) try! realm.transaction { // create self referencing subclass let sub = SwiftSelfRefrencingSubclass.createInDefaultRealm(withValue: ["string", []]) let sub2 = SwiftSelfRefrencingSubclass() sub.objects.add(sub2) } } func testOptionalNSNumberProperties() { let realm = realmWithTestPath() let no = SwiftOptionalNumberObject() XCTAssertEqual([.int, .float, .double, .bool], no.objectSchema.properties.map { $0.type }) XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(true, no.boolCol!) try! realm.transaction { realm.add(no) no.intCol = nil no.floatCol = nil no.doubleCol = nil no.boolCol = nil } XCTAssertNil(no.intCol) XCTAssertNil(no.floatCol) XCTAssertNil(no.doubleCol) XCTAssertNil(no.boolCol) try! realm.transaction { no.intCol = 1.1 no.floatCol = 2.2 as Float as NSNumber no.doubleCol = 3.3 no.boolCol = false } XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(false, no.boolCol!) } func testOptionalSwiftProperties() { let realm = realmWithTestPath() try! realm.transaction { realm.add(SwiftOptionalObject()) } let firstObj = SwiftOptionalObject.allObjects(in: realm).firstObject() as! SwiftOptionalObject XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) try! realm.transaction { firstObj.optObjectCol = SwiftBoolObject() firstObj.optObjectCol!.boolCol = true firstObj.optStringCol = "Hi!" firstObj.optNSStringCol = "Hi!" firstObj.optBinaryCol = Data(bytes: "hi", count: 2) firstObj.optDateCol = Date(timeIntervalSinceReferenceDate: 10) } XCTAssertTrue(firstObj.optObjectCol!.boolCol) XCTAssertEqual(firstObj.optStringCol!, "Hi!") XCTAssertEqual(firstObj.optNSStringCol!, "Hi!") XCTAssertEqual(firstObj.optBinaryCol!, Data(bytes: "hi", count: 2)) XCTAssertEqual(firstObj.optDateCol!, Date(timeIntervalSinceReferenceDate: 10)) try! realm.transaction { firstObj.optObjectCol = nil firstObj.optStringCol = nil firstObj.optNSStringCol = nil firstObj.optBinaryCol = nil firstObj.optDateCol = nil } XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) } func testSwiftClassNameIsDemangled() { XCTAssertEqual(SwiftObject.className(), "SwiftObject", "Calling className() on Swift class should return demangled name") } // Objective-C models // Note: Swift doesn't support custom accessor names // so we test to make sure models with custom accessors can still be accessed func testCustomAccessors() { let realm = realmWithTestPath() realm.beginWriteTransaction() let ca = CustomAccessorsObject.create(in: realm, withValue: ["name", 2]) XCTAssertEqual(ca.name!, "name", "name property should be name.") ca.age = 99 XCTAssertEqual(ca.age, Int32(99), "age property should be 99") try! realm.commitWriteTransaction() } func testClassExtension() { let realm = realmWithTestPath() realm.beginWriteTransaction() let bObject = BaseClassStringObject() bObject.intCol = 1 bObject.stringCol = "stringVal" realm.add(bObject) try! realm.commitWriteTransaction() let objectFromRealm = BaseClassStringObject.allObjects(in: realm)[0] as! BaseClassStringObject XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1") XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal") } func testCreateOrUpdate() { let realm = RLMRealm.default() realm.beginWriteTransaction() _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 1]) let objects = SwiftPrimaryStringObject.allObjects(); XCTAssertEqual(objects.count, UInt(1), "Should have 1 object"); XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 1, "Value should be 1"); _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["stringCol": "string2", "intCol": 2]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") _ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 3]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 3, "Value should be 3"); try! realm.commitWriteTransaction() } // if this fails (and you haven't changed the test module name), the checks // for swift class names and the demangling logic need to be updated func testNSStringFromClassDemangledTopLevelClassNames() { XCTAssertEqual(NSStringFromClass(OuterClass.self), "Tests.OuterClass") } // if this fails (and you haven't changed the test module name), the prefix // check in RLMSchema initialization needs to be updated func testNestedClassNameMangling() { XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC5Tests10OuterClass10InnerClass") } } #else class OuterClass { class InnerClass { } } class SwiftStringObjectSubclass : SwiftStringObject { var stringCol2 = "" } class SwiftSelfRefrencingSubclass: SwiftStringObject { dynamic var objects = RLMArray(objectClassName: SwiftSelfRefrencingSubclass.className()) } class SwiftDefaultObject: RLMObject { dynamic var intCol = 1 dynamic var boolCol = true override class func defaultPropertyValues() -> [NSObject : AnyObject]? { return ["intCol": 2] } } class SwiftOptionalNumberObject: RLMObject { dynamic var intCol: NSNumber? = 1 dynamic var floatCol: NSNumber? = 2.2 as Float dynamic var doubleCol: NSNumber? = 3.3 as Double dynamic var boolCol: NSNumber? = true } class SwiftObjectInterfaceTests: RLMTestCase { // Swift models func testSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = SwiftObject() realm.addObject(obj) obj.boolCol = true obj.intCol = 1234 obj.floatCol = 1.1 obj.doubleCol = 2.2 obj.stringCol = "abcd" obj.binaryCol = "abcd".dataUsingEncoding(NSUTF8StringEncoding) obj.dateCol = NSDate(timeIntervalSince1970: 123) obj.objectCol = SwiftBoolObject() obj.objectCol.boolCol = true obj.arrayCol.addObject(obj.objectCol) try! realm.commitWriteTransaction() let data = NSString(string: "abcd").dataUsingEncoding(NSUTF8StringEncoding) let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, true, "should be true") XCTAssertEqual(firstObj.intCol, 1234, "should be 1234") XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1") XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2") XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 123), "should be epoch + 123") XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true") XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1") XCTAssertEqual((obj.arrayCol.firstObject() as? SwiftBoolObject)!.boolCol, true, "should be true") } func testDefaultValueSwiftObject() { let realm = realmWithTestPath() realm.beginWriteTransaction() realm.addObject(SwiftObject()) try! realm.commitWriteTransaction() let data = NSString(string: "a").dataUsingEncoding(NSUTF8StringEncoding) let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as! SwiftObject XCTAssertEqual(firstObj.boolCol, false, "should be false") XCTAssertEqual(firstObj.intCol, 123, "should be 123") XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23") XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3") XCTAssertEqual(firstObj.stringCol, "a", "should be a") XCTAssertEqual(firstObj.binaryCol!, data!) XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 1), "should be epoch + 1") XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false") XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero") } func testMergedDefaultValuesSwiftObject() { let realm = self.realmWithTestPath() realm.beginWriteTransaction() SwiftDefaultObject.createInRealm(realm, withValue: NSDictionary()) try! realm.commitWriteTransaction() let object = SwiftDefaultObject.allObjectsInRealm(realm).firstObject() as! SwiftDefaultObject XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value") XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key") } func testSubclass() { // test className methods XCTAssertEqual("SwiftStringObject", SwiftStringObject.className()) XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className()) let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() SwiftStringObject.createInDefaultRealmWithValue(["string"]) SwiftStringObjectSubclass.createInDefaultRealmWithValue(["string", "string2"]) try! realm.commitWriteTransaction() // ensure creation in proper table XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count) XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count) try! realm.transactionWithBlock { // create self referencing subclass let sub = SwiftSelfRefrencingSubclass.createInDefaultRealmWithValue(["string", []]) let sub2 = SwiftSelfRefrencingSubclass() sub.objects.addObject(sub2) } } func testOptionalNSNumberProperties() { let realm = realmWithTestPath() let no = SwiftOptionalNumberObject() XCTAssertEqual([.Int, .Float, .Double, .Bool], no.objectSchema.properties.map { $0.type }) XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(true, no.boolCol!) try! realm.transactionWithBlock { realm.addObject(no) no.intCol = nil no.floatCol = nil no.doubleCol = nil no.boolCol = nil } XCTAssertNil(no.intCol) XCTAssertNil(no.floatCol) XCTAssertNil(no.doubleCol) XCTAssertNil(no.boolCol) try! realm.transactionWithBlock { no.intCol = 1.1 no.floatCol = 2.2 as Float no.doubleCol = 3.3 no.boolCol = false } XCTAssertEqual(1, no.intCol!) XCTAssertEqual(2.2 as Float, no.floatCol!) XCTAssertEqual(3.3, no.doubleCol!) XCTAssertEqual(false, no.boolCol!) } func testOptionalSwiftProperties() { let realm = realmWithTestPath() try! realm.transactionWithBlock { realm.addObject(SwiftOptionalObject()) } let firstObj = SwiftOptionalObject.allObjectsInRealm(realm).firstObject() as! SwiftOptionalObject XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) try! realm.transactionWithBlock { firstObj.optObjectCol = SwiftBoolObject() firstObj.optObjectCol!.boolCol = true firstObj.optStringCol = "Hi!" firstObj.optNSStringCol = "Hi!" firstObj.optBinaryCol = NSData(bytes: "hi", length: 2) firstObj.optDateCol = NSDate(timeIntervalSinceReferenceDate: 10) } XCTAssertTrue(firstObj.optObjectCol!.boolCol) XCTAssertEqual(firstObj.optStringCol!, "Hi!") XCTAssertEqual(firstObj.optNSStringCol!, "Hi!") XCTAssertEqual(firstObj.optBinaryCol!, NSData(bytes: "hi", length: 2)) XCTAssertEqual(firstObj.optDateCol!, NSDate(timeIntervalSinceReferenceDate: 10)) try! realm.transactionWithBlock { firstObj.optObjectCol = nil firstObj.optStringCol = nil firstObj.optNSStringCol = nil firstObj.optBinaryCol = nil firstObj.optDateCol = nil } XCTAssertNil(firstObj.optObjectCol) XCTAssertNil(firstObj.optStringCol) XCTAssertNil(firstObj.optNSStringCol) XCTAssertNil(firstObj.optBinaryCol) XCTAssertNil(firstObj.optDateCol) } func testSwiftClassNameIsDemangled() { XCTAssertEqual(SwiftObject.className(), "SwiftObject", "Calling className() on Swift class should return demangled name") } // Objective-C models // Note: Swift doesn't support custom accessor names // so we test to make sure models with custom accessors can still be accessed func testCustomAccessors() { let realm = realmWithTestPath() realm.beginWriteTransaction() let ca = CustomAccessorsObject.createInRealm(realm, withValue: ["name", 2]) XCTAssertEqual(ca.name!, "name", "name property should be name.") ca.age = 99 XCTAssertEqual(ca.age, Int32(99), "age property should be 99") try! realm.commitWriteTransaction() } func testClassExtension() { let realm = realmWithTestPath() realm.beginWriteTransaction() let bObject = BaseClassStringObject() bObject.intCol = 1 bObject.stringCol = "stringVal" realm.addObject(bObject) try! realm.commitWriteTransaction() let objectFromRealm = BaseClassStringObject.allObjectsInRealm(realm)[0] as! BaseClassStringObject XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1") XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal") } func testCreateOrUpdate() { let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["string", 1]) let objects = SwiftPrimaryStringObject.allObjects(); XCTAssertEqual(objects.count, UInt(1), "Should have 1 object"); XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 1, "Value should be 1"); SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["stringCol": "string2", "intCol": 2]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithValue(["string", 3]) XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects") XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 3, "Value should be 3"); try! realm.commitWriteTransaction() } // if this fails (and you haven't changed the test module name), the checks // for swift class names and the demangling logic need to be updated func testNSStringFromClassDemangledTopLevelClassNames() { XCTAssertEqual(NSStringFromClass(OuterClass), "Tests.OuterClass") } // if this fails (and you haven't changed the test module name), the prefix // check in RLMSchema initialization needs to be updated func testNestedClassNameMangling() { XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC5Tests10OuterClass10InnerClass") } } #endif
mit
b07490099dbdec90132b95dc6a59388b
38.402154
142
0.673532
4.985688
false
true
false
false
hgl888/firefox-ios
AccountTests/FxALoginStateMachineTests.swift
27
10046
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import FxA import Shared import XCTest class MockFxALoginClient: FxALoginClient { // Fixed per mock client, for testing. let kA = NSData.randomOfLength(UInt(KeyLength))! let wrapkB = NSData.randomOfLength(UInt(KeyLength))! func keyPair() -> Deferred<Maybe<KeyPair>> { let keyPair: KeyPair = RSAKeyPair.generateKeyPairWithModulusSize(512) return Deferred(value: Maybe(success: keyPair)) } func keys(keyFetchToken: NSData) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAKeysResponse(kA: kA, wrapkB: wrapkB) return Deferred(value: Maybe(success: response)) } func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxASignResponse(certificate: "certificate") return Deferred(value: Maybe(success: response)) } } // A mock client that responds to keys and sign with 401 errors. class MockFxALoginClientAfterPasswordChange: MockFxALoginClient { override func keys(keyFetchToken: NSData) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.Remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } override func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.Remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to keys with 400/104 (needs verification responses). class MockFxALoginClientBeforeVerification: MockFxALoginClient { override func keys(keyFetchToken: NSData) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.Remote(RemoteError(code: 400, errno: 104, error: "Unverified", message: "Unverified message", info: "Unverified info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to sign with 503/999 (unknown server error). class MockFxALoginClientDuringOutage: MockFxALoginClient { override func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.Remote(RemoteError(code: 503, errno: 999, error: "Unknown", message: "Unknown error", info: "Unknown err info")) return Deferred(value: Maybe(failure: response)) } } class FxALoginStateMachineTests: XCTestCase { let marriedState = FxAStateTests.stateForLabel(FxAStateLabel.Married) as! MarriedState override func setUp() { super.setUp() self.continueAfterFailure = false } func withMachine(client: FxALoginClient, callback: (FxALoginStateMachine) -> Void) { let stateMachine = FxALoginStateMachine(client: client) callback(stateMachine) } func withMachineAndClient(callback: (FxALoginStateMachine, MockFxALoginClient) -> Void) { let client = MockFxALoginClient() withMachine(client) { stateMachine in callback(stateMachine, client) } } func testAdvanceWhenInteractionRequired() { // The simple cases are when we get to Separated and Doghouse. There's nothing to do! // We just have to wait for user interaction. for stateLabel in [FxAStateLabel.Separated, FxAStateLabel.Doghouse] { let e = expectationWithDescription("Wait for login state machine.") let state = FxAStateTests.stateForLabel(stateLabel) withMachineAndClient { stateMachine, _ in stateMachine.advanceFromState(state, now: 0).upon { newState in XCTAssertEqual(newState.label, stateLabel) e.fulfill() } } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromEngagedBeforeVerified() { // Advancing from engaged before verified stays put. let e = self.expectationWithDescription("Wait for login state machine.") let engagedState = (FxAStateTests.stateForLabel(.EngagedBeforeVerified) as! EngagedBeforeVerifiedState) withMachine(MockFxALoginClientBeforeVerification()) { stateMachine in stateMachine.advanceFromState(engagedState, now: engagedState.knownUnverifiedAt).upon { newState in XCTAssertEqual(newState.label.rawValue, engagedState.label.rawValue) e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromEngagedAfterVerified() { // Advancing from an Engaged state correctly XORs the keys. withMachineAndClient { stateMachine, client in // let unwrapkB = Bytes.generateRandomBytes(UInt(KeyLength)) let unwrapkB = client.wrapkB // This way we get all 0s, which is easy to test. let engagedState = (FxAStateTests.stateForLabel(.EngagedAfterVerified) as! EngagedAfterVerifiedState).withUnwrapKey(unwrapkB) let e = self.expectationWithDescription("Wait for login state machine.") stateMachine.advanceFromState(engagedState, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.Married.rawValue) if let newState = newState as? MarriedState { // We get kA from the client directly. XCTAssertEqual(newState.kA.hexEncodedString, client.kA.hexEncodedString) // We unwrap kB by XORing. The result is KeyLength (32) 0s. XCTAssertEqual(newState.kB.hexEncodedString, "0000000000000000000000000000000000000000000000000000000000000000") } e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromCohabitingAfterVerifiedDuringOutage() { // Advancing from engaged after verified, but during outage, stays put. let e = self.expectationWithDescription("Wait for login state machine.") let state = (FxAStateTests.stateForLabel(.CohabitingAfterKeyPair) as! CohabitingAfterKeyPairState) withMachine(MockFxALoginClientDuringOutage()) { stateMachine in stateMachine.advanceFromState(state, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, state.label.rawValue) e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromMarried() { // Advancing from a healthy Married state is easy. let e = self.expectationWithDescription("Wait for login state machine.") withMachineAndClient { stateMachine, _ in stateMachine.advanceFromState(self.marriedState, now: 0).upon { newState in XCTAssertEqual(newState.label, FxAStateLabel.Married) e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromMarriedWithExpiredCertificate() { // Advancing from a Married state with an expired certificate gets back to Married. let e = self.expectationWithDescription("Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneWeekInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advanceFromState(self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.Married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh certificate. XCTAssertLessThan(self.marriedState.certificateExpiresAt, now) XCTAssertGreaterThan(newState.certificateExpiresAt, now) } e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromMarriedWithExpiredKeyPair() { // Advancing from a Married state with an expired keypair gets back to Married too. let e = self.expectationWithDescription("Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneMonthInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advanceFromState(self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.Married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh key pair (and certificate, but we don't verify that). XCTAssertLessThan(self.marriedState.keyPairExpiresAt, now) XCTAssertGreaterThan(newState.keyPairExpiresAt, now) } e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } func testAdvanceFromMarriedAfterPasswordChange() { // Advancing from a Married state with a 401 goes to Separated if it needs a new certificate. let e = self.expectationWithDescription("Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneDayInMilliseconds + 1 withMachine(MockFxALoginClientAfterPasswordChange()) { stateMachine in stateMachine.advanceFromState(self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.Separated.rawValue) e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } }
mpl-2.0
abef8bd31b18e5ac67b1e5c1fedfdb5f
47.76699
151
0.674895
5.375067
false
true
false
false
ryan-boder/path-of-least-resistance
PathOfLeastResistance/main.swift
1
506
import Foundation // Read an input grid from stdin var input = "" while true { let line = readLine(stripNewline: true) if line == nil || line!.isEmpty { break } input += line! + "\n" } // Parse it let parser = InputParser() let grid = parser.parse(input) // Run PathFinder let finder = PathFinder() let (success, resistance, path) = finder.find(grid) // Display the output print(success ? "Yes" : "No") print(resistance) print(path.map(){x in String(x)}.joinWithSeparator(" "))
apache-2.0
a0543aa5a9302b45ef86be2f58a59313
20.083333
56
0.652174
3.418919
false
false
false
false
mlatham/AFToolkit
Sources/AFToolkit/Sqlite/Sqlite+TableBase.swift
1
3979
import Foundation import SQLite3 extension Sqlite { open class TableBase<T>: NSObject, SqliteTableProtocol { // MARK: - Properties // Caches indices for column name lookup. private var _columnReadIndices: [String: Int] = [:] public let client: Client public let name: String public var columns: [SqliteColumnProtocol] // Returns a comma-separated list of column names (eg: "column"). public private(set) var allColumnsString: String = "" // Returns a comma-separated list of full column names (eg: "table.column"). public private(set) var allFullColumnsString: String = "" public override var description: String { return name } // MARK: - Inits public init(client: Client, name: String, columns: [SqliteColumnProtocol]) { // Cache column indices. for (i, column) in columns.enumerated() { _columnReadIndices[column.name] = i } self.client = client self.name = name self.columns = columns super.init() for column in columns { var column = column column.table = self } // Initialize the allColumnsString, self.allColumnsString = columns.map { "\($0.name)" }.joined(separator: ", ") self.allFullColumnsString = columns.map { "\($0.fullName)" }.joined(separator: ", ") } // MARK: - Functions public func readIndex(of column: SqliteColumnProtocol) -> Int { return _columnReadIndices[column.name] ?? -1 } public func blob(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Data? { return statement.blob(at: readIndex(of: column)) } public func string(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> String? { return statement.string(at: readIndex(of: column)) } public func iso8601StringDate(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Date? { return statement.iso8601StringDate(at: readIndex(of: column)) } public func int(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Int? { return statement.int(at: readIndex(of: column)) } public func intNumber(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> NSNumber? { return statement.intNumber(at: readIndex(of: column)) } public func intBool(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Bool? { return statement.intBool(at: readIndex(of: column)) } public func double(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Double? { return statement.double(at: readIndex(of: column)) } public func doubleNumber(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> NSNumber? { return statement.doubleNumber(at: readIndex(of: column)) } public func timeIntervalSince1970Date(_ statement: CursorStatement, at column: SqliteColumnProtocol) -> Date? { return statement.timeIntervalSince1970(at: readIndex(of: column)) } public func query( where whereStatement: String? = nil, orderBy: String? = nil, limit: Int? = nil, offset: Int? = nil, cache: Bool) -> [T] { var query = "SELECT \(allColumnsString) FROM \(name)" if let whereStatement = whereStatement?.nonEmpty { query += " WHERE \(whereStatement)" } if let orderBy = orderBy?.nonEmpty { query += " ORDER BY \(orderBy)" } if let offset = offset { if let limit = limit { query += " LIMIT \(limit)" } else { query += " LIMIT 1" } query += " OFFSET \(offset)" } query += ";" return client.query(from: self, query, cache: cache) } public func count(where whereStatement: String?, cache: Bool) -> Int { var query = "SELECT COUNT(*) FROM \(name)" if let whereStatement = whereStatement?.nonEmpty { query.append(" WHERE \(whereStatement)") } return client.count(query: query, cache: cache) } open func readRow(_ cursor: CursorStatement) -> T? { // Abstract. fatalError(NotImplementedError) } } }
mit
af5d33357aa1303917a8ed55f4d4c26a
27.833333
113
0.671526
3.715219
false
false
false
false
SuPair/firefox-ios
Storage/SQL/SQLiteBookmarksResetting.swift
5
5961
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let log = Logger.syncLogger extension MergedSQLiteBookmarks: AccountRemovalDelegate { public func onRemovedAccount() -> Success { return self.local.onRemovedAccount() >>> self.buffer.onRemovedAccount } } extension MergedSQLiteBookmarks: ResettableSyncStorage { public func resetClient() -> Success { return self.local.resetClient() >>> self.buffer.resetClient } } extension SQLiteBookmarkBufferStorage: AccountRemovalDelegate { public func onRemovedAccount() -> Success { return self.resetClient() } } extension SQLiteBookmarkBufferStorage: ResettableSyncStorage { /** * Our buffer is simply a copy of server contents. That means we should * be very willing to drop it and re-populate it from the server whenever we might * be out of sync. See Bug 1212431 Comment 2. */ public func resetClient() -> Success { return self.wipeBookmarks() } public func wipeBookmarks() -> Success { return self.db.run([ "DELETE FROM bookmarksBufferStructure", "DELETE FROM bookmarksBuffer", ]) } } extension SQLiteBookmarks { /** * If a synced record is deleted locally, but hasn't been synced to the server, * then `preserveDeletions=true` will result in that deletion being kept. * * During a reset, we'll redownload all server records. If we don't keep the * local deletion, then when we re-process the (non-deleted) server counterpart * to the now-missing local record, it'll be reinserted: the user's deletion will * be undone. * * Right now we don't preserve deletions when removing the Firefox Account, but * we could do so if we were willing to trade local database space to handle this * possible situation. */ fileprivate func collapseMirrorIntoLocalPreservingDeletions(_ preserveDeletions: Bool) -> Success { // As implemented, this won't work correctly without ON DELETE CASCADE. assert(SwiftData.EnableForeignKeys) // 1. Wait until we commit to complain about constraint violations. let deferForeignKeys = "PRAGMA defer_foreign_keys = ON" // 2. Drop anything from local that's deleted. We don't need to track the // deletion now. Optional: keep them around if they're non-uploaded changes. let removeLocalDeletions = "DELETE FROM bookmarksLocal WHERE is_deleted IS 1 " + (preserveDeletions ? "AND sync_status IS NOT \(SyncStatus.changed.rawValue)" : "") // 3. Mark everything in local as New. let markLocalAsNew = "UPDATE bookmarksLocal SET sync_status = \(SyncStatus.new.rawValue)" // 4. Insert into local anything not overridden left in mirror. // Note that we use the server modified time as our substitute local modified time. // This will provide an ounce of conflict avoidance if the user re-links the same // account at a later date. let copyMirrorContents = """ INSERT OR IGNORE INTO bookmarksLocal ( sync_status, local_modified, guid, date_added, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, faviconID ) SELECT \(SyncStatus.new.rawValue) AS sync_status, server_modified AS local_modified, guid, date_added, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, faviconID FROM bookmarksMirror WHERE is_overridden IS 0 """ // 5.(pre) I have a database right in front of me that violates an assumption: a full // bookmarksMirrorStructure and an empty bookmarksMirror. Clean up, just in case. let removeOverriddenStructure = "DELETE FROM bookmarksMirrorStructure WHERE parent IN (SELECT guid FROM bookmarksMirror WHERE is_overridden IS 1)" // 5. Insert into localStructure anything left in mirrorStructure. // This won't copy the structure of any folders that were already overridden -- // we already deleted those, and the deletions cascaded. let copyMirrorStructure = "INSERT INTO bookmarksLocalStructure SELECT * FROM bookmarksMirrorStructure" // 6. Blank the mirror. let removeMirrorStructure = "DELETE FROM bookmarksMirrorStructure" let removeMirrorContents = "DELETE FROM bookmarksMirror" return db.run([ deferForeignKeys, removeLocalDeletions, markLocalAsNew, copyMirrorContents, removeOverriddenStructure, copyMirrorStructure, removeMirrorStructure, removeMirrorContents, ]) } } extension SQLiteBookmarks: AccountRemovalDelegate { public func onRemovedAccount() -> Success { return self.collapseMirrorIntoLocalPreservingDeletions(false) } } extension SQLiteBookmarks: ResettableSyncStorage { public func resetClient() -> Success { // Flip flags to prompt a re-sync. // // We copy the mirror to local, preserving local changes, apart from // deletions of records that were never synced. // // Records that match the server record that we'll redownload will be // marked as Synced and won't be reuploaded. // // Records that are present locally but aren't on the server will be // uploaded. // return self.collapseMirrorIntoLocalPreservingDeletions(true) } }
mpl-2.0
dc82d612d57fb5068d84a3a98984c475
39.828767
126
0.663479
5.051695
false
false
false
false
nua-schroers/AccessibilityExamples
AccessibilityExamples/ViewWithSlider.swift
1
3801
// // ViewWithSlider.swift // AccessibilityExamples // // Created by Dr. Wolfram Schroers on 3/1/15. // Copyright (c) 2015 Wolfram Schroers. All rights reserved. // import UIKit /// This is a view which contains a description label and a slider. /// The entire view shall be accessible and behave like a slider that /// can be moved with the up/down swipe gestures. /// /// Note that we do NOT want to access the individual sub-elements /// (i.e., the label and the slider) individually when VoiceOver is /// active. We only want to deal with the entire cell. class ViewWithSlider: CustomView { /// MARK: Properties var textLabel = UILabel() var theSlider = UISlider() /// MARK: Private methods override func setup() { // View setup (nothing to do with Accessibility). self.textLabel.text = "Warp factor" self.textLabel.frame = CGRect(x: 5, y: 5, width: 200, height: 50) self.theSlider.frame = CGRect(x: 5, y: 55, width: 200, height: 50) self.theSlider.minimumValue = 0 self.theSlider.maximumValue = 8 self.addSubview(self.textLabel) self.addSubview(self.theSlider) // Accessibility setup. self.isAccessibilityElement = true // The entire view shall be accessible. self.textLabel.isAccessibilityElement = false // But the individual elements (the label and the slider) shall not be. self.theSlider.isAccessibilityElement = false self.accessibilityLabel = "Warp factor" // Give the entire view an appropriate VoiceOver label and hint. self.accessibilityHint = "Swipe up to speed up or down to slow down" // The entire view shall behave as an adjustible element, // i.e. it shall support and respond to swipe-up and -down // gestures. self.accessibilityTraits = UIAccessibilityTraits(rawValue: super.accessibilityTraits.rawValue | UIAccessibilityTraits.adjustable.rawValue) self.updateAccessibility() } override func updateAccessibility() { // Merely update the accessibility value of this view. It // shall be the actual value of the slider without further // interpretation. self.accessibilityValue = "\(self.theSlider.value)" } /// MARK: UIAccessibilityAction /// This method is automagically called when the user does a /// swipe-down while the view is highlighted. /// /// Note that this method is NOT used at all if VoiceOver is /// turned off! override func accessibilityDecrement() { // Respond to a swipe-down gesture. let warpFactor = Int(self.theSlider.value) if (warpFactor > 0) { self.theSlider.setValue(Float(self.theSlider.value-1), animated: false) } else { self.theSlider.setValue(self.theSlider.minimumValue, animated: false) } // Update the value. self.updateAccessibility() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: "") } /// This method is automagically called when the user does a /// swipe-up while the view is highlighted. /// /// Note that this method is NOT used at all if VoiceOver is /// turned off! override func accessibilityIncrement() { // Respond to a swipe-up gesture. let warpFactor = Int(self.theSlider.value) if (warpFactor < 8) { self.theSlider.setValue(Float(self.theSlider.value+1), animated: false) } else { self.theSlider.setValue(self.theSlider.maximumValue, animated: false) } // Update the value. self.updateAccessibility() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: "") } }
mit
e45ee2bc5e31c055c344465b75950da6
37.01
146
0.665351
4.5358
false
false
false
false
robrix/Prelude
Prelude/Compose.swift
1
2107
// Copyright (c) 2014 Rob Rix. All rights reserved. // MARK: - Operators precedencegroup Composition { /// Function composition is associative, but since we want to chain compositions, we pick right-associativity primarily for consistency with Haskell. associativity: right // This is a higher precedence than the exponentiative operators `<<` and `>>`. higherThan: BitwiseShiftPrecedence } infix operator >>> : Composition infix operator <<< : Composition // MARK: - Right-to-left composition /// Returns the right-to-left composition of unary `f` on unary `g`. /// /// This is the function such that `(f <<< g)(x)` = `f(g(x))`. public func <<< <T, U, V> (f: @escaping (U) -> V, g: @escaping (T) -> U) -> (T) -> V { return { f(g($0)) } } /// Returns the right-to-left composition of unary `f` on binary `g`. /// /// This is the function such that `(f <<< g)(x, y)` = `f(g(x, y))`. public func <<< <T, U, V, W> (f: @escaping (V) -> W, g: @escaping (T, U) -> V) -> (T, U) -> W { return { f(g($0, $1)) } } /// Returns the right-to-left composition of binary `f` on unary `g`. /// /// This is the function such that `(f <<< g)(x, y)` = `f(g(x), y)`. public func <<< <T, U, V, W> (f: @escaping (U, V) -> W, g: @escaping (T) -> U) -> (T, V) -> W { return { f(g($0), $1) } } // MARK: - Left-to-right composition /// Returns the left-to-right composition of unary `g` on unary `f`. /// /// This is the function such that `(f >>> g)(x)` = `g(f(x))`. public func >>> <T, U, V> (f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V { return { g(f($0)) } } /// Returns the left-to-right composition of unary `g` on binary `f`. /// /// This is the function such that `(f >>> g)(x, y)` = `g(f(x, y))`. public func >>> <T, U, V, W> (f: @escaping (T, U) -> V, g: @escaping (V) -> W) -> (T, U) -> W { return { g(f($0, $1)) } } /// Returns the left-to-right composition of binary `g` on unary `f`. /// /// This is the function such that `(f >>> g)(x, y)` = `g(f(x), y)`. public func >>> <T, U, V, W> (f: @escaping (T) -> U, g: @escaping (U, V) -> W) -> (T, V) -> W { return { g(f($0), $1) } }
mit
5fee23d8ece3db7c82d9ab6507d26848
32.983871
150
0.561462
2.761468
false
false
false
false
CharlesVu/Smart-iPad
MKHome/Settings/WeatherSettingsViewController.swift
1
1698
// // WeatherSettingsViewController.swift // MKHome // // Created by charles on 07/01/2017. // Copyright © 2017 charles. All rights reserved. // import Foundation import UIKit class WeatherSettingsViewController: UIViewController { fileprivate let userSettings = UserSettings.sharedInstance @IBOutlet var cityWeatherTableView: UITableView? override func viewWillAppear(_ animated: Bool) { cityWeatherTableView?.reloadData() } @IBAction func onCloseClicked(button: UIButton) { dismiss(animated: true) } } extension WeatherSettingsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userSettings.weather.getCities().count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let city = userSettings.weather.getCities()[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell")! cell.textLabel?.text = city.name return cell } } extension WeatherSettingsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } @objc(tableView:commitEditingStyle:forRowAtIndexPath:) func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCell.EditingStyle.delete) { let city = userSettings.weather.getCities()[indexPath.row] userSettings.weather.removeCity(city) tableView.reloadData() } } }
mit
ef61e584ac2a6e9fb86fda394792f21e
31.018868
128
0.716559
5.189602
false
false
false
false
codePrincess/playgrounds
Play with Cognitive Services.playgroundbook/Contents/Chapters/Computer Vision.playgroundchapter/Pages/First steps.playgroundpage/Contents.swift
1
2264
//#-hidden-code import PlaygroundSupport import UIKit import Foundation guard #available(iOS 9, OSX 10.11, *) else { fatalError("Life? Don't talk to me about life. Here I am, brain the size of a planet, and they tell me to run a 'playground'. Call that job satisfaction? I don't.") } func setConfidenceForComputerVision(_ value: Double) { let page = PlaygroundPage.current if let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy { proxy.send(.floatingPoint(value)) } } func retrieveTags() { let page = PlaygroundPage.current if let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy { proxy.send(.string("retrieveTags")) } } func chooseImage (_ imageData: Data) { let page = PlaygroundPage.current if let proxy = page.liveView as? PlaygroundRemoteLiveViewProxy { proxy.send(.data(imageData)) } } //#-end-hidden-code /*: # Describe your picture! It's time to get life into our app! Want to get your picture described by a remote service? Yes? YES? So get ready - and get to know the * *drumroooooll* * **COGNITIVE SERVICES**! We will start with the Computer Vision API. So let's see, what the "computer" can "see" on our image. */ /*: * experiment: Every part of the description of the picture will be returned with a certain confidence. A good value is 0.85 for nice fitting results. But go a head and play around with this value and see, with what funky descriptions the "computer" may come along */ let image = /*#-editable-code*/#imageLiteral(resourceName: "beach.png")/*#-end-editable-code*/ let dataImage = UIImagePNGRepresentation(image) chooseImage(dataImage!) setConfidenceForComputerVision(/*#-editable-code*/0.2/*#-end-editable-code*/) retrieveTags() /*: * callout(What did we learn?): Wonderful! So you just called your first API from the Cognitive Services Suite. The Computer Vision API. If you want to have a detailed look at the documentation - where you can find further examples - visit the dedicated [Computer Vision documentation](https://www.microsoft.com/cognitive-services/en-us/computer-vision-api). */ //: Enough of just describing photos. Let's catch a smile and let the API know! Let's rock on and continue by [using the Emotion API](@next)!
mit
a26d775f91e9a516c6f64fd4791004d1
41.716981
327
0.72924
3.97193
false
false
false
false
TTVS/NightOut
Clubber/AFNetworking Usage Lines.swift
1
5745
// SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: //Alamofire.request(.GET, url, parameters: parameters) // .responseJSON { (req, res, json, error) in // if(error != nil) { // NSLog("Error: \(error)") // println(req) // println(res) // } // else { // NSLog("Success: \(url)") // var json = JSON(json!) // } //} // COPY OF REQUEST (GET) //func makeSignInRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/" // let parameter = nil // // manager.requestSerializer = AFJSONRequestSerializer() // // manager.GET(url, // parameters: nil, // success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in // print("JSON: " + responseObject.description) // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RootPaperNavigationVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // let successMenu = UIAlertController(title: nil, message: "Successfully get from server", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Success") // }) // successMenu.addAction(okAction) // // self.presentViewController(successMenu, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in // print("Error: " + error.localizedDescription) // // // let errorMenu = UIAlertController(title: nil, message: "Failed to get from server.", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Cancelled") // }) // errorMenu.addAction(okAction) // // self.presentViewController(errorMenu, animated: true, completion: nil) // }) // // // // COPY OF RESPONSE (POST) //func makeSignUpRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/users?" // let signUpParams = [ // "user[email]" : "\(emailTextField.text!)", // "user[password]" : "\(passwordTextField.text!)", // "user[password_confirmation]" : "\(passwordConfirmationTextField.text!)", // "user[first_name]" : "\(firstNameTextField.text!)", // "user[last_name]" : "\(lastNameTextField.text!)", // "user[type]" : "Guest" // ] // // print("\(emailTextField.text)") // print("\(passwordTextField.text)") // print("\(passwordConfirmationTextField.text)") // print("\(firstNameTextField.text)") // print("\(lastNameTextField.text)") // // manager.responseSerializer = AFJSONResponseSerializer() // // manager.POST(url, // parameters: signUpParams, // success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in // print("Yes this was a success.. \(responseObject.description)") // // self.displayAlertMessage("Success", alertDescription: "Account has been created") // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("signInVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in // print("We got an error here.. \(error.localizedDescription)") // }) //} // // // // // //[self GET:@"weather.ashx" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didUpdateWithWeather:)]) { // [self.delegate weatherHTTPClient:self didUpdateWithWeather:responseObject]; // } //} failure:^(NSURLSessionDataTask *task, NSError *error) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didFailWithError:)]) { // [self.delegate weatherHTTPClient:self didFailWithError:error]; // } //}]; // ///////////////////////////// // //- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex //{ // if (buttonIndex == [actionSheet cancelButtonIndex]) { // // User pressed cancel -- abort // return; // } // // // 1 // NSURL *baseURL = [NSURL URLWithString:BaseURLString]; // NSDictionary *parameters = @{@"format": @"json"}; // // // 2 // AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL]; // manager.responseSerializer = [AFJSONResponseSerializer serializer]; // // // 3 //if (buttonIndex == 0) { // [manager GET:@"weather.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // self.weather = responseObject; // self.title = @"HTTP GET"; // [self.tableView reloadData]; // } failure:^(NSURLSessionDataTask *task, NSError *error) { // UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" // message:[error localizedDescription] // delegate:nil // cancelButtonTitle:@"Ok" // otherButtonTitles:nil]; // [alertView show]; // }]; //} // // // //
apache-2.0
c11ac747a07e747d86e90100ce5b9f20
33.608434
148
0.604178
4.352273
false
false
false
false
swiftingio/architecture-wars-mvc
MyCards/MyCards/PhotoCamera.swift
1
2742
// // PhotoButton.swift // MyCards // // Created by Maciej Piotrowski on 13/11/16. // import UIKit class PhotoCamera: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { // Main Shape let x = rect.origin.x let y = rect.origin.y let width = rect.size.width let height = rect.size.height let radius: CGFloat = height / 10.0 let main = UIBezierPath(roundedRect: CGRect(x: x, y: y, width: width, height: height), cornerRadius: radius) UIColor.lightGray.setFill() main.fill() // Inner Shape let innerX: CGFloat = x let innerY: CGFloat = height * 5 / 30.0 let innerWidth: CGFloat = width let innerHeight: CGFloat = height * 2 / 3.0 let inner = UIBezierPath(rect: CGRect(x: innerX, y: innerY, width: innerWidth, height: innerHeight)) UIColor.gray.setFill() inner.fill() // Viewfinder let viewFinderX: CGFloat = width / 16.0 let viewFinderY: CGFloat = height / 12.0 let viewFinderWidth: CGFloat = width / 6.0 let viewFinderHeight: CGFloat = height / 6.0 let viewFinderRadius: CGFloat = width / 10.0 let viewfinder = UIBezierPath(roundedRect: CGRect(x: viewFinderX, y: viewFinderY, width: viewFinderWidth, height: viewFinderHeight), cornerRadius: viewFinderRadius) UIColor.lightBlue.setFill() viewfinder.fill() UIColor.darkerBlue.setStroke() viewfinder.lineWidth = 1 viewfinder.stroke() // Lense cover let coverSide: CGFloat = height / (30.0 / 22.0) let coverX: CGFloat = width / 2.0 - coverSide / 2.0 let coverY: CGFloat = height / 2.0 - coverSide / 2.0 let cover = UIBezierPath(ovalIn: CGRect(x: coverX, y: coverY, width: coverSide, height: coverSide)) UIColor.darkerBlue.setFill() cover.fill() // Lense let lenseSide: CGFloat = coverSide * 0.9 let lenseX: CGFloat = width / 2.0 - lenseSide / 2.0 let lenseY: CGFloat = height / 2.0 - lenseSide / 2.0 let lense = UIBezierPath(ovalIn: CGRect(x: lenseX, y: lenseY, width: lenseSide, height: lenseSide)) UIColor.lightBlue.setFill() lense.fill() alpha = 1.0 } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { alpha = 0.0 setNeedsDisplay() } override var intrinsicContentSize: CGSize { return CGSize(width: 40, height: 30) } }
mit
7da200cdfa51bb6b18caab833cfd1193
32.851852
116
0.613056
3.973913
false
false
false
false
gregomni/swift
test/Generics/redundant_requirement_self_conforming_protocol.swift
2
417
// RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s struct G<T> {} // CHECK-LABEL: Generic signature: <T where T == Error> extension G where T : Error, T == Error {} // expected-warning@-1 {{redundant conformance constraint 'any Error' : 'Error'}}
apache-2.0
4f51feb53a3493352c9a3f55ccdb9951
51.125
135
0.726619
3.594828
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Registration/Company/CompanyLoginVerificationToken.swift
1
3666
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation /// A struct containing a token to validate login requests /// received via url schemes. public struct CompanyLoginVerificationToken: Codable, Equatable { /// The unique identifier of the token. let uuid: UUID /// The creation date of the token. let creationDate: Date /// The amount of seconds the token should be considered valid. let timeToLive: TimeInterval /// Creates a new validation token with an expiration time /// of 30 minutes if not specified otherwise. init(uuid: UUID = .init(), creationDate: Date = .init(), timeToLive: TimeInterval = 60 * 30) { self.uuid = uuid self.creationDate = creationDate self.timeToLive = timeToLive } /// Whether the token is no langer valid (older than its time to live). var isExpired: Bool { return abs(creationDate.timeIntervalSinceNow) >= timeToLive } /// Validates a passed in UUID against the token. /// - parameter identifier: The uuid which should be validated against the token. /// - returns: Whether the UUID matches the token and the token is still valid. func matches(identifier: UUID) -> Bool { return uuid == identifier && !isExpired } } public func == (lhs: CompanyLoginVerificationToken, rhs: CompanyLoginVerificationToken) -> Bool { return lhs.uuid == rhs.uuid } public extension CompanyLoginVerificationToken { private static let defaultsKey = "CompanyLoginVerificationTokenDefaultsKey" /// Returns the currently stored verification token. /// - parameter defaults: The defaults to retrieve the token from. static func current(in defaults: UserDefaults = .shared()) -> CompanyLoginVerificationToken? { return defaults.data(forKey: CompanyLoginVerificationToken.defaultsKey).flatMap { try? JSONDecoder().decode(CompanyLoginVerificationToken.self, from: $0) } } /// Stores the token in the provided defaults. /// - parameter defaults: The defaults to store the token in. /// - returns: Whether the write operation succeeded. @discardableResult func store(in defaults: UserDefaults = .shared()) -> Bool { do { let data = try JSONEncoder().encode(self) defaults.set(data, forKey: CompanyLoginVerificationToken.defaultsKey) return true } catch { return false } } /// Deletes the current verification token. /// - parameter defaults: The defaults to delete the token from. static func flush(in defaults: UserDefaults = .shared()) { defaults.removeObject(forKey: defaultsKey) } /// Deletes the current verification token if it is expired. /// - parameter defaults: The defaults to delete the token from. static func flushIfNeeded(in defaults: UserDefaults = .shared()) { guard let token = current(in: defaults), token.isExpired else { return } flush(in: defaults) } }
gpl-3.0
c78c246620974a53192415a5f5020685
37.589474
98
0.691762
4.706033
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/UIKits/ViewControllers/SAlertViewController.swift
2
2858
// // SAlertViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/12/1. // Copyright © 2016年 Snail. All rights reserved. // import UIKit class SAlertViewController: CustomViewController { var alertC : UIAlertController! var actionC : UIAlertController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initView() initAlertView() initActionView() } func initView() { navTitleLabel.text = "AlertViewController" rightBtn.isHidden = false } func initActionView() { //MARK: - actionSheet不能加textField actionC = UIAlertController(title: "actionSheet", message: "actionSheet", preferredStyle: .actionSheet) let sureAction = UIAlertAction(title: "确定", style: .default, handler: {action in print("sureAction") }) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: {action in print("cancelAction") }) let deleteAction = UIAlertAction(title: "删除", style: .destructive, handler: {action in print("deleteAction") }) actionC.addAction(sureAction) actionC.addAction(cancelAction) actionC.addAction(deleteAction) } func initAlertView() { alertC = UIAlertController(title: "alert", message: "alert", preferredStyle: .alert) alertC.addTextField { (textField) in textField.text = "dassa" textField.backgroundColor = UIColor.red } let sureAction = UIAlertAction(title: "确定", style: .default, handler: {action in print("sureAction") }) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: {action in print("cancelAction") }) let deleteAction = UIAlertAction(title: "删除", style: .destructive, handler: {action in print("deleteAction") }) alertC.addAction(sureAction) alertC.addAction(cancelAction) alertC.addAction(deleteAction) } override func rightAction() { super.rightAction() self.present(actionC, animated: true, completion: { }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
8130e3d79d4e08c89217ecaf9c6f26c4
29.706522
111
0.618053
4.947461
false
false
false
false
sai43/AlamofireImage
Source/Request+AlamofireImage.swift
14
9301
// Request+AlamofireImage.swift // // Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation #if os(iOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(OSX) import Cocoa #endif extension Request { /// The completion handler closure used when an image response serializer completes. public typealias CompletionHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<Image>) -> Void // MARK: - iOS and watchOS #if os(iOS) || os(watchOS) /** Creates a response serializer that returns an image initialized from the response data using the specified image options. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - returns: An image response serializer. */ public class func imageResponseSerializer( imageScale imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true) -> GenericResponseSerializer<UIImage> { return GenericResponseSerializer { request, response, data in guard let validData = data where validData.length > 0 else { return .Failure(data, Request.imageDataError()) } guard Request.validateResponse(response) else { return .Failure(data, Request.contentTypeValidationError()) } do { let image = try Request.imageFromResponseData(validData, imageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .Success(image) } catch { return .Failure(data, error) } } } /** Adds a handler to be called once the request has finished. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage( imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true, completionHandler: CompletionHandler) -> Self { return response( responseSerializer: Request.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } private class func imageFromResponseData(data: NSData, imageScale: CGFloat) throws -> UIImage { if let image = UIImage(data: data, scale: imageScale) { return image } throw imageDataError() } private class var imageScale: CGFloat { #if os(iOS) return UIScreen.mainScreen().scale #elseif os(watchOS) return WKInterfaceDevice.currentDevice().screenScale #endif } #elseif os(OSX) // MARK: - OSX /** Creates a response serializer that returns an image initialized from the response data. - returns: An image response serializer. */ public class func imageResponseSerializer() -> GenericResponseSerializer<NSImage> { return GenericResponseSerializer { request, response, data in guard let validData = data where validData.length > 0 else { return .Failure(data, Request.imageDataError()) } guard Request.validateResponse(response) else { return .Failure(data, Request.contentTypeValidationError()) } guard let bitmapImage = NSBitmapImageRep(data: validData) else { return .Failure(data, Request.imageDataError()) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .Success(image) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage(completionHandler: CompletionHandler) -> Self { return response( responseSerializer: Request.imageResponseSerializer(), completionHandler: completionHandler ) } #endif // MARK: - Private - Shared Helper Methods private class func validateResponse(response: NSHTTPURLResponse?) -> Bool { let acceptableContentTypes: Set<String> = [ "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-win-bitmap" ] if let mimeType = response?.MIMEType where acceptableContentTypes.contains(mimeType) { return true } return false } private class func contentTypeValidationError() -> NSError { let failureReason = "Failed to validate response due to unacceptable content type" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } private class func imageDataError() -> NSError { let failureReason = "Failed to create a valid Image from the response data" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } }
mit
0030855041f8e4711beca68c071f2e72
41.861751
121
0.614128
5.706135
false
false
false
false
bouwman/LayoutResearch
LayoutResearch/Views/RoundedButton.swift
1
877
// // RoundedButton.swift // LayoutResearch // // Created by Tassilo Bouwman on 23.07.17. // Copyright © 2017 Tassilo Bouwman. All rights reserved. // import UIKit @IBDesignable class RoundedButton: UIButton { var identifier = "" override init(frame: CGRect) { super.init(frame: frame) cornerRadius = frame.size.height / 2 } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) cornerRadius = frame.size.height / 2 } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = cornerRadius } override var isEnabled: Bool { didSet { alpha = isEnabled ? 1.0 : 0.5 } } @IBInspectable var cornerRadius: CGFloat = 5 { didSet { layer.cornerRadius = cornerRadius } } }
mit
52c109d84e7f963ada97326589003fb9
20.365854
58
0.586758
4.358209
false
false
false
false
ReactiveCocoa/ReactiveSwift
Tests/ReactiveSwiftTests/DisposableSpec.swift
1
4378
// // DisposableSpec.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-07-13. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveSwift class DisposableSpec: QuickSpec { override func spec() { describe("SimpleDisposable") { it("should set disposed to true") { let disposable = AnyDisposable() expect(disposable.isDisposed) == false disposable.dispose() expect(disposable.isDisposed) == true } } describe("ActionDisposable") { it("should run the given action upon disposal") { var didDispose = false let disposable = AnyDisposable { didDispose = true } expect(didDispose) == false expect(disposable.isDisposed) == false disposable.dispose() expect(didDispose) == true expect(disposable.isDisposed) == true } } describe("CompositeDisposable") { var disposable = CompositeDisposable() beforeEach { disposable = CompositeDisposable() } it("should ignore the addition of nil") { disposable.add(nil) return } it("should dispose of added disposables") { let simpleDisposable = AnyDisposable() disposable += simpleDisposable var didDispose = false disposable += { didDispose = true } expect(simpleDisposable.isDisposed) == false expect(didDispose) == false expect(disposable.isDisposed) == false disposable.dispose() expect(simpleDisposable.isDisposed) == true expect(didDispose) == true expect(disposable.isDisposed) == true } it("should not dispose of removed disposables") { let simpleDisposable = AnyDisposable() let handle = disposable += simpleDisposable // We should be allowed to call this any number of times. handle?.dispose() handle?.dispose() expect(simpleDisposable.isDisposed) == false disposable.dispose() expect(simpleDisposable.isDisposed) == false } it("should create with initial disposables") { let disposable1 = AnyDisposable() let disposable2 = AnyDisposable() let disposable3 = AnyDisposable() let compositeDisposable = CompositeDisposable([disposable1, disposable2, disposable3]) expect(disposable1.isDisposed) == false expect(disposable2.isDisposed) == false expect(disposable3.isDisposed) == false compositeDisposable.dispose() expect(disposable1.isDisposed) == true expect(disposable2.isDisposed) == true expect(disposable3.isDisposed) == true } } describe("ScopedDisposable") { it("should be initialized with an instance of `Disposable` protocol type") { let d: Disposable = AnyDisposable() let scoped = ScopedDisposable(d) expect(type(of: scoped) == ScopedDisposable<AnyDisposable>.self) == true } it("should dispose of the inner disposable upon deinitialization") { let simpleDisposable = AnyDisposable() func runScoped() { let scopedDisposable = ScopedDisposable(simpleDisposable) expect(simpleDisposable.isDisposed) == false expect(scopedDisposable.isDisposed) == false } expect(simpleDisposable.isDisposed) == false runScoped() expect(simpleDisposable.isDisposed) == true } } describe("SerialDisposable") { var disposable: SerialDisposable! beforeEach { disposable = SerialDisposable() } it("should dispose of the inner disposable") { let simpleDisposable = AnyDisposable() disposable.inner = simpleDisposable expect(disposable.inner).notTo(beNil()) expect(simpleDisposable.isDisposed) == false expect(disposable.isDisposed) == false disposable.dispose() expect(disposable.inner).to(beNil()) expect(simpleDisposable.isDisposed) == true expect(disposable.isDisposed) == true } it("should dispose of the previous disposable when swapping innerDisposable") { let oldDisposable = AnyDisposable() let newDisposable = AnyDisposable() disposable.inner = oldDisposable expect(oldDisposable.isDisposed) == false expect(newDisposable.isDisposed) == false disposable.inner = newDisposable expect(oldDisposable.isDisposed) == true expect(newDisposable.isDisposed) == false expect(disposable.isDisposed) == false disposable.inner = nil expect(newDisposable.isDisposed) == true expect(disposable.isDisposed) == false } } } }
mit
ba3943ca6c46dd3a00cb917d05007a35
25.215569
90
0.696894
4.197507
false
false
false
false