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
ReactiveX/RxSwift
Tests/RxSwiftTests/VirtualSchedulerTest.swift
1
6540
// // VirtualSchedulerTest.swift // Tests // // Created by Krunoslav Zaher on 12/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import XCTest #if os(Linux) import Glibc #endif import Foundation class VirtualSchedulerTest : RxTest { } extension VirtualSchedulerTest { func testVirtualScheduler_initialClock() { let scheduler = TestVirtualScheduler(initialClock: 10) XCTAssertEqual(scheduler.now, Date(timeIntervalSince1970: 100.0)) XCTAssertEqual(scheduler.clock, 10) } func testVirtualScheduler_start() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { _ in times.append(scheduler.clock) _ = scheduler.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler.clock) return Disposables.create() } return scheduler.schedule(()) { _ in times.append(scheduler.clock) return Disposables.create() } } scheduler.start() XCTAssertEqual(times, [ 1, 1, 3 ]) } func testVirtualScheduler_disposeStart() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { _ in times.append(scheduler.clock) let d = scheduler.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler.clock) return Disposables.create() } let d2 = scheduler.schedule(()) { _ in times.append(scheduler.clock) return Disposables.create() } d2.dispose() d.dispose() return Disposables.create() } scheduler.start() XCTAssertEqual(times, [ 1 ]) } func testVirtualScheduler_advanceToAfter() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { _ in times.append(scheduler.clock) _ = scheduler.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler.clock) return Disposables.create() } return scheduler.schedule(()) { _ in times.append(scheduler.clock) return Disposables.create() } } scheduler.advanceTo(10) XCTAssertEqual(times, [ 1, 1, 3 ]) } func testVirtualScheduler_advanceToBefore() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { [weak scheduler] _ in times.append(scheduler!.clock) _ = scheduler!.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler!.clock) return Disposables.create() } return scheduler!.schedule(()) { _ in times.append(scheduler!.clock) return Disposables.create() } } scheduler.advanceTo(1) XCTAssertEqual(times, [ 1, 1 ]) } func testVirtualScheduler_disposeAdvanceTo() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { [weak scheduler] _ in times.append(scheduler!.clock) let d1 = scheduler!.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler!.clock) return Disposables.create() } let d2 = scheduler!.schedule(()) { _ in times.append(scheduler!.clock) return Disposables.create() } d1.dispose() d2.dispose() return Disposables.create() } scheduler.advanceTo(20) XCTAssertEqual(times, [ 1, ]) } func testVirtualScheduler_stop() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { [weak scheduler] _ in times.append(scheduler!.clock) _ = scheduler!.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler!.clock) return Disposables.create() } _ = scheduler!.schedule(()) { _ in times.append(scheduler!.clock) return Disposables.create() } scheduler!.stop() return Disposables.create() } scheduler.start() XCTAssertEqual(times, [ 1, ]) } func testVirtualScheduler_sleep() { let scheduler = TestVirtualScheduler() var times: [Int] = [] _ = scheduler.scheduleRelative((), dueTime: .seconds(10)) { [weak scheduler] _ in times.append(scheduler!.clock) scheduler!.sleep(10) _ = scheduler!.scheduleRelative((), dueTime: .seconds(20)) { _ in times.append(scheduler!.clock) return Disposables.create() } _ = scheduler!.schedule(()) { _ in times.append(scheduler!.clock) return Disposables.create() } return Disposables.create() } scheduler.start() XCTAssertEqual(times, [ 1, 11, 13 ]) } func testVirtualScheduler_stress() { let scheduler = TestVirtualScheduler() var times = [Int]() var ticks = [Int]() for _ in 0 ..< 20000 { #if os(Linux) let random = Int(Glibc.random() % 10000) #else let random = Int(arc4random() % 10000) #endif times.append(random) _ = scheduler.scheduleRelative((), dueTime: .seconds(10 * random)) { [weak scheduler] _ in ticks.append(scheduler!.clock) return Disposables.create() } } scheduler.start() times = times.sorted() XCTAssertEqual(times, ticks) } }
mit
53c58b7e27826dcb004edb4a3e33c15d
26.13278
102
0.516593
4.991603
false
true
false
false
RobotsAndPencils/SwiftCharts
Examples/Examples/CandleStickInteractiveExample.swift
1
15207
// // CandleStickInteractiveExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class CandleStickInteractiveExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) var readFormatter = NSDateFormatter() readFormatter.dateFormat = "dd.MM.yyyy" var displayFormatter = NSDateFormatter() displayFormatter.dateFormat = "MMM dd" let date = {(str: String) -> NSDate in return readFormatter.dateFromString(str)! } let calendar = NSCalendar.currentCalendar() let dateWithComponents = {(day: Int, month: Int, year: Int) -> NSDate in let components = NSDateComponents() components.day = day components.month = month components.year = year return calendar.dateFromComponents(components)! } func filler(date: NSDate) -> ChartAxisValueDate { let filler = ChartAxisValueDate(date: date, formatter: displayFormatter) filler.hidden = true return filler } let chartPoints = [ ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39), ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4), ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5), ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5), ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44), ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46), ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5), ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49), ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5), ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39), ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40), ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38), ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39), ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36), ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5), ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31), ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30), ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25), ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5), ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27), ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30), ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31), ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6), ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5), ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6), ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33) ] func generateDateAxisValues(month: Int, year: Int) -> [ChartAxisValueDate] { let date = dateWithComponents(1, month, year) let calendar = NSCalendar.currentCalendar() let monthDays = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date) return Array(monthDays.toRange()!).map {day in let date = dateWithComponents(day, month, year) let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings) axisValue.hidden = !(day % 5 == 0) return axisValue } } let xValues = generateDateAxisValues(10, year: 2015) let yValues = 20.stride(through: 55, by: 5).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)} let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let defaultChartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let infoViewHeight: CGFloat = 50 let chartFrame = CGRectMake(defaultChartFrame.origin.x, defaultChartFrame.origin.y + infoViewHeight, defaultChartFrame.width, defaultChartFrame.height - infoViewHeight) let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let viewGenerator = {(chartPointModel: ChartPointLayerModel<ChartPointCandleStick>, layer: ChartPointsViewsLayer<ChartPointCandleStick, ChartCandleStickView>, chart: Chart) -> ChartCandleStickView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) let x = screenLoc.x let highScreenY = screenLoc.y let lowScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y let openScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y let closeScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.whiteColor()) : (openScreenY, closeScreenY, UIColor.blackColor()) let v = ChartCandleStickView(lineX: screenLoc.x, width: Env.iPad ? 10 : 5, top: highScreenY, bottom: lowScreenY, innerRectTop: rectTop, innerRectBottom: rectBottom, fillColor: fillColor, strokeWidth: Env.iPad ? 1 : 0.5) v.userInteractionEnabled = false return v } let candleStickLayer = ChartPointsCandleStickViewsLayer<ChartPointCandleStick, ChartCandleStickView>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: viewGenerator) let infoView = InfoWithIntroView(frame: CGRectMake(10, 70, self.view.frame.size.width, infoViewHeight)) self.view.addSubview(infoView) let trackerLayer = ChartPointsTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, locChangedFunc: {[weak candleStickLayer, weak infoView] screenLoc in candleStickLayer?.highlightChartpointView(screenLoc: screenLoc) if let chartPoint = candleStickLayer?.chartPointsForScreenLocX(screenLoc.x).first { infoView?.showChartPoint(chartPoint) } else { infoView?.clear() } }, lineColor: UIColor.redColor(), lineWidth: Env.iPad ? 1 : 0.6) let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true) let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true) let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, dividersLayer, candleStickLayer, trackerLayer ] ) self.view.addSubview(chart.view) self.chart = chart } } private class InfoView: UIView { let statusView: UIView let dateLabel: UILabel let lowTextLabel: UILabel let highTextLabel: UILabel let openTextLabel: UILabel let closeTextLabel: UILabel let lowLabel: UILabel let highLabel: UILabel let openLabel: UILabel let closeLabel: UILabel override init(frame: CGRect) { let itemHeight: CGFloat = 40 let y = (frame.height - itemHeight) / CGFloat(2) self.statusView = UIView(frame: CGRectMake(0, y, itemHeight, itemHeight)) self.statusView.layer.borderColor = UIColor.blackColor().CGColor self.statusView.layer.borderWidth = 1 self.statusView.layer.cornerRadius = Env.iPad ? 13 : 8 let font = ExamplesDefaults.labelFont self.dateLabel = UILabel() self.dateLabel.font = font self.lowTextLabel = UILabel() self.lowTextLabel.text = "Low:" self.lowTextLabel.font = font self.lowLabel = UILabel() self.lowLabel.font = font self.highTextLabel = UILabel() self.highTextLabel.text = "High:" self.highTextLabel.font = font self.highLabel = UILabel() self.highLabel.font = font self.openTextLabel = UILabel() self.openTextLabel.text = "Open:" self.openTextLabel.font = font self.openLabel = UILabel() self.openLabel.font = font self.closeTextLabel = UILabel() self.closeTextLabel.text = "Close:" self.closeTextLabel.font = font self.closeLabel = UILabel() self.closeLabel.font = font super.init(frame: frame) self.addSubview(self.statusView) self.addSubview(self.dateLabel) self.addSubview(self.lowTextLabel) self.addSubview(self.lowLabel) self.addSubview(self.highTextLabel) self.addSubview(self.highLabel) self.addSubview(self.openTextLabel) self.addSubview(self.openLabel) self.addSubview(self.closeTextLabel) self.addSubview(self.closeLabel) } private override func didMoveToSuperview() { let views = [self.statusView, self.dateLabel, self.highTextLabel, self.highLabel, self.lowTextLabel, self.lowLabel, self.openTextLabel, self.openLabel, self.closeTextLabel, self.closeLabel] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerate().map{index, view in ("v\(index)", view) } let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in u[tuple.0] = tuple.1 return u } let circleDiameter: CGFloat = Env.iPad ? 26 : 15 let labelsSpace: CGFloat = Env.iPad ? 10 : 5 let hConstraintStr = namedViews[1..<namedViews.count].reduce("H:|[v0(\(circleDiameter))]") {str, tuple in "\(str)-(\(labelsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|-(18)-[\($0.0)(\(circleDiameter))]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)} self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showChartPoint(chartPoint: ChartPointCandleStick) { let color = chartPoint.open > chartPoint.close ? UIColor.blackColor() : UIColor.whiteColor() self.statusView.backgroundColor = color self.dateLabel.text = chartPoint.x.labels.first?.text ?? "" self.lowLabel.text = "\(chartPoint.low)" self.highLabel.text = "\(chartPoint.high)" self.openLabel.text = "\(chartPoint.open)" self.closeLabel.text = "\(chartPoint.close)" } func clear() { self.statusView.backgroundColor = UIColor.clearColor() } } private class InfoWithIntroView: UIView { var introView: UIView! var infoView: InfoView! override init(frame: CGRect) { super.init(frame: frame) } private override func didMoveToSuperview() { let label = UILabel(frame: CGRectMake(0, self.bounds.origin.y, self.bounds.width, self.bounds.height)) label.text = "Drag the line to see chartpoint data" label.font = ExamplesDefaults.labelFont label.backgroundColor = UIColor.whiteColor() self.introView = label self.infoView = InfoView(frame: self.bounds) self.addSubview(self.infoView) self.addSubview(self.introView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func animateIntroAlpha(alpha: CGFloat) { UIView.animateWithDuration(0.1, animations: { self.introView.alpha = alpha }) } func showChartPoint(chartPoint: ChartPointCandleStick) { self.animateIntroAlpha(0) self.infoView.showChartPoint(chartPoint) } func clear() { self.animateIntroAlpha(1) self.infoView.clear() } }
apache-2.0
af18869e1ab095b98fe06faf85443cd2
47.126582
231
0.642402
4.507113
false
false
false
false
wojteklu/logo
Logo/Logo/Evaluation/Environment.swift
1
657
import Foundation enum Constant: String { case heading case stack case x case y } class Environment { var map: [String: Object] = [:] func get(name: String) -> Object? { return map[name] } func get(constant: Constant) -> Object? { return get(name: constant.rawValue) } func set(name: String, value: Object) { map[name] = value } func set(constant: Constant, value: Object) { map[constant.rawValue] = value } func copy() -> Environment { let environment = Environment() environment.map = map return environment } }
mit
e40e2fba2156128765f686497258d19d
18.323529
49
0.560122
4.211538
false
false
false
false
stephentyrone/swift
test/IRGen/signature_conformances_multifile_future.swift
3
2274
// RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir -primary-file %s %S/Inputs/signature_conformances_other.swift | %FileCheck %s -DINT=i%target-ptrsize // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // Make sure we correctly determine the witness table is dependent, even though // it was defined in a different file. // CHECK-LABEL: define hidden swiftcc void @"$s39signature_conformances_multifile_future5passQyyF"() func passQ() { // CHECK: call swiftcc void @"$s39signature_conformances_multifile_future12AlsoConformsVACyxGycfC"(%swift.type* @"$sSiN") // CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s39signature_conformances_multifile_future12AlsoConformsVySiGMD") // CHECK: [[WITNESS_TABLE:%[0-9]+]] = call i8** @"$s39signature_conformances_multifile_future12AlsoConformsVySiGACyxGAA1QAAWl"() // CHECK: call swiftcc void @"$s39signature_conformances_multifile_future6takesQyyxAA1QRzlF"( // CHECK-SAME: %swift.opaque* noalias nocapture undef, // CHECK-SAME: %swift.type* [[METADATA]], // CHECK-SAME: i8** [[WITNESS_TABLE]] // CHECK-SAME: ) takesQ(AlsoConforms<Int>()) // CHECK: ret void } // CHECK-LABEL: define hidden swiftcc void @"$s39signature_conformances_multifile_future5passPyyF"() func passP() { // CHECK: call swiftcc void @"$s39signature_conformances_multifile_future8ConformsVACyxq_GycfC"(%swift.type* @"$sSiN", %swift.type* @"$sSSN") // CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s39signature_conformances_multifile_future8ConformsVySiSSGMD") // CHECK: [[WITNESS_TABLE:%[0-9]+]] = call i8** @"$s39signature_conformances_multifile_future8ConformsVySiSSGACyxq_GAA1PAAWl"() // CHECK: call swiftcc void @"$s39signature_conformances_multifile_future6takesPyyxAA1PRzlF"( // CHECK-SAME: %swift.opaque* noalias nocapture undef, // CHECK-SAME: %swift.type* [[METADATA]], // CHECK-SAME: i8** [[WITNESS_TABLE]] // CHECK-SAME: ) takesP(Conforms<Int, String>()) // CHECK: ret void }
apache-2.0
fd39c4c413fc4bdce8e93794890f529b
57.307692
202
0.716799
3.569859
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Buttons/BorderButton.swift
1
2091
import Foundation @IBDesignable class BorderButton: UIButton { var cornerRadius: CGFloat { return frame.height/9 } @IBInspectable var borderWidth: CGFloat = 1 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor setTitleColor(borderColor, for: .normal) } } override var isHighlighted: Bool { didSet { invalidateAppearance() } } override func tintColorDidChange() { super.tintColorDidChange() invalidateAppearance() } override var intrinsicContentSize: CGSize { guard let label = titleLabel else { return super.intrinsicContentSize } let size = label.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) let height = size.height + 10 let width = size.width + 15 return CGSize(width: width, height: height) } override func awakeFromNib() { super.awakeFromNib() borderWidth = 1 } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } func invalidateAppearance() { let isDimmed = tintAdjustmentMode == .dimmed let filled = isDimmed ? false : isHighlighted let color: UIColor = isDimmed ? tintColor : isHighlighted ? borderColor ?? tintColor : tintColor UIView.animate(withDuration: 0.25, delay: 0.0, options: [.allowUserInteraction, .curveEaseInOut], animations: { [unowned self] in self.layer.borderColor = color.cgColor if filled { self.backgroundColor = color self.setTitleColor(.white, for: .highlighted) } else { self.backgroundColor = .clear self.setTitleColor(color, for: .normal) } }) } }
gpl-3.0
153b9929d1a37c27aa9bd3390c438a6e
27.256757
137
0.58154
5.620968
false
false
false
false
vishw3/IOSChart-IOS-7.0-Support
VisChart/Classes/Renderers/ChartXAxisRenderer.swift
2
11285
// // ChartXAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartXAxisRenderer: ChartAxisRendererBase { internal var _xAxis: ChartXAxis!; public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer); _xAxis = xAxis; } public func computeAxis(#xValAverageLength: Float, xValues: [String]) { var a = ""; var max = Int(round(xValAverageLength + Float(_xAxis.spaceBetweenLabels))); for (var i = 0; i < max; i++) { a += "h"; } var widthText = a as NSString; var heightText = "Q" as NSString; _xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; _xAxis.labelHeight = _xAxis.labelFont.lineHeight; _xAxis.values = xValues; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return; } var yoffset = CGFloat(4.0); if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset); drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6); } } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _xAxis.axisLineWidth); if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); var maxx = self._maxX; var minx = self._minX; if (maxx >= _xAxis.values.count) { maxx = _xAxis.values.count - 1; } if (minx < 0) { minx = 0; } for (var i = minx; i <= maxx; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i); position.y = 0.0; position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (viewPortHandler.isInBoundsX(position.x)) { var label = _xAxis.values[i]; var labelns = label as NSString; if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1) { var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0; } } else if (i == 0) { // avoid clipping of the first var width = labelns.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width; position.x += width / 2.0; } } ChartUtils.drawText(context: context, text: label, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i); position.y = 0.0; position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (position.x >= viewPortHandler.offsetLeft && position.x <= viewPortHandler.chartWidth) { _gridLineSegmentsBuffer[0].x = position.x; _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _gridLineSegmentsBuffer[1].x = position.x; _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines; if (limitLines.count == 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = CGFloat(l.limit); position.y = 0.0; position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = position.x; _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _limitLineSegmentsBuffer[1].x = position.y; _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = l.lineWidth; var yOffset: CGFloat = add / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
mit
a8c0f4c2aac58c3cd0796ab8d9f0109c
35.406452
216
0.544971
5.603277
false
false
false
false
szysz3/ios-timetracker
TimeTracker/UIConsts.swift
1
498
// // UIConsts.swift // TimeTracker // // Created by Michał Szyszka on 27.09.2016. // Copyright © 2016 Michał Szyszka. All rights reserved. // import Foundation import UIKit class UIConsts { //MARK: Fields static let alertTitle = "Oops!" static let alertBtnTitle = "OK" static let mainViewSegueName = "showMainView" static let loginViewSegueName = "showLoginView" static let cornerRadius: CGFloat = 4 static let borderWidth: CGFloat = 0.5 }
mit
53a1139e1d9d9f627dc51b9c0fea7107
19.625
57
0.670707
3.897638
false
false
false
false
mminami/MMMoviePlayer
Demo/Demo/MovieItemCell.swift
1
976
// // Created by mminami on 2017/10/27. // Copyright (c) 2017 mminami. All rights reserved. // import Foundation import UIKit protocol CellProtocol { static var identifier: String { get } } protocol NibProtocol { static var nib: UINib { get } } class MovieItemCell: UITableViewCell, CellProtocol, NibProtocol { static var identifier = "\(MovieItemCell.self)" static var nib: UINib { return UINib(nibName: "\(MovieItemCell.self)", bundle: nil) } @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! func configure(_ movieItem: MovieItem) { nameLabel.text = movieItem.presenterName titleLabel.text = movieItem.title descriptionLabel.text = movieItem.description durationLabel.text = movieItem.videoDurationText } }
mit
e82d80d548a26473196c24b97ac36be8
26.885714
67
0.704918
4.376682
false
false
false
false
to4iki/conference-app-2017-ios
conference-app-2017/data/storage/DiskCache.swift
1
2344
import Cache import Himotoki import Result /// hyperoslo/Cache Adapter struct DiskCache: Storage { private let base = HybridCache(name: Bundle.main.bundleIdentifier!) static let shared = DiskCache() private init() {} func read<T: Decodable>(key: String, completion: @escaping (Result<T, StorageError>) -> Void) { base.async.object(forKey: key) { (json: JSON?) in if case .some(.dictionary(let value)) = json { do { let result = try T.decodeValue(value) completion(.success(result)) } catch { completion(.failure(.read(error))) } } else { completion(.failure(.notFound)) } } } func read<T: Decodable>(key: String, completion: @escaping (Result<[T], StorageError>) -> Void) { base.async.object(forKey: key) { (json: JSON?) in if case .some(.array(let value)) = json { do { let result: [T] = try decodeArray(value) completion(.success(result)) } catch { completion(.failure(.read(error))) } } else { completion(.failure(.notFound)) } } } func write(_ value: JSON, key: String, completion: @escaping (Result<Void, StorageError>) -> Void) { base.async.addObject(value, forKey: key) { (error: Error?) in if let error = error { completion(.failure(.write(error))) } else { completion(.success()) } } } func remove(key: String, completion: @escaping (Result<Void, StorageError>) -> Void) { base.async.removeObject(forKey: key) { (error: Error?) in if let error = error { completion(.failure(.remove(error))) } else { completion(.success()) } } } func removeAll(completion: @escaping (Result<Void, StorageError>) -> Void) { base.async.clear(keepingRootDirectory: true) { (error: Error?) in if let error = error { completion(.failure(.remove(error))) } else { completion(.success()) } } } }
apache-2.0
959cb0c4e02ada3383f9ba1ac6e777cb
32.014085
104
0.502986
4.697395
false
false
false
false
quadro5/swift3_L
swift_question.playground/Pages/Shuffle Array.xcplaygroundpage/Contents.swift
1
3437
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) extension Array { func shuffle() -> Array { var res = self let count = res.count if count < 2 { return res } for index in 0..<count - 1 { let resCount = count - index let exchangeIndex = index + Int(arc4random_uniform(UInt32(resCount))) swap(&res[index], &res[exchangeIndex]) } return res } } /* 把每个数等概率的放到任何一个位置 每一个位置等概率的得到某个值。 similar with n persons lottery n ticket(number from 1~n) for each person, it's equal probability to get any ticket number 来计算一下概率。如果某个元素被放入第i(1≤i≤n1≤i≤n )个位置, 就必须是在前i - 1次选取中都没有选到它,并且第i次选取是恰好选中它。 其概率为: pi=n−1/n × n−2/n−1 ×⋯× n−i+1/n−i+2 × 1/n−i+1 = 1/n */ func shuffle(nums: [Int]) -> [Int] { var nums = nums let count = nums.count if count < 2 { return nums } for index in 0..<count - 1 { let restCount = count - index let exchangeIndex = index + Int(arc4random_uniform(UInt32(restCount))) if index != exchangeIndex { swap(&nums[index], &nums[exchangeIndex]) } } return nums } let nums = [1, 2, 3, 4, 5, 6] let res = shuffle(nums: nums) // 这个改良版本接受⼀个 UInt32 的数字 n 作为输⼊,将结果归⼀化到 0 到 n - 1 之间。只要我们的输⼊不超过 Int 的范围,就可以避免危险的转换: let diceFaceCount: UInt32 = 6 let randomRoll = Int(arc4random_uniform(diceFaceCount)) + 1 //print(randomRoll) // 最佳实践当然是为创建⼀个 Range 的随机数的⽅法,这样我们就能在之后很容易地复⽤,甚⾄设计类似与 Randomable 这样的协议了: func random(in range: Range<Int>) -> Int { let count = UInt32(range.upperBound - range.lowerBound) return Int(arc4random_uniform(count)) + range.lowerBound } for _ in 0...2 { let range = Range<Int>(1...6) print(random(in: range)) } Int.max Int64.max Int32.max UInt32.max let testInt: Int64 = 9223372036854775807 if testInt > Int64(UInt32.max) { print("more than UInt32.max") } else { print("less than UInt32.max") } // 3 Random max index /* equal probability 可以用Reservoir Sampling 不需要额外space 如果被选中则会替换res结果。 所以被须满足当前点选中,后面点都不中才可以满足条件。 假设元素为i,则被选中的概率为: 1/i i/(i+1) i+1)/(i+2)* ... (n-1)/n = 1/n; //给一个全是数字的数组,随机返回0到当前位置中最大值得坐标 //比如【1,2,3,3,3,3,1,2】 //在最后一个2的时候有4个3都是最大值,要按1/4的概率返回其中一个3的index //[1, 2, 3, 3, 3, 3] */ func random_max(nums: [Int]) -> Int { var res = 0 var count = 0 var max = Int.min for i in 0..<nums.count { // keep tracking max value if nums[i] > max { max = nums[i] count = 1 res = i // if max value more than one } else if nums[i] == max { count += 1 if Int(arc4random()) % count == 0 { res = i; } } } return res }
unlicense
793d739637512ac26e45f8232b004bcb
19.614815
122
0.584621
2.725759
false
false
false
false
ramunasjurgilas/operation-queue-ios
operation-queue-ios/ViewControllers/CompletedTasks/CompletedTasksViewController.swift
1
5082
// // CompletedTasksViewController.swift // operation-queue-ios // // Created by Ramunas Jurgilas on 2017-04-11. // Copyright © 2017 Ramūnas Jurgilas. All rights reserved. // import UIKit import CoreData class CompletedTasksViewController: UITableViewController, NSFetchedResultsControllerDelegate, TaskCellDelegate { // MARK: - Table view data source override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func numberOfSections(in tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) let task = self.fetchedResultsController.object(at: indexPath) (cell as? TaskCell)?.configureWithTask(task, delegate: self) return cell } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController<Task> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest() // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.predicate = [TaskStatus.completed].predicate() fetchRequest.sortDescriptors = [sortDescriptor] let moc = CoreDataManager.shared.persistentContainer.viewContext moc.automaticallyMergesChangesFromParent = true // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil) aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController<Task>? = nil func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: break case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } // MARK: - TaskCellDelegate func didSwipeLeft(_ task: Task) { moveBackToPending(task) } func didSwipeRight(_ task: Task) { moveBackToPending(task) } // MARK: - Private Methods private func moveBackToPending(_ task: Task) { task.status = TaskStatus.pending.rawValue task.duration = 0 try? task.managedObjectContext?.save() } }
mit
e7ab36a7aec4ed9075ace6830ea83f31
38.379845
209
0.678346
5.812357
false
false
false
false
sschiau/swift
test/Constraints/diagnostics_swift4.swift
2
1793
// RUN: %target-typecheck-verify-swift -swift-version 4 // SR-2505: "Call arguments did not match up" assertion func sr_2505(_ a: Any) {} // expected-note {{}} sr_2505() // expected-error {{missing argument for parameter #1 in call}} sr_2505(a: 1) // expected-error {{extraneous argument label 'a:' in call}} sr_2505(1, 2) // expected-error {{extra argument in call}} sr_2505(a: 1, 2) // expected-error {{extra argument in call}} struct C_2505 { init(_ arg: Any) { } } protocol P_2505 { } extension C_2505 { init<T>(from: [T]) where T: P_2505 { } } class C2_2505: P_2505 { } let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{incorrect argument label in call (have 'arg:', expected 'from:')}} // rdar://problem/31898542 - Swift 4: 'type of expression is ambiguous without more context' errors, without a fixit enum R31898542<T> { case success(T) // expected-note {{'success' declared here}} case failure } func foo() -> R31898542<()> { return .success() // expected-error {{missing argument for parameter #1 in call}} {{19-19=<#()#>}} } // rdar://problem/31973368 - Cannot convert value of type '(K, V) -> ()' to expected argument type '((key: _, value: _)) -> Void' // SE-0110: We reverted to allowing this for the time being, but this // test is valuable in case we end up disallowing it again in the // future. class R<K: Hashable, V> { func forEach(_ body: (K, V) -> ()) { let dict: [K:V] = [:] dict.forEach(body) } } // Make sure that solver doesn't try to form solutions with available overloads when better generic choices are present. infix operator +=+ : AdditionPrecedence func +=+(_ lhs: Int, _ rhs: Int) -> Bool { return lhs == rhs } func +=+<T: BinaryInteger>(_ lhs: T, _ rhs: Int) -> Bool { return lhs == rhs }
apache-2.0
06e6d0058cc3ab3aba66257ddce0a9bd
31.017857
129
0.63971
3.265938
false
false
false
false
practicalswift/swift
test/IDE/print_clang_decls.swift
2
9619
// RUN: %empty-directory(%t) // REQUIRES: objc_interop // This file deliberately does not use %clang-importer-sdk for most RUN lines. // Instead, it generates custom overlay modules itself, and uses -I %t when it // wants to use them. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=TAG_DECLS_AND_TYPEDEFS -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=FOUNDATION -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes.bits -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=CTYPESBITS -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=nullability -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=CHECK-NULLABILITY -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=bridged_typedef -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=CHECK-BRIDGED-TYPEDEF -strict-whitespace < %t.printed.txt // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct1 {{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: /*! // TAG_DECLS_AND_TYPEDEFS-NEXT: @keyword Foo2 // TAG_DECLS_AND_TYPEDEFS-NEXT: */ // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStruct2 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}typealias FooStructTypedef1 = FooStruct2{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStructTypedef2 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct3 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct4 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct5 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct6 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // Skip through unavailable typedefs when importing types. // TAG_DECLS_AND_TYPEDEFS: @available(*, unavailable, message: "use double") // TAG_DECLS_AND_TYPEDEFS-NEXT: typealias real_t = Double // TAG_DECLS_AND_TYPEDEFS-NEXT: func realSin(_ value: Double) -> Double // NEGATIVE-NOT: typealias FooStructTypedef2 // FOUNDATION-LABEL: {{^}}/// Aaa. NSArray. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}class NSArray : NSObject {{{$}} // FOUNDATION-NEXT: init!(objects: UnsafePointer<AnyObject>?, count cnt: Int) // FOUNDATION-NEXT: subscript(idx: Int) -> Any { get } // FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingMode. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}enum NSRuncingMode : UInt {{{$}} // FOUNDATION-NEXT: {{^}} init?(rawValue: UInt){{$}} // FOUNDATION-NEXT: {{^}} var rawValue: UInt { get }{{$}} // FOUNDATION-NEXT: {{^}} typealias RawValue = UInt // FOUNDATION-NEXT: {{^}} case mince{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "mince"){{$}} // FOUNDATION-NEXT: {{^}} static var Mince: NSRuncingMode { get }{{$}} // FOUNDATION-NEXT: {{^}} case quince{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "quince"){{$}} // FOUNDATION-NEXT: {{^}} static var Quince: NSRuncingMode { get }{{$}} // FOUNDATION-NEXT: {{^}}}{{$}} // FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingOptions. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}struct NSRuncingOptions : OptionSet {{{$}} // FOUNDATION-NEXT: {{^}} init(rawValue: UInt){{$}} // FOUNDATION-NEXT: {{^}} let rawValue: UInt{{$}} // FOUNDATION-NEXT: {{^}} typealias RawValue = UInt // FOUNDATION-NEXT: {{^}} typealias Element = NSRuncingOptions // FOUNDATION-NEXT: {{^}} typealias ArrayLiteralElement = NSRuncingOptions // FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}} // FOUNDATION-NEXT: {{^}} static var none: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "none"){{$}} // FOUNDATION-NEXT: {{^}} static var None: NSRuncingOptions { get } // FOUNDATION-NEXT: {{^}} static var enableMince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableMince"){{$}} // FOUNDATION-NEXT: {{^}} static var EnableMince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} static var enableQuince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableQuince"){{$}} // FOUNDATION-NEXT: {{^}} static var EnableQuince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}}}{{$}} // FOUNDATION-LABEL: {{^}}/// Unavailable Global Functions{{$}} // FOUNDATION-NEXT: @available(*, unavailable, message: "Zone-based memory management is unavailable") // FOUNDATION-NEXT: NSSetZoneName(_ zone: NSZone, _ name: String) // FOUNDATION-LABEL: struct FictionalServerError // FOUNDATION: enum Code // FOUNDATION: case meltedDown // FOUNDATION: static var meltedDown: FictionalServerError.Code // FOUNDATION-LABEL: extension NSLaundromat { // FOUNDATION-NEXT: struct Error // FOUNDATION: enum Code // FOUNDATION: case tooMuchSoap // FOUNDATION: static var tooMuchSoap: NSLaundromat.Error.Code { get } // CTYPESBITS-NOT: FooStruct1 // CTYPESBITS: {{^}}typealias DWORD = Int32{{$}} // CTYPESBITS-NEXT: {{^}}var MY_INT: Int32 { get }{{$}} // CTYPESBITS-NOT: FooStruct1 // CHECK-NULLABILITY: func getId1() -> Any? // CHECK-NULLABILITY: var global_id: AnyObject? // CHECK-NULLABILITY: class SomeClass { // CHECK-NULLABILITY: class func methodA(_ obj: SomeClass?) -> Any{{$}} // CHECK-NULLABILITY: func methodA(_ obj: SomeClass?) -> Any{{$}} // CHECK-NULLABILITY: class func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}} // CHECK-NULLABILITY: func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}} // CHECK-NULLABILITY: func methodC() -> Any? // CHECK-NULLABILITY: var property: Any? // CHECK-NULLABILITY: func stringMethod() -> String{{$}} // CHECK-NULLABILITY: func optArrayMethod() -> [Any]? // CHECK-NULLABILITY: } // CHECK-NULLABILITY: func compare_classes(_ sc1: SomeClass, _ sc2: SomeClass, _ sc3: SomeClass!) // CHECK-BRIDGED-TYPEDEF: typealias NSMyAmazingStringAlias = String // CHECK-BRIDGED-TYPEDEF: func acceptNSMyAmazingStringAlias(_ param: NSMyAmazingStringAlias?) // CHECK-BRIDGED-TYPEDEF: func acceptNSMyAmazingStringAliasArray(_ param: [NSMyAmazingStringAlias]) // CHECK-BRIDGED-TYPEDEF: func acceptIndirectedAmazingAlias(_ param: AutoreleasingUnsafeMutablePointer<NSString>?)
apache-2.0
0fdf5655d0bc77063067c9596a882229
57.652439
219
0.655058
3.337613
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingUI/Order/AcceptLegalView.swift
1
2608
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import ComposableArchitecture import FeatureCardIssuingDomain import Localization import SwiftUI import ToolKit struct AcceptLegalView: View { @State private var loading = true private typealias L10n = LocalizationConstants.CardIssuing.Legal private let store: Store<AcceptLegalState, AcceptLegalAction> init(store: Store<AcceptLegalState, AcceptLegalAction>) { self.store = store } var body: some View { VStack(spacing: 0) { WithViewStore(store) { viewStore in ZStack(alignment: .center) { Text(viewStore.state.current?.displayName ?? "") .typography(.title3) .padding([.top, .leading], Spacing.padding1) HStack { Spacer() Icon.closeCirclev2 .frame(width: 24, height: 24) .onTapGesture(perform: { viewStore.send(.close) }) } .padding(.horizontal, Spacing.padding2) } .padding(.bottom, Spacing.padding2) } IfLetStore( store.scope(state: \.current?.url), then: { store in WithViewStore(store) { viewStore in WebView( url: viewStore.state, loading: $loading ) } }, else: { Spacer() } ) WithViewStore(store) { viewStore in HStack(alignment: .center) { PrimaryButton( title: viewStore.state.hasNext ? L10n.Button.next : L10n.Button.accept, isLoading: viewStore.state.accepted == .loading || loading ) { viewStore.send(viewStore.state.hasNext ? .next : .accept) } .disabled(viewStore.state.accepted == .loading || loading) } .padding(Spacing.padding2) .onAppear { viewStore.send(.onAppear) } } } .listStyle(PlainListStyle()) .padding(.vertical, Spacing.padding2) .background(Color.semantic.background.ignoresSafeArea()) } }
lgpl-3.0
da6155724e16575d4fca0806b484f4e4
33.76
95
0.475643
5.582441
false
false
false
false
gbarcena/GifResizer
GifResizer/ViewController.swift
1
3086
// // ViewController.swift // GifResizer // // Created by Gustavo Barcena on 5/27/15. // Copyright (c) 2015 Gustavo Barcena. All rights reserved. // import UIKit import GifWriter import YLGIFImage func runOnMainThread(_ block:@escaping ()->()) { DispatchQueue.main.async { block() } } func stringFromSize(_ size:CGSize?) -> String { if let size = size { return "\(size.width)x\(size.height)" } return "" } class ViewController: UIViewController { @IBOutlet weak var imageView : YLImageView! @IBOutlet weak var label : UILabel! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.global(qos: .background).async { self.writeGIF() } } func writeGIF() { var images = [UIImage]() for i in 1...7 { let imageName = "ninenine_\(i)" if let image = UIImage(named: imageName) { images.append(image) } } let fileURL = type(of: self).fileLocation("ninenine.gif") guard let gifWriter = GIFWriter(images: images) else { return } gifWriter.makeGIF(fileURL) guard let data = try? Data(contentsOf: fileURL), let gifImage = YLGIFImage(data: data) else { return } runOnMainThread({ () -> () in self.imageView.image = gifImage self.label.text = "Created GIF \(stringFromSize(gifImage.size))" }) Thread.sleep(forTimeInterval: 1.0) let maxSize = 300000 let size = gifImage.size print("Original Size: \(data.count)") print("Original Width: \(size.width)") let newWidth = GIFResizer.calculateBestNewWidth(oldWidth: Int(size.width), oldSizeInBytes: data.count, maxSizeInBytes: maxSize) print("newWidth Width: \(newWidth)") let maxEdgeSize: Double if size.width >= size.height { maxEdgeSize = newWidth } else { maxEdgeSize = newWidth * Double(size.height / size.width) } let smallFileURL = type(of: self).fileLocation("ninenine-small.gif") let success = GIFResizer.resizeGIF(data, fileURL: smallFileURL, maxEdgeSize: maxEdgeSize) if (success) { if let data = try? Data(contentsOf: smallFileURL) { let gifImage = YLGIFImage(data: data) runOnMainThread { self.imageView.image = gifImage self.label.text = "Resized GIF \(stringFromSize(gifImage?.size))" } print("Final Size: \(data.count)") print("Final Width: \(gifImage!.size.width)") } } } class func fileLocation(_ fileName:String) -> URL { let path = URL(fileURLWithPath: NSTemporaryDirectory()) let fileURL = path.appendingPathComponent(fileName) return fileURL } }
mit
b0b1500125451136dc6bca959d0a35a3
28.961165
97
0.558328
4.485465
false
false
false
false
jmohr7/civil-war
civil-warTests/civil_warTests.swift
1
1329
// // civil_warTests.swift // civil-warTests // // Created by Joseph Mohr on 1/30/16. // Copyright © 2016 Mohr. All rights reserved. // import XCTest @testable import civil_war class civil_warTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testVectorMath(){ let pointA = CGPoint(x: 1.0, y: 1.0) let pointB = CGPoint(x: 2.0, y: 2.0) XCTAssert(pointA - pointB == CGPoint(x:-1.0, y: -1.0)) XCTAssert(pointA + pointB == CGPoint(x:3.0, y: 3.0)) XCTAssert(pointB * 3 == CGPoint(x:6.0, y: 6.0)) XCTAssert(pointB / 2 == CGPoint(x:1.0, y: 1.0)) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
3d6e5c909058cb9e4bc9001b628cc818
29.883721
111
0.603916
3.783476
false
true
false
false
Jnosh/swift
test/SILGen/generic_tuples.swift
14
1591
// RUN: %target-swift-frontend -emit-silgen -parse-as-library %s | %FileCheck %s func dup<T>(_ x: T) -> (T, T) { return (x,x) } // CHECK-LABEL: sil hidden @_T014generic_tuples3dup{{[_0-9a-zA-Z]*}}F // CHECK: ([[RESULT_0:%.*]] : $*T, [[RESULT_1:%.*]] : $*T, [[XVAR:%.*]] : $*T): // CHECK-NEXT: debug_value_addr [[XVAR]] : $*T, let, name "x" // CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_0]] // CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_1]] // CHECK-NEXT: destroy_addr [[XVAR]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] // <rdar://problem/13822463> // Specializing a generic function on a tuple type changes the number of // SIL parameters, which caused a failure in the ownership conventions code. struct Blub {} // CHECK-LABEL: sil hidden @_T014generic_tuples3foo{{[_0-9a-zA-Z]*}}F func foo<T>(_ x: T) {} // CHECK-LABEL: sil hidden @_T014generic_tuples3bar{{[_0-9a-zA-Z]*}}F func bar(_ x: (Blub, Blub)) { foo(x) } // rdar://26279628 // A type parameter constrained to be a concrete type must be handled // as that concrete type throughout SILGen. That's especially true // if it's constrained to be a tuple. protocol HasAssoc { associatedtype A } extension HasAssoc where A == (Int, Int) { func returnTupleAlias() -> A { return (0, 0) } } // CHECK-LABEL: sil hidden @_T014generic_tuples8HasAssocPA2aBRzSi_Sit1ARtzlE16returnTupleAliasSi_SityF : $@convention(method) <Self where Self : HasAssoc, Self.A == (Int, Int)> (@in_guaranteed Self) -> (Int, Int) { // CHECK: return {{.*}} : $(Int, Int)
apache-2.0
b455c61c59d2461c3b4856500dff74e3
39.794872
214
0.637335
3.03626
false
false
false
false
asashin227/LNKLabel
Example/Tests/Tests.swift
1
1158
// https://github.com/Quick/Quick import Quick import Nimble import LNKLabel 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" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
93663499762588a6d0286e6ecbff15bb
22.04
60
0.356771
5.538462
false
false
false
false
Awalz/SwiftyCam
Source/SwiftyCamButton.swift
1
4676
/*Copyright (c) 2016, Andrew Walz. Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit //MARK: Public Protocol Declaration /// Delegate for SwiftyCamButton public protocol SwiftyCamButtonDelegate: class { /// Called when UITapGestureRecognizer begins func buttonWasTapped() /// Called When UILongPressGestureRecognizer enters UIGestureRecognizerState.began func buttonDidBeginLongPress() /// Called When UILongPressGestureRecognizer enters UIGestureRecognizerState.end func buttonDidEndLongPress() /// Called when the maximum duration is reached func longPressDidReachMaximumDuration() /// Sets the maximum duration of the video recording func setMaxiumVideoDuration() -> Double } // MARK: Public View Declaration /// UIButton Subclass for Capturing Photo and Video with SwiftyCamViewController open class SwiftyCamButton: UIButton { /// Delegate variable public weak var delegate: SwiftyCamButtonDelegate? // Sets whether button is enabled public var buttonEnabled = true /// Maximum duration variable fileprivate var timer : Timer? /// Initialization Declaration override public init(frame: CGRect) { super.init(frame: frame) createGestureRecognizers() } /// Initialization Declaration required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createGestureRecognizers() } /// UITapGestureRecognizer Function @objc fileprivate func Tap() { guard buttonEnabled == true else { return } delegate?.buttonWasTapped() } /// UILongPressGestureRecognizer Function @objc fileprivate func LongPress(_ sender:UILongPressGestureRecognizer!) { guard buttonEnabled == true else { return } switch sender.state { case .began: delegate?.buttonDidBeginLongPress() startTimer() case .cancelled, .ended, .failed: invalidateTimer() delegate?.buttonDidEndLongPress() default: break } } /// Timer Finished @objc fileprivate func timerFinished() { invalidateTimer() delegate?.longPressDidReachMaximumDuration() } /// Start Maximum Duration Timer fileprivate func startTimer() { if let duration = delegate?.setMaxiumVideoDuration() { //Check if duration is set, and greater than zero if duration != 0.0 && duration > 0.0 { timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(SwiftyCamButton.timerFinished), userInfo: nil, repeats: false) } } } // End timer if UILongPressGestureRecognizer is ended before time has ended fileprivate func invalidateTimer() { timer?.invalidate() timer = nil } // Add Tap and LongPress gesture recognizers fileprivate func createGestureRecognizers() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SwiftyCamButton.Tap)) let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(SwiftyCamButton.LongPress)) self.addGestureRecognizer(tapGesture) self.addGestureRecognizer(longGesture) } }
bsd-2-clause
c7291262a8d602f5f4dcce1bc525c5d5
32.163121
166
0.688195
5.77284
false
false
false
false
BBBInc/AlzPrevent-ios
researchline/PieChartViewDataSource.swift
1
3388
// // PieChartViewDataSource.swift // researchline // // Created by jknam on 2016. 2. 8.. // Copyright © 2016년 bbb. All rights reserved. // import ResearchKit class PieChartViewDataSource: NSObject, ORKPieChartViewDataSource { var label = ["To Do", "Done"] let colors = [ UIColor(red: 217/225, green: 217/255, blue: 217/225, alpha: 1), // UIColor(red: 142/255, green: 142/255, blue: 147/255, alpha: 1), UIColor(red: 244/255, green: 190/255, blue: 74/255, alpha: 1) ] var values = [10.0, 25.0] func numberOfSegmentsInPieChartView(pieChartView: ORKPieChartView ) -> Int { return values.count } func pieChartView(pieChartView: ORKPieChartView, valueForSegmentAtIndex index: Int) -> CGFloat { return CGFloat(values[index]) } func pieChartView(pieChartView: ORKPieChartView, colorForSegmentAtIndex index: Int) -> UIColor { return colors[index] } func pieChartView(pieChartView: ORKPieChartView, titleForSegmentAtIndex index: Int) -> String { return label[index] } } class LineGraphDataSource: NSObject, ORKGraphChartViewDataSource { var name = "" var data = [] var max = CGFloat(70.0) var min = CGFloat(0) var scale = 1.0 var count = 0 var rangePoint = true func numberOfPlotsInGraphChartView(graphChartView: ORKGraphChartView) -> Int { return 1 } func graphChartView(graphChartView: ORKGraphChartView, pointForPointIndex pointIndex: Int, plotIndex: Int) -> ORKRangedPoint { var keyString = "successData" if(rangePoint == false){ keyString = "data" } let dataItem = self.data[self.count - pointIndex - 1][keyString]!! as? [String: AnyObject] if dataItem!.keys.contains(name){ if let valueNum: NSNumber = dataItem![name] as? NSNumber { debugPrint(name) debugPrint(valueNum) let doubleNum = Double(valueNum); if(rangePoint){ return ORKRangedPoint(minimumValue: 0.0, maximumValue: CGFloat(doubleNum)) } return ORKRangedPoint(value: CGFloat(doubleNum)) }else { let valueStr = dataItem![name] as! String return ORKRangedPoint(value: CGFloat(Double(valueStr)!)) } }else{ return ORKRangedPoint(value: 0.0) } } func graphChartView(graphChartView: ORKGraphChartView, numberOfPointsForPlotIndex plotIndex: Int) -> Int { return count } func maximumValueForGraphChartView(graphChartView: ORKGraphChartView) -> CGFloat { if max == 0 { return graphChartView.maximumValue } return self.max } func minimumValueForGraphChartView(graphChartView: ORKGraphChartView) -> CGFloat { return self.min } func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String? { let minusDate = self.count - pointIndex - 1 let calendar = NSCalendar.currentCalendar() let date = calendar.dateByAddingUnit(.Day, value: -minusDate, toDate: NSDate(), options: []) let components = calendar.components(.Day, fromDate: date!) return String(components.day) } }
bsd-3-clause
4ccddae869db64b8b3369781fe4579a2
33.20202
130
0.62452
4.688366
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/Siri/SiriShortcuts.swift
1
5608
/* 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 Intents import IntentsUI class SiriShortcuts { enum activityType: String { case erase = "EraseIntent" case eraseAndOpen = "org.mozilla.ios.Klar.eraseAndOpen" case openURL = "org.mozilla.ios.Klar.openUrl" } func getActivity(for type: activityType) -> NSUserActivity? { switch type { case .eraseAndOpen: return eraseAndOpenActivity case .openURL: return openUrlActivity default: return nil } } func getIntent(for type: activityType) -> INIntent? { switch type { case .erase: let intent = EraseIntent() intent.suggestedInvocationPhrase = UIConstants.strings.eraseSiri return intent default: return nil } } private var eraseAndOpenActivity: NSUserActivity = { let activity = NSUserActivity(activityType: activityType.eraseAndOpen.rawValue) activity.title = UIConstants.strings.eraseAndOpenSiri activity.userInfo = [:] activity.isEligibleForSearch = true activity.isEligibleForPrediction = true activity.suggestedInvocationPhrase = UIConstants.strings.eraseAndOpenSiri activity.persistentIdentifier = NSUserActivityPersistentIdentifier(activityType.eraseAndOpen.rawValue) return activity }() private var openUrlActivity: NSUserActivity? = { guard let url = UserDefaults.standard.value(forKey: "favoriteUrl") as? String else { return nil } let activity = NSUserActivity(activityType: activityType.openURL.rawValue) activity.title = UIConstants.strings.openUrlSiri activity.userInfo = ["url": url] activity.isEligibleForSearch = false activity.isEligibleForPrediction = true activity.suggestedInvocationPhrase = UIConstants.strings.openUrlSiri activity.persistentIdentifier = NSUserActivityPersistentIdentifier(activityType.openURL.rawValue) return activity }() func hasAddedActivity(type: SiriShortcuts.activityType, _ completion: @escaping (_ result: Bool) -> Void) { INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcuts, error) in DispatchQueue.main.async { guard let voiceShortcuts = voiceShortcuts else { return } // First, check for userActivity, which is for shortcuts that work in the foreground var foundShortcut = voiceShortcuts.filter { (attempt) in attempt.shortcut.userActivity?.activityType == type.rawValue }.first // Next, check for intent, which is used for shortcuts that work in the background if type == SiriShortcuts.activityType.erase && foundShortcut == nil { foundShortcut = voiceShortcuts.filter { (attempt) in attempt.shortcut.intent as? EraseIntent != nil }.first } completion(foundShortcut != nil) } } } func displayAddToSiri(for activityType: activityType, in viewController: UIViewController) { var shortcut: INShortcut? if let activity = SiriShortcuts().getActivity(for: activityType) { shortcut = INShortcut(userActivity: activity) } else if let intent = SiriShortcuts().getIntent(for: activityType) { shortcut = INShortcut(intent: intent) } guard let foundShortcut = shortcut else { return } let addViewController = INUIAddVoiceShortcutViewController(shortcut: foundShortcut) addViewController.modalPresentationStyle = .formSheet addViewController.delegate = viewController as? INUIAddVoiceShortcutViewControllerDelegate viewController.present(addViewController, animated: true, completion: nil) } func displayEditSiri(for shortcut: INVoiceShortcut, in viewController: UIViewController) { let editViewController = INUIEditVoiceShortcutViewController(voiceShortcut: shortcut) editViewController.modalPresentationStyle = .formSheet editViewController.delegate = viewController as? INUIEditVoiceShortcutViewControllerDelegate viewController.present(editViewController, animated: true, completion: nil) } func manageSiri(for activityType: SiriShortcuts.activityType, in viewController: UIViewController) { INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcuts, error) in DispatchQueue.main.async { guard let voiceShortcuts = voiceShortcuts else { return } var foundShortcut = voiceShortcuts.filter { (attempt) in attempt.shortcut.userActivity?.activityType == activityType.rawValue }.first if activityType == SiriShortcuts.activityType.erase && foundShortcut == nil { foundShortcut = voiceShortcuts.filter { (attempt) in attempt.shortcut.intent as? EraseIntent != nil }.first } if let foundShortcut = foundShortcut { self.displayEditSiri(for: foundShortcut, in: viewController) } else { self.displayAddToSiri(for: activityType, in: viewController) } } } } }
mpl-2.0
3ef51b28ca9380413fc86b91b3c89cd2
45.347107
111
0.654601
5.519685
false
false
false
false
machelix/DSFacebookImagePicker
Source/PhotoCell.swift
2
1030
// // PhotoCell.swift // DSFacebookImagePicker // // Created by Home on 2014-10-14. // Copyright (c) 2014 Sanche. All rights reserved. // import UIKit class PhotoCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var associatedPhoto : Photo? override func prepareForReuse() { super.prepareForReuse() if let thisPhoto = associatedPhoto{ thisPhoto.attemptImageCache() } imageView?.image = nil associatedPhoto = nil } func setUpWithPhoto(thisPhoto:Photo){ imageView?.image = nil associatedPhoto = thisPhoto thisPhoto.loadThumbnail() setImage(thisPhoto) } func setImage(photo:Photo){ if let foundPhoto = photo.thumbnailData{ imageView?.image = foundPhoto } else if !photo.imageLoadFailed { let delay = 0.1 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { () in self.setImage(photo) }) } } }
mit
09300f0bfdc59e47772c2dd14202a827
20.914894
63
0.658252
4.007782
false
false
false
false
paulofaria/SwiftHTTPServer
Libuv/Pack.swift
3
1888
// Pack.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. final class Pack<A> { let unpack: A init(_ value: A) { unpack = value } } func retainedVoidPointer<A>(x: A?) -> UnsafeMutablePointer<Void> { guard let value = x else { return UnsafeMutablePointer() } let unmanaged = Unmanaged.passRetained(Pack(value)) return UnsafeMutablePointer(unmanaged.toOpaque()) } func fromVoidPointer<A>(x: UnsafeMutablePointer<Void>) -> A? { guard x != nil else { return nil } return Unmanaged<Pack<A>>.fromOpaque(COpaquePointer(x)).takeUnretainedValue().unpack } func releaseVoidPointer<A>(x: UnsafeMutablePointer<Void>) -> A? { guard x != nil else { return nil } return Unmanaged<Pack<A>>.fromOpaque(COpaquePointer(x)).takeRetainedValue().unpack }
mit
a20ac010aaf4a913b83739dd85960ff0
32.140351
88
0.726165
4.360277
false
false
false
false
gtranchedone/AlgorithmsSwift
Algorithms.playground/Pages/Problem - Convert base.xcplaygroundpage/Contents.swift
1
2170
/*: [Previous](@previous) # Search a maze ### Given a 2D array of black and white entries representing a maze with designated entry and exit points, find a path from the entrance to the exit, if one exists. */ func findPathFrom(entrance: MazePoint, to exit: MazePoint, var inMaze maze: [[MazeSpace]]) -> Stack<MazePoint>? { guard isPoint(entrance, inMaze: maze) else { return nil } guard isPoint(exit, inMaze: maze) else { return nil } var stack = Stack<MazePoint>() dfsPoint(exit, from: entrance, inMaze: &maze, path: &stack) return stack.isEmpty ? nil : stack } func dfsPoint(target: MazePoint, from point: MazePoint, inout inMaze maze: [[MazeSpace]], inout path: Stack<MazePoint>) -> Bool { guard maze[point.x][point.y] == .Path else { return false } maze[point.x][point.y] = .VisitedPath if point == target { path.push(point) return true } let adjacentPoints = adjacentPointsTo(point, inMaze: maze) for adj in adjacentPoints { if dfsPoint(target, from: adj, inMaze: &maze, path: &path) { path.push(adj) return true } } return false } func adjacentPointsTo(point: MazePoint, inMaze maze: [[MazeSpace]]) -> [MazePoint] { var points = [MazePoint]() let up = MazePoint(x: point.x, y: point.x - 1) if isPoint(up, inMaze: maze) { points.append(up) } let down = MazePoint(x: point.x, y: point.x + 1) if isPoint(down, inMaze: maze) { points.append(down) } let left = MazePoint(x: point.x - 1, y: point.x) if isPoint(left, inMaze: maze) { points.append(left) } let right = MazePoint(x: point.x + 1, y: point.x) if isPoint(right, inMaze: maze) { points.append(right) } return points } func isPoint(point: MazePoint, inMaze maze: [[MazeSpace]]) -> Bool { guard point.x >= 0 && point.x < maze.count else { return false } return point.y >= 0 && point.y < maze[point.x].count } enum MazeSpace { case Wall case Path case VisitedPath } struct MazePoint: Equatable { let x: Int, y: Int } func ==(lhs: MazePoint, rhs: MazePoint) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } //: [Next](@next)
mit
924b52f38e44639354f8440c917c7ad0
32.890625
164
0.639926
3.194404
false
false
false
false
momo13014/RayWenderlichDemo
RayCoreConcepts_SB1/RayCoreConcepts_SB1/GamePickerViewController.swift
1
4559
// // GamePickerViewController.swift // RayCoreConcepts_SB1 // // Created by shendong on 16/9/1. // Copyright © 2016年 shendong. All rights reserved. // import UIKit class GamePickerViewController: UITableViewController { var games:[String] = [ "Angry Birds", "Chess", "Russian Roulette", "Spin the Bottle", "Texas Hold'em Poker", "Tic-Tac-Toe"] var selectedGameIndex: Int? var seletedGame: String? { didSet{ if let game = seletedGame { selectedGameIndex = games.indexOf(game)! } } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return games.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("GameCell", forIndexPath: indexPath) cell.textLabel?.text = games[indexPath.row] if indexPath.row == selectedGameIndex { cell.accessoryType = .Checkmark }else{ cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let index = selectedGameIndex{ let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) cell?.accessoryType = .None } seletedGame = games[indexPath.row] let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.accessoryType = .Checkmark } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "SaveSelectedGame" { if let cell = sender as? UITableViewCell { let indexPath = tableView.indexPathForCell(cell) if let index = indexPath?.row { seletedGame = games[index] } } } } }
mit
c3945b8f420baa67a31d6c3f6f324f7f
33.255639
157
0.652107
5.347418
false
false
false
false
aslanyanhaik/youtube-iOS
YouTube/ViewControllers/MainVC.swift
1
5607
// MIT License // Copyright (c) 2017 Haik Aslanyan // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class MainVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { //MARK: Properties @IBOutlet var tabBarView: TabBarView! @IBOutlet weak var collectionView: UICollectionView! var views = [UIView]() //MARK: Methods func customization() { self.view.backgroundColor = UIColor.rbg(r: 228, g: 34, b: 24) //CollectionView Setup self.collectionView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) self.collectionView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: (self.view.bounds.height)) //TabbarView setup self.view.addSubview(self.tabBarView) self.tabBarView.translatesAutoresizingMaskIntoConstraints = false guard let v = self.view else { return } let _ = NSLayoutConstraint.init(item: v, attribute: .top, relatedBy: .equal, toItem: self.tabBarView, attribute: .top, multiplier: 1.0, constant: 0).isActive = true let _ = NSLayoutConstraint.init(item: v, attribute: .left, relatedBy: .equal, toItem: self.tabBarView, attribute: .left, multiplier: 1.0, constant: 0).isActive = true let _ = NSLayoutConstraint.init(item: v, attribute: .right, relatedBy: .equal, toItem: self.tabBarView, attribute: .right, multiplier: 1.0, constant: 0).isActive = true self.tabBarView.heightAnchor.constraint(equalToConstant: 64).isActive = true //ViewController init let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") let trendingVC = self.storyboard?.instantiateViewController(withIdentifier: "TrendingVC") let subscriptionsVC = self.storyboard?.instantiateViewController(withIdentifier: "SubscriptionsVC") let accountVC = self.storyboard?.instantiateViewController(withIdentifier: "AccountVC") let viewControllers = [homeVC, trendingVC, subscriptionsVC, accountVC] for vc in viewControllers { self.addChild(vc!) vc!.didMove(toParent: self) vc!.view.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: (self.view.bounds.height - 44)) self.views.append(vc!.view) } self.collectionView.reloadData() //NotificationCenter setup NotificationCenter.default.addObserver(self, selector: #selector(self.scrollViews(notification:)), name: Notification.Name.init(rawValue: "didSelectMenu"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.hideBar(notification:)), name: NSNotification.Name("hide"), object: nil) } @objc func scrollViews(notification: Notification) { if let info = notification.userInfo { let userInfo = info as! [String: Int] self.collectionView.scrollToItem(at: IndexPath.init(row: userInfo["index"]!, section: 0), at: .centeredHorizontally, animated: true) } } @objc func hideBar(notification: NSNotification) { let state = notification.object as! Bool self.navigationController?.setNavigationBarHidden(state, animated: true) } //MARK: Delegates func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.views.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.contentView.addSubview(self.views[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize.init(width: self.collectionView.bounds.width, height: (self.collectionView.bounds.height + 22)) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollIndex = scrollView.contentOffset.x / self.view.bounds.width NotificationCenter.default.post(name: Notification.Name.init(rawValue: "scrollMenu"), object: nil, userInfo: ["length": scrollIndex]) } //MARK: ViewController lifecyle override func viewDidLoad() { super.viewDidLoad() self.customization() } deinit { NotificationCenter.default.removeObserver(self) } }
mit
bfc417aa7135a3c41c215ac205f8cd09
52.4
176
0.710005
4.676397
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Core/_Protocols/JSONSerializable.swift
1
2348
// // JSONSerializable.swift // APExtensions // // Created by Anton Plebanovich on 9.11.21. // Copyright © 2021 Anton Plebanovich. All rights reserved. // import RoutableLogger public protocol JSONSerializable {} public extension JSONSerializable { /// Returns `self` converted to a JSON string or reports an error and returns `nil` if unable. /// It's using keys sorting on iOS 11 or higher. func safeJSONString(file: String = #file, function: String = #function, line: UInt = #line) -> String? { if #available(iOS 11.0, *) { return safeJSONString(options: [.sortedKeys], file: file, function: function, line: line) } else { return safeJSONString(options: [], file: file, function: function, line: line) } } func safePrettyJSONString(file: String = #file, function: String = #function, line: UInt = #line) -> String? { if #available(iOS 11.0, *) { return safeJSONString(options: [.sortedKeys, .prettyPrinted], file: file, function: function, line: line) } else { return safeJSONString(options: [.prettyPrinted], file: file, function: function, line: line) } } func safeJSONString(options: JSONSerialization.WritingOptions, file: String = #file, function: String = #function, line: UInt = #line) -> String? { safeJSONData(options: options, file: file, function: function, line: line)? .safeUTF8String(file: file, function: function, line: line) } func safeJSONData(options: JSONSerialization.WritingOptions, file: String = #file, function: String = #function, line: UInt = #line) -> Data? { guard JSONSerialization.isValidJSONObject(self) else { RoutableLogger.logError("Ivalid JSON object", data: ["self": self, "options": options], file: file, function: function, line: line) return nil } do { return try JSONSerialization.data(withJSONObject: self, options: options) } catch { RoutableLogger.logError("Unable to transform object to JSON string", error: error, data: ["self": self, "options": options], file: file, function: function, line: line) return nil } } } extension Array: JSONSerializable {} extension Dictionary: JSONSerializable {}
mit
94dbf7467b6b265e1a68f07bcfafe0f3
41.672727
180
0.643375
4.386916
false
false
false
false
hejunbinlan/Carlos
Tests/Fakes/CacheLevelFake.swift
2
875
import Foundation import Carlos class CacheLevelFake<A, B>: CacheLevel { typealias KeyType = A typealias OutputType = B init() {} var numberOfTimesCalledGet = 0 var didGetKey: KeyType? var cacheRequestToReturn: CacheRequest<OutputType>? func get(key: KeyType) -> CacheRequest<OutputType> { numberOfTimesCalledGet++ didGetKey = key return cacheRequestToReturn ?? CacheRequest<OutputType>() } var numberOfTimesCalledSet = 0 var didSetValue: OutputType? var didSetKey: KeyType? func set(value: OutputType, forKey key: KeyType) { numberOfTimesCalledSet++ didSetKey = key didSetValue = value } var numberOfTimesCalledClear = 0 func clear() { numberOfTimesCalledClear++ } var numberOfTimesCalledOnMemoryWarning = 0 func onMemoryWarning() { numberOfTimesCalledOnMemoryWarning++ } }
mit
0c407c2244bef14024c82a667c40f3d8
20.9
61
0.708571
5.087209
false
false
false
false
zisko/swift
test/SILGen/pgo_foreach.swift
1
3331
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_foreach -o %t/main // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // need to move counts attached to expr for this // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=SIL // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=IR // need to check Opt support // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_foreach -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: OS=macosx // SIL-LABEL: // pgo_foreach.guessForEach1 // SIL-LABEL: sil @$S11pgo_foreach13guessForEach11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) { // IR-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF public func guessForEach1(x: Int32) -> Int32 { // SIL: switch_enum {{.*}} : $Optional<Int32>, case #Optional.some!enumelt.1: {{.*}} !case_count(798), case #Optional.none!enumelt: {{.*}} !case_count(42) var ret : Int32 = 0 for currVal in stride(from: 5, to: x, by: 5) { ret += currVal } return ret } // SIL-LABEL: // pgo_foreach.guessForEach2 // SIL-LABEL: sil @$S11pgo_foreach13guessForEach21xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) { // IR-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF public func guessForEach2(x: Int32) -> Int32 { // SIL: switch_enum {{.*}} : $Optional<(String, Int32)>, case #Optional.some!enumelt.1: {{.*}} !case_count(168), case #Optional.none!enumelt: {{.*}} !case_count(42) var ret : Int32 = 0 let names = ["John" : Int32(1), "Paul" : Int32(2), "George" : Int32(3), "Ringo" : Int32(x)] for (name, number) in names { ret += Int32(name.count) ret += number } return ret } // SIL-LABEL: // pgo_foreach.main() // IR-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$S9pgo_foreach10guessWhiles5Int32VAD1x_tF func main() { // SIL: switch_enum {{.*}} : $Optional<Int>, case #Optional.some!enumelt.1: {{.*}} !case_count(42), case #Optional.none!enumelt: {{.*}} !case_count(1) var guesses : Int32 = 0; for _ in 1...42 { guesses += guessForEach1(x: 100) guesses += guessForEach2(x: 100) } } main() // IR: !{!"branch_weights", i32 421, i32 43} // IR: !{!"branch_weights", i32 176401, i32 421} // IR-OPT: !{!"branch_weights", i32 421, i32 43} // IR-OPT: !{!"branch_weights", i32 176401, i32 421}
apache-2.0
360906e2144671bde2bd02aa2522f1ed
47.985294
186
0.68538
2.854327
false
false
false
false
edx/edx-app-ios
Source/ProfileBanner.swift
1
3737
// // ProfileBanner.swift // edX // // Created by Michael Katz on 9/28/15. // Copyright © 2015 edX. All rights reserved. // import UIKit /** Helper Class to display a Profile image and username in a row. Optional change [📷] button. */ class ProfileBanner: UIView { enum Style { case LightContent case DarkContent var textColor: UIColor { switch(self) { case .LightContent: return OEXStyles.shared().neutralWhiteT() case .DarkContent: return OEXStyles.shared().primaryBaseColor() } } } let shortProfView: ProfileImageView = ProfileImageView() let usernameLabel: UILabel = UILabel() let editable: Bool let changeCallback: (()->())? let changeButton = IconButton() var style = Style.LightContent { didSet { usernameLabel.attributedText = usernameStyle.attributedString(withText: usernameLabel.attributedText?.string) } } private func setupViews() { addSubview(shortProfView) addSubview(usernameLabel) usernameLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1), for: .horizontal) shortProfView.snp.makeConstraints { make in make.leading.equalTo(self.snp.leadingMargin) make.height.equalTo(40) make.width.equalTo(shortProfView.snp.height) make.centerY.equalTo(self) } usernameLabel.snp.makeConstraints { make in make.leading.equalTo(shortProfView.snp.trailing).offset(6) make.centerY.equalTo(shortProfView) } if editable { isUserInteractionEnabled = true addSubview(changeButton) changeButton.setIconAndTitle(icon: Icon.Camera, title: Strings.Profile.changePictureButton) changeButton.setAccessibility(with: UIAccessibilityTraits.button, hint: Strings.Profile.changePictureAccessibilityHint) changeButton.snp.makeConstraints { make in make.centerY.equalTo(shortProfView) make.trailing.equalTo(snp.trailingMargin).priority(.high) make.leading.equalTo(usernameLabel).priority(.low) } changeButton.oex_addAction({ [weak self] _ in self?.changeCallback?() }, for: .touchUpInside) } } init(editable: Bool, didChange: @escaping (()->())) { self.editable = editable changeCallback = didChange super.init(frame: CGRect.zero) setupViews() setAccessibilityIdentifiers() } override init(frame: CGRect) { editable = false changeCallback = nil super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setAccessibilityIdentifiers() { accessibilityIdentifier = "ProfileBanner:view" shortProfView.accessibilityIdentifier = "ProfileBanner:short-profile-image-view" usernameLabel.accessibilityIdentifier = "ProfileBanner:username-label" changeButton.accessibilityIdentifier = "ProfileBanner:change-button" } func showProfile(profile: UserProfile, networkManager: NetworkManager) { shortProfView.remoteImage = profile.image(networkManager: networkManager) usernameLabel.attributedText = usernameStyle.attributedString(withText: profile.username) } var usernameStyle : OEXTextStyle { return OEXTextStyle(weight : .normal, size: .large, color: style.textColor) } }
apache-2.0
ec1477cb4eb403bdfa3e1f773240f0ed
31.745614
131
0.631128
5.177531
false
false
false
false
hchhatbar/SAHC_iOS_App
SAHC/SAHC/LoginViewController.swift
1
5253
// // LoginViewController.swift // SAHC // // Created by Michael Hari on 3/24/16. // Copyright © 2016 AppForCause. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet var authCodeTxtField: UITextField! @IBOutlet var emailTxtField: UITextField! @IBOutlet var phoneNumberTxtField: UITextField! @IBAction func signInBtnPressed(sender: AnyObject) { // TODO: validate fields are validate inputs if self.authCodeTxtField.text != nil && self.emailTxtField.text != nil && self.phoneNumberTxtField.text != nil { let hud: MBProgressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.mode = MBProgressHUDMode.AnnularDeterminate hud.label.text = NSLocalizedString("Logging in...", comment: "Logging In Text for Spinner") dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), { Service.sharedInstance.authenticate(self.authCodeTxtField.text!, email: self.emailTxtField.text!, phoneNumber: self.phoneNumberTxtField.text!) { (inner: () throws -> Bool) -> Void in // dismiss spinner dispatch_async(dispatch_get_main_queue(), { hud.hideAnimated(true) }) do { let success = try inner() // get result if success { // auth success dispatch_async(dispatch_get_main_queue(), { self.performSegueWithIdentifier("LoginToLandingSegue", sender: nil) }) } else { self.displayAlert(NSLocalizedString("Authentication Failure", comment: "Server returned auth failure"), message: NSLocalizedString("Your authcode, email and/or phone number is incorrect, please try again", comment: "Generic Auth Failture Msg")) } } catch let error { switch error { case Service.AuthenticationError.AuthenticationAPINotReachable: print(NSLocalizedString("The Internet connection appears to be offline.", comment: "Internet offline")) self.displayAlert(NSLocalizedString("No Internet", comment: "No Internet"), message: NSLocalizedString("The Internet connection appears to be offline.", comment: "Internet offline")) case Service.AuthenticationError.AuthenticationCallThrewError(let error): print(error.localizedDescription) self.displayAlert(NSLocalizedString("Unknown Server Error", comment: "Server Error"), message: NSLocalizedString("Server is currently offline, please try again later.", comment: "Try again later")) case Service.AuthenticationError.AuthenticationResponseNotOK(let httpCode): print("httpCode returned from server: \(httpCode)") self.displayAlert(NSLocalizedString("Unknown Server Error", comment: "Server Error"), message: NSLocalizedString("Server is currently offline, please try again later.", comment: "Try again later")) case Service.AuthenticationError.AuthenticationResponseMalformed(let data, let error): print(error.localizedDescription) print(NSString(data: data, encoding: NSUTF8StringEncoding)) self.displayAlert(NSLocalizedString("Unknown Server Error", comment: "Server Error"), message: NSLocalizedString("Server is currently offline, please try again later.", comment: "Try again later")) case Service.AuthenticationError.AuthenticationResponseUnrecognized(let json): print(json) self.displayAlert(NSLocalizedString("Unknown Server Error", comment: "Server Error"), message: NSLocalizedString("Server is currently offline, please try again later.", comment: "Try again later")) default: break } } } }) // end dispatch_async outer } } func displayAlert(title: String, message: String) { dispatch_async(dispatch_get_main_queue(), { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Okay"), style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) }) } }
mit
d503aa3a8122f1f7039eb8a05bebf14b
56.714286
272
0.558454
6.297362
false
false
false
false
verticon/MecklenburgTrailOfHistory
Trail of History/AppDelegate.swift
1
3527
// // AppDelegate.swift // Trail of History // // Created by Robert Vaessen on 3/14/16. // Copyright © 2018 Robert Vaessen. All rights reserved. // import UIKit import CoreData import Firebase import FirebaseDatabase import VerticonsToolbox @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print("\(applicationName) started - \(LocalTime.text)") //_ = Firebase.connection.addListener(self, handlerClassMethod: AppDelegate.firebaseConnectionEventHandler) //listFonts() //printInfo() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. } func listFonts() { var list = "" for family in UIFont.familyNames { list += "\(family)\n" for font in UIFont.fontNames(forFamilyName: family) { list += "\t\(font)\n" } } print(list) } private func printInfo() { print("Stdout = \(stdout)") print("Trail of history file name = \(String(describing: tohFileName))") } private func firebaseConnectionEventHandler(event: Firebase.ConnectionEvent) { switch event { case .established: alertUser(title: applicationName, body: "A database connection has been established.") case .failed: alertUser(title: applicationName, body: "A database connection could not be established; locally cached data, if any, will be used") break case .lost: alertUser(title: applicationName, body: "The database connection has been lost.") break } } }
mit
c3b4d578a3fe536e367930326a2a273e
40
285
0.699376
5.399694
false
false
false
false
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDKTests/BSValidatorTests.swift
1
22296
// // BSValidatorTests.swift // BluesnapSDK // // Created by Shevie Chen on 20/08/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import XCTest @testable import BluesnapSDK class BSValidatorTests: XCTestCase { override func setUp() { print("----------------------------------------------------") 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 testValidateName() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: true, input: input, addressDetails: addressDetails), true) XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "") XCTAssertEqual(addressDetails.name, "") input.setValue("a") XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "A") XCTAssertEqual(addressDetails.name, "A") input.setValue("ab") XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "Ab") XCTAssertEqual(addressDetails.name, "Ab") input.setValue("ab cd") XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "Ab Cd") XCTAssertEqual(addressDetails.name, "Ab Cd") input.setValue(" ab cd ") XCTAssertEqual(BSValidator.validateName(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "Ab Cd") XCTAssertEqual(addressDetails.name, "Ab Cd") } func testValidateEmail() { let input = BSInputLine() let addressDetails = BSBillingAddressDetails() XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: true, input: input, addressDetails: addressDetails), true) XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "") XCTAssertEqual(addressDetails.email, "") input.setValue("aaa") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "aaa") XCTAssertEqual(addressDetails.email, "aaa") input.setValue("aaa.bbb") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "aaa.bbb") XCTAssertEqual(addressDetails.email, "aaa.bbb") input.setValue("aaa@bbb") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "aaa@bbb") XCTAssertEqual(addressDetails.email, "aaa@bbb") input.setValue("[email protected]") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "[email protected]") XCTAssertEqual(addressDetails.email, "[email protected]") input.setValue("[email protected]") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "[email protected]") XCTAssertEqual(addressDetails.email, "[email protected]") input.setValue(" [email protected] ") XCTAssertEqual(BSValidator.validateEmail(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "[email protected]") XCTAssertEqual(addressDetails.email, "[email protected]") } func testValidateStreet() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() XCTAssertEqual(BSValidator.validateStreet(ignoreIfEmpty: true, input: input, addressDetails: addressDetails), true) XCTAssertEqual(BSValidator.validateStreet(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "") XCTAssertEqual(addressDetails.address, "") input.setValue("12") XCTAssertEqual(BSValidator.validateStreet(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "12") XCTAssertEqual(addressDetails.address, "12") input.setValue("12 Cdf") XCTAssertEqual(BSValidator.validateStreet(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.address, "12 Cdf") input.setValue(" 12 Cdf ") XCTAssertEqual(BSValidator.validateStreet(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.address, "12 Cdf") } func testValidateCity() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() XCTAssertEqual(BSValidator.validateCity(ignoreIfEmpty: true, input: input, addressDetails: addressDetails), true) XCTAssertEqual(BSValidator.validateCity(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "") XCTAssertEqual(addressDetails.city, "") input.setValue("12") XCTAssertEqual(BSValidator.validateCity(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "12") XCTAssertEqual(addressDetails.city, "12") input.setValue("12 Cdf") XCTAssertEqual(BSValidator.validateCity(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.city, "12 Cdf") input.setValue(" 12 Cdf ") XCTAssertEqual(BSValidator.validateCity(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.city, "12 Cdf") } func testValidateCountry() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() var result: Bool addressDetails.country = nil result = BSValidator.validateCountry(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "" result = BSValidator.validateCountry(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = nil result = BSValidator.validateCountry(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "" result = BSValidator.validateCountry(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "12" result = BSValidator.validateCountry(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "12 Cdf" result = BSValidator.validateCountry(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "us" result = BSValidator.validateCountry(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "US" result = BSValidator.validateCountry(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) } func testValidateZip() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() XCTAssertEqual(BSValidator.validateZip(ignoreIfEmpty: true, input: input, addressDetails: addressDetails), true) XCTAssertEqual(BSValidator.validateZip(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "") XCTAssertEqual(addressDetails.zip, "") input.setValue("12") XCTAssertEqual(BSValidator.validateZip(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), false) XCTAssertEqual(input.getValue(), "12") XCTAssertEqual(addressDetails.zip, "12") input.setValue("12 Cdf") XCTAssertEqual(BSValidator.validateZip(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.zip, "12 Cdf") input.setValue(" 12 Cdf ") XCTAssertEqual(BSValidator.validateZip(ignoreIfEmpty: false, input: input, addressDetails: addressDetails), true) XCTAssertEqual(input.getValue(), "12 Cdf") XCTAssertEqual(addressDetails.zip, "12 Cdf") } func testValidateState() { let input = BSInputLine() let addressDetails = BSBaseAddressDetails() var result: Bool addressDetails.state = nil result = BSValidator.validateState(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.state = "" result = BSValidator.validateState(ignoreIfEmpty: true, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "US" addressDetails.state = nil result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "IL" addressDetails.state = nil result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "US" addressDetails.state = "" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "IL" addressDetails.state = "" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "US" addressDetails.state = "12" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "IL" addressDetails.state = "12" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "US" addressDetails.state = "12 Cdf" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, false) addressDetails.country = "US" addressDetails.state = "AL" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) addressDetails.country = "AR" addressDetails.state = "" result = BSValidator.validateState(ignoreIfEmpty: false, input: input, addressDetails: addressDetails) XCTAssertEqual(result, true) } func testValidateExp() { let input = BSCcInputLine() XCTAssertEqual(BSValidator.validateExp(input: input), false, "1 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "1 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expInvalidMessage, "1 message") input.expTextField.text = "12" XCTAssertEqual(BSValidator.validateExp(input: input), false, "2 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "2 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expInvalidMessage, "2 message") input.expTextField.text = "1220" XCTAssertEqual(BSValidator.validateExp(input: input), false, "3 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "3 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expInvalidMessage, "3 message") input.expTextField.text = "12/26" XCTAssertEqual(BSValidator.validateExp(input: input), true, "4 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, true, "4 isHidden") input.expTextField.text = "14/26" XCTAssertEqual(BSValidator.validateExp(input: input), false, "5 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "5 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expMonthInvalidMessage, "5 message") input.expTextField.text = "11/11" XCTAssertEqual(BSValidator.validateExp(input: input), false, "6 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "6 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expPastInvalidMessage, "6 message") input.expTextField.text = "12/80" XCTAssertEqual(BSValidator.validateExp(input: input), false, "7 validateExp") XCTAssertEqual(input.expErrorLabel?.isHidden, false, "7 isHidden") XCTAssertEqual(input.expErrorLabel?.text, BSValidator.expInvalidMessage, "7 message") } func testValidateCvv() { let input = BSCcInputLine() XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "visa"), false) XCTAssertEqual(input.cvvErrorLabel?.isHidden, false) XCTAssertEqual(input.cvvErrorLabel?.text, BSValidator.cvvInvalidMessage) input.cvvTextField.text = "14" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "visa"), false) XCTAssertEqual(input.cvvErrorLabel?.isHidden, false) XCTAssertEqual(input.cvvErrorLabel?.text, BSValidator.cvvInvalidMessage) input.cvvTextField.text = "143" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "visa"), true) XCTAssertEqual(input.cvvErrorLabel?.isHidden, true) input.cvvTextField.text = "143" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "VISA"), true) XCTAssertEqual(input.cvvErrorLabel?.isHidden, true) input.cvvTextField.text = "143" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "amex"), false) XCTAssertEqual(input.cvvErrorLabel?.isHidden, false) XCTAssertEqual(input.cvvErrorLabel?.text, BSValidator.cvvInvalidMessage) input.cvvTextField.text = "143" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "AMEX"), false) XCTAssertEqual(input.cvvErrorLabel?.isHidden, false) XCTAssertEqual(input.cvvErrorLabel?.text, BSValidator.cvvInvalidMessage) input.cvvTextField.text = "1434" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "amex"), true) XCTAssertEqual(input.cvvErrorLabel?.isHidden, true) input.cvvTextField.text = "1434" XCTAssertEqual(BSValidator.validateCvv(input: input, cardType: "AMEX"), true) XCTAssertEqual(input.cvvErrorLabel?.isHidden, true) } func testvalidateCCN() { let input = BSCcInputLine() XCTAssertEqual(BSValidator.validateCCN(input: input), false) XCTAssertEqual(input.errorLabel?.isHidden, false) XCTAssertEqual(input.errorLabel?.text, BSValidator.ccnInvalidMessage) input.setValue("4111 1111 1111 1111") XCTAssertEqual(BSValidator.validateCCN(input: input), true) XCTAssertEqual(input.errorLabel?.isHidden, true) input.setValue("4111 1111 1111") XCTAssertEqual(BSValidator.validateCCN(input: input), false) XCTAssertEqual(input.errorLabel?.isHidden, false) XCTAssertEqual(input.errorLabel?.text, BSValidator.ccnInvalidMessage) } func testNameEditingChanged() { let input = BSInputLine() BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "") input.setValue("a") BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "A") input.setValue("ab") BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "Ab") input.setValue("ab c") BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "Ab C") input.setValue("a9") BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "A") input.setValue("aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee yyy") BSValidator.nameEditingChanged(input) XCTAssertEqual(input.getValue(), "Aaaa Aaaa Bbbb Bbbb Cccc Cccc Dddd Dddd Eeee Eeee Aaaa Aaaa Bbbb Bbbb Cccc Cccc Dddd Dddd Eeee Eeee ") } // func testPhoneEditingChanged() { // // let input = BSInputLine() // BSValidator.phoneEditingChanged(input) // XCTAssertEqual(input.getValue(), "") // // input.setValue("1") // BSValidator.phoneEditingChanged(input) // XCTAssertEqual(input.getValue(), "1") // // input.setValue("123456789 123456789 123456789 555") // BSValidator.phoneEditingChanged(input) // XCTAssertEqual(input.getValue(), "123456789 123456789 123456789 ") // } func testEmailEditingChanged() { let input = BSInputLine() BSValidator.emailEditingChanged(input) XCTAssertEqual(input.getValue(), "") input.setValue("a") BSValidator.emailEditingChanged(input) XCTAssertEqual(input.getValue(), "a") input.setValue("ab-7/") BSValidator.emailEditingChanged(input) XCTAssertEqual(input.getValue(), "ab-7") input.setValue("ab c") BSValidator.emailEditingChanged(input) XCTAssertEqual(input.getValue(), "abc") input.setValue("aaaa-aaaa-bbbb-bbbb-cccc-cccc-dddd-dddd-eeee-eeee-ffff-ffff-aaaa-aaaa-bbbb-bbbb-cccc-cccc-dddd-dddd-eeee-eeee-ffff-ffff-yyy") BSValidator.emailEditingChanged(input) XCTAssertEqual(input.getValue(), "aaaa-aaaa-bbbb-bbbb-cccc-cccc-dddd-dddd-eeee-eeee-ffff-ffff-aaaa-aaaa-bbbb-bbbb-cccc-cccc-dddd-dddd-eeee-eeee-ffff-ffff-") } func testAddressEditingChanged() { let input = BSInputLine() BSValidator.addressEditingChanged(input) XCTAssertEqual(input.getValue(), "") input.setValue("a") BSValidator.addressEditingChanged(input) XCTAssertEqual(input.getValue(), "a") input.setValue("ab 90210") BSValidator.addressEditingChanged(input) XCTAssertEqual(input.getValue(), "ab 90210") input.setValue("aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee yyy") BSValidator.addressEditingChanged(input) XCTAssertEqual(input.getValue(), "aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee ") } func testCityEditingChanged() { let input = BSInputLine() BSValidator.cityEditingChanged(input) XCTAssertEqual(input.getValue(), "") input.setValue("a") BSValidator.cityEditingChanged(input) XCTAssertEqual(input.getValue(), "a") input.setValue("ab 90210/") BSValidator.cityEditingChanged(input) XCTAssertEqual(input.getValue(), "ab ") input.setValue("aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee yyy") BSValidator.cityEditingChanged(input) XCTAssertEqual(input.getValue(), "aaaa aaaa bbbb bbbb cccc cccc dddd dddd eeee eeee ") } func testZipEditingChanged() { let input = BSInputLine() BSValidator.zipEditingChanged(input) XCTAssertEqual(input.getValue(), "") input.setValue("a") BSValidator.zipEditingChanged(input) XCTAssertEqual(input.getValue(), "a") input.setValue("ab 90210/") BSValidator.zipEditingChanged(input) XCTAssertEqual(input.getValue(), "ab 90210/") input.setValue("aaaa aaaa bbbb bbbb yyy") BSValidator.zipEditingChanged(input) XCTAssertEqual(input.getValue(), "aaaa aaaa bbbb bbbb ") } func testCcnEditingChanged() { let input = BSCcInputLine() BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "") input.setValue("4111") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "4111") input.setValue("4111 abcd") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "4111") input.setValue("41112222") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "4111 2222") input.setValue("4111 555") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "4111 555") input.setValue("4111 55556666.777") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "4111 5555 6666 777") input.setValue("1111 2222 3333 4444 5555 6666") BSValidator.ccnEditingChanged(input.textField) XCTAssertEqual(input.getValue(), "1111 2222 3333 444455556") } }
mit
57619c0cfad89a7eb9304bbf8aa73410
41.305503
164
0.688989
4.678909
false
true
false
false
OscarSwanros/swift
test/SILGen/witness_tables.swift
2
41058
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil // RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil // RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil // RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil // RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil import witness_tables_b struct Arg {} @objc class ObjCClass {} infix operator <~> {} protocol AssocReqt { func requiredMethod() } protocol ArchetypeReqt { func requiredMethod() } protocol AnyProtocol { associatedtype AssocType associatedtype AssocWithReqt: AssocReqt func method(x x: Arg, y: Self) func generic<A: ArchetypeReqt>(x x: A, y: Self) func assocTypesMethod(x x: AssocType, y: AssocWithReqt) static func staticMethod(x x: Self) func <~>(x: Self, y: Self) } protocol ClassProtocol : class { associatedtype AssocType associatedtype AssocWithReqt: AssocReqt func method(x x: Arg, y: Self) func generic<B: ArchetypeReqt>(x x: B, y: Self) func assocTypesMethod(x x: AssocType, y: AssocWithReqt) static func staticMethod(x x: Self) func <~>(x: Self, y: Self) } @objc protocol ObjCProtocol { func method(x x: ObjCClass) static func staticMethod(y y: ObjCClass) } class SomeAssoc {} struct ConformingAssoc : AssocReqt { func requiredMethod() {} } // TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables { // TABLE-TESTABLE-LABEL: sil_witness_table [serialized] ConformingAssoc: AssocReqt module witness_tables { // TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: {{.*}} : @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-ALL-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> () struct ConformingStruct : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingStruct) {} func generic<D: ArchetypeReqt>(x x: D, y: ConformingStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformingStruct) {} } func <~>(x: ConformingStruct, y: ConformingStruct) {} // TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW {{.*}}: ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () protocol AddressOnly {} struct ConformingAddressOnlyStruct : AnyProtocol { var p: AddressOnly // force address-only layout with a protocol-type field typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingAddressOnlyStruct) {} func generic<E: ArchetypeReqt>(x x: E, y: ConformingAddressOnlyStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformingAddressOnlyStruct) {} } func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {} // TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> () class ConformingClass : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingClass) {} func generic<F: ArchetypeReqt>(x x: F, y: ConformingClass) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ConformingClass) {} } func <~>(x: ConformingClass, y: ConformingClass) {} // TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingClass, @in_guaranteed ConformingClass) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingClass, @thick ConformingClass.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> () struct ConformsByExtension {} extension ConformsByExtension : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformsByExtension) {} func generic<G: ArchetypeReqt>(x x: G, y: ConformsByExtension) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformsByExtension) {} } func <~>(x: ConformsByExtension, y: ConformsByExtension) {} // TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> () extension OtherModuleStruct : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: OtherModuleStruct) {} func generic<H: ArchetypeReqt>(x x: H, y: OtherModuleStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: OtherModuleStruct) {} } func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {} // TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> () protocol OtherProtocol {} struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method<I, J>(x x: I, y: J) {} func generic<K, L>(x x: K, y: L) {} func assocTypesMethod<M, N>(x x: M, y: N) {} static func staticMethod<O>(x x: O) {} } func <~> <P: OtherProtocol>(x: P, y: P) {} // TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> () class ConformingClassToClassProtocol : ClassProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingClassToClassProtocol) {} func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingClassToClassProtocol) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ConformingClassToClassProtocol) {} } func <~>(x: ConformingClassToClassProtocol, y: ConformingClassToClassProtocol) {} // TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #ClassProtocol.method!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #ClassProtocol.generic!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #ClassProtocol.staticMethod!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #ClassProtocol."<~>"!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> () class ConformingClassToObjCProtocol : ObjCProtocol { @objc func method(x x: ObjCClass) {} @objc class func staticMethod(y y: ObjCClass) {} } // TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol struct ConformingGeneric<R: AssocReqt> : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = R func method(x x: Arg, y: ConformingGeneric) {} func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingGeneric) {} func assocTypesMethod(x x: SomeAssoc, y: R) {} static func staticMethod(x x: ConformingGeneric) {} } func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {} // TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: R // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP16assocTypesMetho{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } protocol AnotherProtocol {} struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt> : AnyProtocol, AnotherProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = S func method<T, U>(x x: T, y: U) {} func generic<V, W>(x x: V, y: W) {} func assocTypesMethod<X, Y>(x x: X, y: Y) {} static func staticMethod<Z>(x x: Z) {} } func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {} // TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: S // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP7{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } protocol InheritedProtocol1 : AnyProtocol { func inheritedMethod() } protocol InheritedProtocol2 : AnyProtocol { func inheritedMethod() } protocol InheritedClassProtocol : class, AnyProtocol { func inheritedMethod() } struct InheritedConformance : InheritedProtocol1 { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: InheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: InheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: InheritedConformance) {} func inheritedMethod() {} } func <~>(x: InheritedConformance, y: InheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA0C9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: RedundantInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: RedundantInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: RedundantInheritedConformance) {} func inheritedMethod() {} } func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: DiamondInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: DiamondInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: DiamondInheritedConformance) {} func inheritedMethod() {} } func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol2A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } class ClassInheritedConformance : InheritedClassProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ClassInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: ClassInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ClassInheritedConformance) {} func inheritedMethod() {} } func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW // TABLE-NEXT: } // -- Witnesses have the 'self' abstraction level of their protocol. // AnyProtocol has no class bound, so its witnesses treat Self as opaque. // InheritedClassProtocol has a class bound, so its witnesses treat Self as // a reference value. // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@guaranteed ClassInheritedConformance) -> () // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> () struct GenericAssocType<T> : AssocReqt { func requiredMethod() {} } protocol AssocTypeWithReqt { associatedtype AssocType : AssocReqt } struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt { typealias AssocType = CC } // TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables { // TABLE-NEXT: associated_type AssocType: CC // TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent // TABLE-NEXT: } struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt { typealias AssocType = GenericAssocType<DD> } // TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables { // TABLE-NEXT: associated_type AssocType: GenericAssocType<DD> // TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): GenericAssocType<DD>: specialize <DD> (<T> GenericAssocType<T>: AssocReqt module witness_tables) // TABLE-NEXT: } protocol InheritedFromObjC : ObjCProtocol { func inheritedMethod() } class ConformsInheritedFromObjC : InheritedFromObjC { @objc func method(x x: ObjCClass) {} @objc class func staticMethod(y y: ObjCClass) {} func inheritedMethod() {} } // TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables { // TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: {{.*}} : @_T014witness_tables25ConformsInheritedFromObjCCAA0deF1CA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW // TABLE-NEXT: } protocol ObjCAssoc { associatedtype AssocType : ObjCProtocol } struct HasObjCAssoc : ObjCAssoc { typealias AssocType = ConformsInheritedFromObjC } // TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables { // TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC // TABLE-NEXT: } protocol Initializer { init(arg: Arg) } // TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct struct HasInitializerStruct : Initializer { init(arg: Arg) { } } // TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass class HasInitializerClass : Initializer { required init(arg: Arg) { } } // TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW // TABLE-NEXT: } // SYMBOL: sil private [transparent] [thunk] @_T014witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum enum HasInitializerEnum : Initializer { case A init(arg: Arg) { self = .A } }
apache-2.0
99db99e161ddd4e834a82278418b48ef
73.610909
325
0.757579
3.62669
false
false
false
false
dche/FlatUtil
Sources/Promise.swift
1
5105
// // FlatUtil - Promise.swift // // A very simple Promise constuct based on Future. // // Copyright (c) 2017 The FlatUtil authors. // Licensed under MIT License. import Dispatch /// An implementation of the popular Promise API. The implementation is /// based on the `Future`, which is a concept equivalent to `Promise`. /// /// - seealso: (Promise documentation on MDN) /// [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise] public struct Promise<T> { fileprivate let f: Future<T> /// Creates a `Promise` from a `Future`. public init(_ future: Future<T>) { self.f = future } /// Creates a `Promise` with an operation that computes a value. /// The computation is executed on given dispatch queue. /// /// - parameters: /// - dispatchQueue: The dispatch queue where the value if computed. /// - operation: The computation that returns the fulfilled value. public init( dispatchQueue q: DispatchQueue? = nil, operation o: @escaping () -> Result<T> ) { self.f = Future(dispatchQueue: q, operation: o) } /// Returns a `Promise` that is fulfilled with the given value. /// /// - parameters: /// - val: The fulfilled value. public static func resolve(_ val: T) -> Promise<T> { return Promise(Future(value: val)) } /// Returns a `Promise` that is rejected with the given reason. public static func reject(_ reason: Error) -> Promise<T> { return Promise(Future(error: reason)) } /// Returns a `Promise` that is settled with a value that is derived /// from the fulfilled value of the receiver. public func then<S>(_ operation: @escaping (T) -> S) -> Promise<S> { return Promise<S>(self.f.map { Result.value(operation($0)) }) } /// `FlatMap` version of `then`. public func then<S>(_ operation: @escaping (T) -> Promise<S>) -> Promise<S> { return Promise<S>(self.f.andThen { operation($0).f }) } /// Returns a `Promise` that is settled with the fulfilled value of the /// receiver, or a value derived from the error public func `catch`(_ handler: @escaping (Error) -> T?) -> Promise<T> { return Promise(self.f.fallback { // Called if only self.f's result IS an error. let err = self.f.result().error! guard let v = handler(err) else { return Future(error: err) } return Future(value: v) }) } /// `FlatMap` version of `fallback`. public func `catch`(_ handler: @escaping (Error) -> Promise<T>?) -> Promise<T> { return Promise(self.f.fallback { let err = self.f.result().error! guard let p = handler(err) else { return Future(error: err) } return p.f }) } /// Blocks the caller and returns the fufilled value of the receiver. /// Returns `nil` if the receiver is rejected. public func await() -> T? { return self.f.result().value } } extension Promise { /// Returns a `Promise` that is fulfilled with an `Array` of fulfilled /// values of given promises. public static func all<S, T>(_ promises: S) -> Promise<[T]> where S: Sequence, S.Iterator.Element == Promise<T> { var res = Promise<[T]>.resolve([]) guard promises.underestimatedCount > 0 else { return res } // TODO: Use `dispatch_barrier_sync` instead? promises.forEach({ p in let future: Future<[T]> = res.f.join(p.f) { (ary, v) in var ar = ary ar.append(v) return Future(value: ar) } res = Promise<[T]>(future) }) return res } /// Returns a `Promise` that is settled with the fulfilled value or /// rejection error of the first settled `Promise` of given sequence of /// `Promise`s. /// /// - note: Settlements of `Promise`s can not be cancelled. So if /// a `Promise` has side effects, the effects will happen even if the /// `Promise` is not the first settled one. public static func race<S, T>(_ promises: S) -> Promise<T> where S: Sequence, S.Iterator.Element == Promise<T> { return Promise<T> { let lck = SpinLock() let rsc = DispatchSemaphore(value: 0) var val: Result<T>? = nil for p in promises { guard val == nil else { break } let _ = p.then { Result<T>.value($0) }.catch { Result<T>.error($0) }.then { (v: Result<T>) -> Result<T> in lck.lock() defer { lck.unlock() } if val == nil { val = v rsc.signal() } return v } } rsc.wait() return val! } } }
mit
c8446ffbc7f3b4f381edc747fd4e8cc0
32.149351
93
0.544564
4.191297
false
false
false
false
rexmas/Crust
Pods/RealmSwift/RealmSwift/Util.swift
2
5844
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 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 Foundation import Realm #if BUILDING_REALM_SWIFT_TESTS import RealmSwift #endif // MARK: Internal Helpers // Swift 3.1 provides fixits for some of our uses of unsafeBitCast // to use unsafeDowncast instead, but the bitcast is required. internal func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return unsafeBitCast(x, to: type) } /// Given a list of `Any`-typed varargs, unwrap any optionals and /// replace them with the underlying value or NSNull. internal func unwrapOptionals(in varargs: [Any]) -> [Any] { return varargs.map { arg in if let someArg = arg as Any? { return someArg } return NSNull() } } internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) -> Never { NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise() fatalError() // unreachable } internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { let regex = try? NSRegularExpression(pattern: pattern, options: []) return regex?.stringByReplacingMatches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } internal func cast<U, V>(_ value: U, to: V.Type) -> V { if let v = value as? V { return v } return unsafeBitCast(value, to: to) } extension Object { // Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject` // but actually operate on `RLMObjectBase`. Do not expose cast value to user. internal func unsafeCastToRLMObject() -> RLMObject { return unsafeBitCast(self, to: RLMObject.self) } } // MARK: CustomObjectiveCBridgeable /// :nodoc: public func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T { if T.self == DynamicObject.self { return unsafeBitCast(x as AnyObject, to: T.self) } else if let bridgeableType = T.self as? CustomObjectiveCBridgeable.Type { return bridgeableType.bridging(objCValue: x) as! T } else if let bridgeableType = T.self as? RealmEnum.Type { return bridgeableType._rlmFromRawValue(x) as! T } else { return x as! T } } /// :nodoc: public func dynamicBridgeCast<T>(fromSwift x: T) -> Any { if let x = x as? CustomObjectiveCBridgeable { return x.objCValue } else if let bridgeableType = T.self as? RealmEnum.Type { return bridgeableType._rlmToRawValue(x) } else { return x } } // Used for conversion from Objective-C types to Swift types internal protocol CustomObjectiveCBridgeable { static func bridging(objCValue: Any) -> Self var objCValue: Any { get } } // FIXME: needed with swift 3.2 // Double isn't though? extension Float: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Float { return (objCValue as! NSNumber).floatValue } internal var objCValue: Any { return NSNumber(value: self) } } extension Int8: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int8 { return (objCValue as! NSNumber).int8Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int16: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int16 { return (objCValue as! NSNumber).int16Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int32: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int32 { return (objCValue as! NSNumber).int32Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Int64: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Int64 { return (objCValue as! NSNumber).int64Value } internal var objCValue: Any { return NSNumber(value: self) } } extension Optional: CustomObjectiveCBridgeable { internal static func bridging(objCValue: Any) -> Optional { if objCValue is NSNull { return nil } else { return .some(dynamicBridgeCast(fromObjectiveC: objCValue)) } } internal var objCValue: Any { if let value = self { return dynamicBridgeCast(fromSwift: value) } else { return NSNull() } } } // MARK: AssistedObjectiveCBridgeable internal protocol AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self var bridged: (objectiveCValue: Any, metadata: Any?) { get } }
mit
a92ca119bc1a4e6965b7ed029a14420d
31.10989
111
0.65024
4.348214
false
false
false
false
hooman/swift
test/Generics/unify_superclass_types_1.swift
1
985
// RUN: %target-typecheck-verify-swift -requirement-machine=verify -dump-requirement-machine 2>&1 | %FileCheck %s class Base {} class Derived : Base { func derivedMethod() {} } protocol P : Base {} func takesDerived(_: Derived) {} extension P where Self : Derived { func passesDerived() { derivedMethod() } } // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : Derived, τ_0_0 : P> // CHECK-NEXT: Rewrite system: { // CHECK-NEXT: - [P].[superclass: Base] => [P] // CHECK-NEXT: - [P].[layout: _NativeClass] => [P] // CHECK-NEXT: - τ_0_0.[superclass: Derived] => τ_0_0 // CHECK-NEXT: - τ_0_0.[layout: _NativeClass] => τ_0_0 // CHECK-NEXT: - τ_0_0.[P] => τ_0_0 // CHECK-NEXT: - τ_0_0.[superclass: Base] => τ_0_0 // CHECK-NEXT: } // CHECK-NEXT: Property map: { // CHECK-NEXT: [P] => { layout: _NativeClass superclass: [superclass: Base] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P] layout: _NativeClass superclass: [superclass: Derived] } // CHECK-NEXT: }
apache-2.0
9977ecf4172c1d8c5022a2ee6a018535
33.75
113
0.631038
2.861765
false
false
false
false
jeffreybergier/WaterMe2
WaterMe/WaterMe/Categories/NSUserActivity+WaterMe.swift
1
5142
// // NSUserActivity+WaterMe.swift // WaterMe // // Created by Jeffrey Bergier on 9/23/18. // Copyright © 2018 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe 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. // // WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>. // import Datum import Intents import CoreSpotlight import MobileCoreServices typealias NSUserActivityContinuedHandler = ([UIUserActivityRestoring]?) -> Void typealias UserActivityResult = Result<UserActivityToContinue, UserActivityToFail> struct UserActivityToContinue { var activity: RestoredUserActivity var completion: NSUserActivityContinuedHandler } struct UserActivityToFail: Error { var error: UserActivityError var completion: NSUserActivityContinuedHandler? } extension NSUserActivity { fileprivate static let stringSeparator = "::" public static func uniqueString(for rawActivity: RawUserActivity, and uuids: [Identifier]) -> String { let uuids = uuids.sorted(by: { $0.uuid <= $1.uuid }) return uuids.reduce(rawActivity.rawValue) { prevValue, item -> String in return prevValue + stringSeparator + item.uuid } } public static func deuniqueString(fromRawString rawString: String) -> (String, [String])? { let components = rawString.components(separatedBy: self.stringSeparator) let _first = components.first let rest = components.dropFirst() guard let first = _first else { return nil } return (first, Array(rest)) } public var restoredUserActivityResult: Result<RestoredUserActivity, UserActivityError> { guard let rawString = self.userInfo?[CSSearchableItemActivityIdentifier] as? String, let (rawValue, uuids) = type(of: self).deuniqueString(fromRawString: rawString), let uuid = uuids.first, let kind = RawUserActivity(rawValue: rawValue) else { return .failure(.restorationFailed) } switch kind { case .editReminder: return .success(.editReminder(.init(rawValue: uuid))) case .editReminderVessel: return .success(.editReminderVessel(.init(rawValue: uuid))) case .viewReminder: return .success(.viewReminder(.init(rawValue: uuid))) case .performReminder: return .success(.performReminder(.init(rawValue: uuid))) case .indexedItem: assertionFailure("Unimplmented") return .failure(.restorationFailed) } } public var waterme_isEligibleForNeededServices: Bool { get { if #available(iOS 12.0, *) { return self.isEligibleForSearch && self.isEligibleForHandoff && self.isEligibleForPrediction } else { return self.isEligibleForSearch && self.isEligibleForHandoff } } set { self.isEligibleForSearch = newValue self.isEligibleForHandoff = newValue if #available(iOS 12.0, *) { self.isEligibleForPrediction = newValue } } } public convenience init(kind: RawUserActivity, delegate: NSUserActivityDelegate) { self.init(activityType: kind.rawValue) self.delegate = delegate self.waterme_isEligibleForNeededServices = true } public func update(uuid: Identifier, title: String, phrase: String, description: String, thumbnailData: Data?) { guard let kind = RawUserActivity(rawValue: self.activityType) else { assertionFailure() return } let persistentIdentifier = type(of: self).uniqueString(for: kind, and: [uuid]) self.title = title if #available(iOS 12.0, *) { self.suggestedInvocationPhrase = phrase self.persistentIdentifier = persistentIdentifier } self.addUserInfoEntries(from: [CSSearchableItemActivityIdentifier: persistentIdentifier]) self.requiredUserInfoKeys = [CSSearchableItemActivityIdentifier] let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeContent as String) attributes.relatedUniqueIdentifier = persistentIdentifier attributes.contentDescription = description attributes.thumbnailData = thumbnailData self.contentAttributeSet = attributes } }
gpl-3.0
87ab7bfc3c1dfcee1e72f6ea014678e1
36.253623
97
0.650846
4.929051
false
false
false
false
Ben21hao/edx-app-ios-new
Source/UserProfile.swift
1
7307
// // Profile.swift // edX // // Created by Michael Katz on 9/24/15. // Copyright © 2015 edX. All rights reserved. // import Foundation import edXCore public class UserProfile { public enum ProfilePrivacy: String { case Private = "private" case Public = "all_users" } enum ProfileFields: String, RawStringExtractable { case Image = "profile_image" case HasImage = "has_image" case ImageURL = "image_url_full" case Username = "username" case LanguagePreferences = "language_proficiencies" case Country = "country" case Bio = "bio" case YearOfBirth = "year_of_birth" case ParentalConsent = "requires_parental_consent" case AccountPrivacy = "account_privacy" case Name = "name" //用户名 case Education = "level_of_education"//学历 case Nickname = "nickname"//昵称 case Remainscore = "remainscore" //宝典 case phone = "mobile"//手机号码 case email = "email"//邮箱 case coupon = "can_use_coupon_num"//优惠券 case order = "wait_order_num"//未支付订单 case vertify = "verify_status" //认证信息 case code = "code" case companyDic = "company"//公司dic case logoUrl = "logo"//公司logo } let hasProfileImage: Bool let imageURL: String? let username: String? var preferredLanguages: [NSDictionary]? var countryCode: String? var bio: String? var birthYear: Int? let parentalConsent: Bool? var accountPrivacy: ProfilePrivacy? var hasUpdates: Bool { return updateDictionary.count > 0 } var updateDictionary = [String: AnyObject]() let statusCode : Int? //状态码 400 未认证,200 提交成功 ,201 已认证,202 认证失败 let name : String? var educationCode : String? var nickname: String?//昵称 var remainscore: Double?//宝典 var phone : String?//手机号 var email : String?//邮箱 var coupon : Double? //优惠券 var order : Double?//未支付订单 let logoUrl: String?//公司logo public init?(json: JSON) { let profileImage = json[ProfileFields.Image] if let hasImage = profileImage[ProfileFields.HasImage].bool where hasImage { hasProfileImage = true imageURL = profileImage[ProfileFields.ImageURL].string } else { hasProfileImage = false imageURL = nil } username = json[ProfileFields.Username].string preferredLanguages = json[ProfileFields.LanguagePreferences].arrayObject as? [NSDictionary] countryCode = json[ProfileFields.Country].string bio = json[ProfileFields.Bio].string birthYear = json[ProfileFields.YearOfBirth].int parentalConsent = json[ProfileFields.ParentalConsent].bool accountPrivacy = ProfilePrivacy(rawValue: json[ProfileFields.AccountPrivacy].string ?? "") let companyDic = json[ProfileFields.companyDic] logoUrl = companyDic[ProfileFields.logoUrl].string let profileStatus = json[ProfileFields.vertify] statusCode = profileStatus[ProfileFields.code].int phone = json[ProfileFields.phone].string //手机号 email = json[ProfileFields.email].string//邮箱 name = json[ProfileFields.Name].string//用户名 nickname = json[ProfileFields.Nickname].string//昵称 coupon = json[ProfileFields.coupon].double//优惠券 order = json[ProfileFields.order].double//未支付订单 remainscore = json[ProfileFields.Remainscore].double educationCode = json[ProfileFields.Education].string print("json-----\(json)") } internal init(username : String, bio : String? = nil, parentalConsent : Bool? = false, countryCode : String? = nil, accountPrivacy : ProfilePrivacy? = nil,name : String, education : String? = nil,nickname : String,remainscore : Double,phone : String,email : String,coupon : Double,order : Double) { self.accountPrivacy = accountPrivacy self.username = username self.hasProfileImage = false self.imageURL = nil self.parentalConsent = parentalConsent self.bio = bio self.countryCode = countryCode self.name = name self.statusCode = nil self.educationCode = education self.nickname = nickname self.remainscore = remainscore self.phone = phone self.email = email self.coupon = coupon self.order = order self.logoUrl = nil } var languageCode: String? { get { guard let languages = preferredLanguages where languages.count > 0 else { return nil } return languages[0]["code"] as? String } set { guard let code = newValue else { preferredLanguages = []; return } guard preferredLanguages != nil && preferredLanguages!.count > 0 else { preferredLanguages = [["code": code]] return } preferredLanguages!.replaceRange(0...0, with: [["code": code]]) } } } extension UserProfile { //ViewModel func image(networkManager: NetworkManager) -> RemoteImage { let placeholder = UIImage(named: "default_big") if let url = imageURL where hasProfileImage { return RemoteImageImpl(url: url, networkManager: networkManager, placeholder: placeholder, persist: true) } else { return RemoteImageJustImage(image: placeholder) } } var country: String? { guard let code = countryCode else { return nil } return NSLocale.currentLocale().displayNameForKey(NSLocaleCountryCode, value: code) } var language: String? { return languageCode.flatMap { return NSLocale.currentLocale().displayNameForKey(NSLocaleLanguageCode, value: $0) } } var educat: String? { if educationCode == "p" { return Strings.dDegree } else if educationCode == "m" { return Strings.mDegree } else if educationCode == "b" { return Strings.bDegree } else if educationCode == "a" { return Strings.aDegree } else if educationCode == "hs" { return Strings.hsDegree } else if educationCode == "jhs" { return Strings.jhsDegree } else if educationCode == "el" { return Strings.elDegree } else if educationCode == "none" { return Strings.noneDegree } else if educationCode == "other" { return Strings.otherDegree } else { return educationCode } } var sharingLimitedProfile: Bool { get { return (parentalConsent ?? false) || (accountPrivacy == nil) || (accountPrivacy! == .Private) } } func setLimitedProfile(newValue:Bool) { let newStatus: ProfilePrivacy = newValue ? .Private: .Public if newStatus != accountPrivacy { updateDictionary[ProfileFields.AccountPrivacy.rawValue] = newStatus.rawValue } accountPrivacy = newStatus } }
apache-2.0
14fff4be0a48a346d24b1c0e3dd91383
34.829146
302
0.614867
4.737542
false
false
false
false
ACChe/eidolon
Kiosk/App/Networking/NetworkLogger.swift
1
1865
import Foundation import Moya /// Logs network activity (outgoing requests and incoming responses). class NetworkLogger<Target: MoyaTarget>: Plugin<Target> { typealias Comparison = Target -> Bool let whitelist: Comparison let blacklist: Comparison init(whitelist: Comparison = { _ -> Bool in return true }, blacklist: Comparison = { _ -> Bool in return true }) { self.whitelist = whitelist self.blacklist = blacklist super.init() } override func willSendRequest(request: MoyaRequest, provider: MoyaProvider<Target>, target: Target) { // If the target is in the blacklist, don't log it. guard blacklist(target) == false else { return } logger.log("Sending request: \(request.request?.URL?.absoluteString ?? String())") } override func didReceiveResponse(data: NSData?, statusCode: Int?, response: NSURLResponse?, error: ErrorType?, provider: MoyaProvider<Target>, target: Target) { // If the target is in the blacklist, don't log it. guard blacklist(target) == false else { return } if 200..<400 ~= (statusCode ?? 0) && whitelist(target) == false { // If the status code is OK, and if it's not in our whitelist, then don't worry about logging its response body. logger.log("Received response(\(statusCode ?? 0)) from \(response?.URL?.absoluteString ?? String()).") } else { // Otherwise, log everything. let dataString: NSString? if let data = data { dataString = NSString(data: data, encoding: NSUTF8StringEncoding) ?? "Encoding error" } else { dataString = "No response body" } logger.log("Received response(\(statusCode ?? 0)) from \(response?.URL?.absoluteString ?? String()): \(dataString)") } } }
mit
f43e00af2dfaf85d955c2e793fbbc62f
40.444444
164
0.626273
4.831606
false
true
false
false
zeroc-ice/ice-demos
swift/Ice/helloUI/Client.swift
1
6204
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Combine import Ice import PromiseKit class Client: ObservableObject { // MARK: - Public Properties // For Error bindings @Published var error: Error? @Published var showingError = false // For Status bindings @Published var isSpinning = false @Published var statusMessage = "" // For Button view bindings @Published var helloEnabled: Bool = true @Published var shutdownEnabled = true @Published var flushEnabled = false @Published var proxySettings: ProxySettings = .init() { didSet { do { try updateProxy() } catch { exception(error) } } } // MARK: - Private Properties private var helloPrx: HelloPrx! private var communicator: Ice.Communicator // MARK: - Initialize the client with a communicator init() { communicator = Client.loadCommunicator() do { try updateProxy() } catch { exception(error) } } // MARK: - Public functions to send the say hello message, flush the batch requests, and shutdown the hello server func sayHello() { do { let delay = Int32(proxySettings.delay) if proxySettings.isBatched { // Batch requests get enqueued locally thus this call is non blocking try helloPrx.sayHello(delay) queuedRequest("hello") } else { // Non Batched requests get sent asynchronously var response = false firstly { helloPrx.sayHelloAsync(delay, sentOn: DispatchQueue.main) { _ in if !response { self.requestSent() } } }.done { response = true self.ready() }.catch { error in response = true self.exception(error) } } } catch { exception(error) } } func flushBatch() { firstly { helloPrx.ice_flushBatchRequestsAsync() }.done { self.flushBatchSend() }.catch { error in self.exception(error) } } func shutdown() { do { if proxySettings.isBatched { try helloPrx.shutdown() queuedRequest("shutdown") } else { sendingRequest() var response = false firstly { helloPrx.shutdownAsync { _ in if !response { self.requestSent() } } }.done { response = true self.ready() }.catch { error in response = true self.exception(error) self.ready() } } } catch { exception(error) ready() } } // MARK: - Control the state of the client private func exception(_ err: Error) { error = err showingError = true } private func flushBatchSend() { flushEnabled = false statusMessage = "Flushed batch requests" } private class func loadCommunicator() -> Ice.Communicator { var initData = Ice.InitializationData() let properties = Ice.createProperties() properties.setProperty(key: "Ice.Plugin.IceDiscovery", value: "0") properties.setProperty(key: "Ice.Plugin.IceSSL", value: "1") properties.setProperty(key: "IceSSL.CheckCertName", value: "0") properties.setProperty(key: "IceSSL.DefaultDir", value: "certs") properties.setProperty(key: "IceSSL.CAs", value: "cacert.der") properties.setProperty(key: "IceSSL.CertFile", value: "client.p12") properties.setProperty(key: "IceSSL.Password", value: "password") initData.properties = properties do { return try Ice.initialize(initData) } catch { print(error) fatalError() } } private func queuedRequest(_ name: String) { flushEnabled = true statusMessage = "Queued \(name) request" } private func ready() { helloEnabled = true shutdownEnabled = true statusMessage = "Ready" isSpinning = false } private func requestSent() { if proxySettings.deliveryMode == .twoway || proxySettings.deliveryMode == .twowaySecure { statusMessage = "Waiting for response" } else { ready() } } private func sendingRequest() { helloEnabled = false shutdownEnabled = false statusMessage = "Sending request" isSpinning = true } private func updateProxy() throws { let isHostEmpty = proxySettings.connection == "" let hostname = isHostEmpty ? "localhost" : proxySettings.connection let s = "hello:tcp -h \"\(hostname)\" -p 10000:" + "ssl -h \"\(hostname)\" -p 10001:" + "udp -h \"\(hostname)\" -p 10000" helloPrx = uncheckedCast(prx: try communicator.stringToProxy(s)!, type: HelloPrx.self) switch proxySettings.deliveryMode { case .twoway: helloPrx = helloPrx.ice_twoway() case .twowaySecure: helloPrx = helloPrx.ice_twoway().ice_secure(true) case .oneway: helloPrx = helloPrx.ice_oneway() case .onewayBatch: helloPrx = helloPrx.ice_batchOneway() case .onewaySecure: helloPrx = helloPrx.ice_oneway().ice_secure(true) case .onewaySecureBatch: helloPrx = helloPrx.ice_batchOneway().ice_secure(true) case .datagram: helloPrx = helloPrx.ice_datagram() case .datagramBatch: helloPrx = helloPrx.ice_batchDatagram() } if proxySettings.timeout != 0 { helloPrx = helloPrx.ice_invocationTimeout(Int32(proxySettings.timeout)) } } }
gpl-2.0
53c25265c0466dd2bded0055dd4702bb
29.263415
118
0.539168
4.831776
false
false
false
false
carping/Postal
Postal/IMAPSession+List.swift
1
2521
// // The MIT License (MIT) // // Copyright (c) 2017 Snips // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import libetpan extension IMAPSession { func listFolders() throws -> [Folder] { let prefix = defaultNamespace?.items.first?.prefix ?? MAIL_DIR_SEPARATOR_S var list: UnsafeMutablePointer<clist>? = nil if capabilities.contains(.XList) && !capabilities.contains(.Gmail) { // XLIST support is deprecated on Gmail. See https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated try mailimap_xlist(imap, prefix, "*", &list).toIMAPError?.check() } else { try mailimap_list(imap, prefix, "*", &list).toIMAPError?.check() } defer { mailimap_list_result_free(list) } if let list = list { return makeFolders(sequence(list, of: mailimap_mailbox_list.self)) } return [] } func makeFolders<S: Sequence>(_ sequence: S) -> [Folder] where S.Iterator.Element == mailimap_mailbox_list { return sequence.flatMap { (folder: mailimap_mailbox_list) -> Folder? in guard let name = String.fromUTF8CString(folder.mb_name) else { return nil } var mb_delimiter: [CChar] = [ folder.mb_delimiter, 0 ] let delimiter = String(cString: &mb_delimiter) return Folder(name: name, flags: FolderFlag(flags: folder.mb_flag), delimiter: delimiter) } } }
mit
2e24728624433a54246ea2133d3ca26b
44.017857
128
0.678302
4.105863
false
false
false
false
astephensen/Tock
Tock/Controllers/MenubarController.swift
1
2123
// // MenubarController.swift // Tock // // Created by Alan Stephensen on 11/05/2015. // Copyright (c) 2015 Alan Stephensen. All rights reserved. // import Cocoa class MenubarController: NSObject, NSPopoverDelegate { var statusItem: NSStatusItem var statusItemButton: NSStatusBarButton var viewController: NSViewController? var popover: NSPopover? var menu: NSMenu? let statusItemViewWidth = 22.0 override init() { // Create the status item and assign local variables. statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(CGFloat(statusItemViewWidth)) statusItemButton = statusItem.button! super.init() // Setup status item button. statusItemButton.image = NSImage(named: "menubar_icon") statusItemButton.alternateImage = NSImage(named: "menubar_icon_selected") statusItemButton.target = self statusItemButton.action = "statusButtonClicked:" } func statusButtonClicked(sender: AnyObject) { if popover?.shown == true { popover?.performClose(sender) } else { showViewController() } } func showViewController() { // Create the popover and show it from the status item button. popover = NSPopover() popover?.delegate = self // popover?.behavior = .Transient popover?.contentViewController = viewController popover?.appearance = NSAppearance(named: NSAppearanceNameAqua) popover?.showRelativeToRect(statusItemButton.frame, ofView: statusItemButton.superview!, preferredEdge: NSMaxYEdge) popover?.contentSize = NSSize(width: 590.0, height: 500.0) // We need to make the application active so the popover is in control. NSApplication.sharedApplication().activateIgnoringOtherApps(true) } func rightMouseClicked() { statusItem.popUpStatusItemMenu(menu!) } // MARK: NSPopoverDelegate func popoverDidClose(notification: NSNotification) { popover = nil } }
mit
fcdcafa36676b0e8948d5e0912982bd2
30.686567
123
0.658502
5.128019
false
false
false
false
openxc/openxc-ios-app-demo
openXCenabler/SendCanViewController.swift
1
3404
// // SendCanViewController.swift // openXCenabler // // Created by Tim Buick on 2016-08-04. // Copyright (c) 2016 Ford Motor Company Licensed under the BSD license. // import UIKit import openXCiOSFramework class SendCanViewController: UIViewController, UITextFieldDelegate { // UI outlets @IBOutlet weak var bussel: UISegmentedControl! @IBOutlet weak var idField: UITextField! @IBOutlet weak var dataField: UITextField! @IBOutlet weak var lastReq: UILabel! var vm: VehicleManager! var bm: BluetoothManager! override func viewDidLoad() { super.viewDidLoad() // grab VM instance vm = VehicleManager.sharedInstance bm = BluetoothManager.sharedInstance } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // text view delegate to clear keyboard func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder(); return true; } override func viewDidAppear(_ animated: Bool) { if(!bm.isBleConnected){ AlertHandling.sharedInstance.showAlert(onViewController: self, withText: errorMSG, withMessage:errorMsgBLE) } } // CAN send button hit @IBAction func sendHit(_ sender: AnyObject) { // hide keyboard when the send button is hit for textField in self.view.subviews where textField is UITextField { textField.resignFirstResponder() } // if the VM isn't operational, don't send anything if bm.connectionState != VehicleManagerConnectionState.operational { lastReq.text = "Not connected to VI" return } // create an empty CAN request let cmd = VehicleCanRequest() // look at segmented control for bus cmd.bus = bussel.selectedSegmentIndex + 1 // check that the msg id field is valid if let mid = idField.text as String? { let midtrim = mid.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if midtrim=="" { lastReq.text = "Invalid command : need a message_id" return } if let midInt = Int(midtrim,radix:16) as NSInteger? { cmd.id = midInt } else { lastReq.text = "Invalid command : message_id should be hex number (with no leading 0x)" return } } else { lastReq.text = "Invalid command : need a message_id" return } // check that the payload field is valid if let payld = dataField.text as String? { let payldtrim = payld.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if payldtrim=="" { lastReq.text = "Invalid command : need a payload" return } if (Int(payldtrim,radix:16) as NSInteger?) != nil { cmd.data = dataField.text! as NSString if (cmd.data.length % 2) == 1 { cmd.data = "0" + dataField.text! as NSString } } else { lastReq.text = "Invalid command : payload should be hex number (with no leading 0x)" return } } else { lastReq.text = "Invalid command : need a payload" return } // send the CAN request vm.sendCanReq(cmd) // update the last request sent label lastReq.text = "bus:"+String(cmd.bus)+" id:0x"+idField.text!+" payload:0x"+String(cmd.data) } }
bsd-3-clause
849937c3839fb8dc811e845559a8effd
26.451613
119
0.643948
4.369705
false
false
false
false
xwu/swift
tools/swift-inspect/Sources/swift-inspect/main.swift
1
7232
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ArgumentParser import SwiftRemoteMirror func argFail(_ message: String) -> Never { print(message, to: &Std.err) exit(EX_USAGE) } func machErrStr(_ kr: kern_return_t) -> String { let errStr = String(cString: mach_error_string(kr)) let errHex = String(kr, radix: 16) return "\(errStr) (0x\(errHex))" } func dumpConformanceCache(context: SwiftReflectionContextRef) throws { try context.iterateConformanceCache { type, proto in let typeName = context.name(metadata: type) ?? "<unknown>" let protoName = context.name(proto: proto) ?? "<unknown>" print("Conformance: \(typeName): \(protoName)") } } func dumpRawMetadata( context: SwiftReflectionContextRef, inspector: Inspector, backtraceStyle: Backtrace.Style? ) throws { let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:] for allocation in context.allocations { let tagName = context.metadataTagName(allocation.tag) ?? "<unknown>" print("Metadata allocation at: \(hex: allocation.ptr) " + "size: \(allocation.size) tag: \(allocation.tag) (\(tagName))") printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector) } } func dumpGenericMetadata( context: SwiftReflectionContextRef, inspector: Inspector, backtraceStyle: Backtrace.Style? ) throws { let allocations = context.allocations.sorted() let metadatas = allocations.findGenericMetadata(in: context) let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:] print("Address","Allocation","Size","Offset","Name", separator: "\t") for metadata in metadatas { print("\(hex: metadata.ptr)", terminator: "\t") if let allocation = metadata.allocation, let offset = metadata.offset { print("\(hex: allocation.ptr)\t\(allocation.size)\t\(offset)", terminator: "\t") } else { print("???\t???\t???", terminator: "\t") } print(metadata.name) if let allocation = metadata.allocation { printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector) } } } func dumpMetadataCacheNodes( context: SwiftReflectionContextRef, inspector: Inspector ) throws { print("Address","Tag","Tag Name","Size","Left","Right", separator: "\t") for allocation in context.allocations { guard let node = context.metadataAllocationCacheNode(allocation.allocation_t) else { continue } let tagName = context.metadataTagName(allocation.tag) ?? "<unknown>" print("\(hex: allocation.ptr)\t\(allocation.tag)\t\(tagName)\t" + "\(allocation.size)\t\(hex: node.Left)\t\(hex: node.Right)") } } func printBacktrace( style: Backtrace.Style?, for ptr: swift_reflection_ptr_t, in backtraces: [swift_reflection_ptr_t: Backtrace], inspector: Inspector ) { if let style = style { if let backtrace = backtraces[ptr] { print(backtrace.symbolicated(style: style, inspector: inspector)) } else { print("Unknown backtrace.") } } } func makeReflectionContext( nameOrPid: String ) -> (Inspector, SwiftReflectionContextRef) { guard let pid = pidFromHint(nameOrPid) else { argFail("Cannot find pid/process \(nameOrPid)") } guard let inspector = Inspector(pid: pid) else { argFail("Failed to inspect pid \(pid) (are you running as root?)") } guard let reflectionContext = swift_reflection_createReflectionContextWithDataLayout( inspector.passContext(), Inspector.Callbacks.QueryDataLayout, Inspector.Callbacks.Free, Inspector.Callbacks.ReadBytes, Inspector.Callbacks.GetStringLength, Inspector.Callbacks.GetSymbolAddress ) else { argFail("Failed to create reflection context") } return (inspector, reflectionContext) } func withReflectionContext( nameOrPid: String, _ body: (SwiftReflectionContextRef, Inspector) throws -> Void ) throws { let (inspector, context) = makeReflectionContext(nameOrPid: nameOrPid) defer { swift_reflection_destroyReflectionContext(context) inspector.destroyContext() } try body(context, inspector) } struct SwiftInspect: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Swift runtime debug tool", subcommands: [ DumpConformanceCache.self, DumpRawMetadata.self, DumpGenericMetadata.self, DumpCacheNodes.self, ]) } struct UniversalOptions: ParsableArguments { @Argument(help: "The pid or partial name of the target process") var nameOrPid: String } struct BacktraceOptions: ParsableArguments { @Flag(help: "Show the backtrace for each allocation") var backtrace: Bool = false @Flag(help: "Show a long-form backtrace for each allocation") var backtraceLong: Bool = false var style: Backtrace.Style? { backtrace ? .oneLine : backtraceLong ? .long : nil } } struct DumpConformanceCache: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the contents of the target's protocol conformance cache.") @OptionGroup() var options: UniversalOptions func run() throws { try withReflectionContext(nameOrPid: options.nameOrPid) { context, _ in try dumpConformanceCache(context: context) } } } struct DumpRawMetadata: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the target's metadata allocations.") @OptionGroup() var universalOptions: UniversalOptions @OptionGroup() var backtraceOptions: BacktraceOptions func run() throws { try withReflectionContext(nameOrPid: universalOptions.nameOrPid) { try dumpRawMetadata(context: $0, inspector: $1, backtraceStyle: backtraceOptions.style) } } } struct DumpGenericMetadata: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the target's generic metadata allocations.") @OptionGroup() var universalOptions: UniversalOptions @OptionGroup() var backtraceOptions: BacktraceOptions func run() throws { try withReflectionContext(nameOrPid: universalOptions.nameOrPid) { try dumpGenericMetadata(context: $0, inspector: $1, backtraceStyle: backtraceOptions.style) } } } struct DumpCacheNodes: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the target's metadata cache nodes.") @OptionGroup() var options: UniversalOptions func run() throws { try withReflectionContext(nameOrPid: options.nameOrPid) { try dumpMetadataCacheNodes(context: $0, inspector: $1) } } } SwiftInspect.main()
apache-2.0
78d0cc064d8d097b7a1dac2111a2c5ce
29.008299
102
0.685564
4.226768
false
false
false
false
ReactiveKit/ReactiveGitter
Entities/Utilities.swift
1
1468
// // Utilities.swift // ReactiveGitter // // Created by Srdan Rasic on 14/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import Foundation import Freddy private let dateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() extension String { public func to8601Date() throws -> Date { if let date = dateTimeFormatter.date(from: self) { return date } else { throw JSON.Error.valueNotConvertible(value: .string(self), to: Date.self) } } } extension Date { public func to8601String() -> String { return dateTimeFormatter.string(from: self) } } extension String { public func toURL() throws -> URL { if let url = URL(string: self) { return url } else { throw JSON.Error.valueNotConvertible(value: .string(self), to: URL.self) } } } extension JSONDecodable { public init(data: Data) throws { let json = try JSON(data: data) try self.init(json: json) } } extension Array where Element: JSONDecodable { public init(data: Data) throws { let json = try JSON(data: data) switch json { case .array(let array): try self.init(array.map(Element.init)) default: throw JSON.Error.valueNotConvertible(value: json, to: [Element].self) } } }
mit
9ceca71ee197952db16b00c58e485800
21.227273
79
0.66803
3.595588
false
false
false
false
goRestart/restart-backend-app
Tests/StorageTests/Utils/Validator/EmailValidatorSpec.swift
1
1303
import XCTest import Shared @testable import FluentStorage class EmailValidatorSpec: XCTestCase { static let allTests = [ ("testShould_return_false_when_email_is_invalid", testShould_return_false_when_email_is_invalid), ("testShould_return_true_when_email_is_valid", testShould_return_true_when_email_is_valid), ("testShould_return_false_when_email_lenght_is_incorrect", testShould_return_false_when_email_lenght_is_incorrect) ] private let sut = EmailValidator() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testShould_return_false_when_email_is_invalid() { let invalidEmail1 = "despacito@" let invalidEmail2 = "favoritos@com" let invalidEmail3 = "fonsihot.com" XCTAssertFalse(sut.validate(invalidEmail1)) XCTAssertFalse(sut.validate(invalidEmail2)) XCTAssertFalse(sut.validate(invalidEmail3)) } func testShould_return_true_when_email_is_valid() { let validEmail = "[email protected]" XCTAssertTrue(sut.validate(validEmail)) } func testShould_return_false_when_email_lenght_is_incorrect() { let invalidEmail = "[email protected]" XCTAssertFalse(sut.validate(invalidEmail)) } }
gpl-3.0
ee7267d27512b78a40d9e7c4fc3a9f46
28.613636
122
0.669992
3.901198
false
true
false
false
kyle791121/Lookout
Lookout/Lookout/Person.swift
1
575
// // Person.swift // Lookout // // Created by Chunkai Chan on 2016/9/26. // Copyright © 2016年 Chunkai Chan. All rights reserved. // import Foundation class Person { var name: String var phoneNumber: String var trackID: String var email: String var photo: NSData? init(name: String, phoneNumber: String, trackID: String, email: String, photo: NSData) { self.name = name self.phoneNumber = phoneNumber self.trackID = trackID self.email = email self.photo = photo } }
mit
5e4b1ba76ac8dc725a4d183927517575
18.758621
92
0.59965
4.085714
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Base/KLScriptValue.swift
1
8098
/** * @file KLScriptValue.swift * @brief Extend JSValue class * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import KiwiEngine import CoconutData import JavaScriptCore import Foundation private var temp_record_id: UInt = 0 extension JSValue { public static let instancePropertyName: String = "instanceName" public convenience init(URL url: URL, in context: KEContext) { let urlobj = KLURL(URL: url, context: context) self.init(object: urlobj, in: context) } public convenience init(image img: CNImage, in context: KEContext) { let imgobj = KLImage(context: context) imgobj.coreImage = img self.init(object: imgobj, in: context) } public static func hasClassName(value val: JSValue, className name: String) -> Bool { if let dict = val.toObject() as? Dictionary<String, Any> { if let str = dict["class"] as? String { return str == name } } return false } public var isDictionary: Bool { get { if let _ = self.toDictionary() { return true } else { return false } } } public var isSet: Bool { get { return CNValueSet.isSet(scriptValue: self) }} public func toSet() -> CNValue? { return CNValueSet.fromJSValue(scriptValue: self) } public var isPoint: Bool { get { return CGPoint.isPoint(scriptValue: self) } } public var isSize: Bool { get { return CGSize.isSize(scriptValue: self) } } public var isRect: Bool { get { return CGRect.isRect(scriptValue: self) } } public var isRange: Bool { get { return NSRange.isRange(scriptValue: self) } } public var isEnum: Bool { get { return CNEnum.isEnum(scriptValue: self) } } public func toEnum() -> CNEnum? { return CNEnum.fromJSValue(scriptValue: self) } public var isURL: Bool { get { if let urlobj = self.toObject() as? KLURL { if let _ = urlobj.url { return true } } return false } } public func toURL() -> URL? { if let urlobj = self.toObject() as? KLURL { if let url = urlobj.url { return url } } return nil } public var isImage: Bool { get { if let imgobj = self.toObject() as? KLImage { if let _ = imgobj.coreImage { return true } } return false }} public func toImage() -> CNImage? { if let imgobj = self.toObject() as? KLImage { if let img = imgobj.coreImage { return img } } return nil } public var isRecord: Bool { get { if let _ = self.toObject() as? KLRecord { return true } else { return false } }} public func toRecord() -> CNRecord? { if let recobj = self.toObject() as? KLRecordCoreProtocol { return recobj.core() } else { return nil } } public var isColor: Bool { get { if let _ = self.toObject() as? KLColor { return true } return false } } public func toColor() -> CNColor? { if let colobj = self.toObject() as? KLColor { return colobj.core } return nil } public var isSegment: Bool { get { return CNValueSegment.isValueSegment(scriptValue: self) } } public func toSegment() -> CNValueSegment? { return CNValueSegment.fromJSValue(scriptValue: self) } public var isPointer: Bool { get { return CNPointerValue.isPointer(scriptValue: self) } } public func toPointer() -> CNPointerValue? { switch CNPointerValue.fromJSValue(scriptValue: self) { case .success(let val): return val case .failure(let err): CNLog(logLevel: .error, message: err.toString(), atFunction: #function, inFile: #file) return nil } } private func anyToDouble(any aval: Any?) -> CGFloat? { if let val = aval as? CGFloat { return val } else if let val = aval as? Double { return CGFloat(val) } else if let val = aval as? NSNumber { return CGFloat(val.floatValue) } else { return nil } } private func anyToInt(any aval: Any?) -> Int? { if let val = aval as? Int { return val } else if let val = aval as? NSNumber { return val.intValue } else { return nil } } private func anyToString(any aval: Any?) -> String? { if let val = aval as? String { return val } else { return nil } } public var type: CNValueType? { get { var result: CNValueType? if self.isUndefined { result = nil } else if self.isNull { result = .objectType(nil) } else if self.isBoolean { result = .boolType } else if self.isNumber { result = .numberType } else if self.isString { result = .stringType } else if self.isArray { result = .arrayType(.anyType) } else if self.isSet { result = .setType(.anyType) } else if self.isDictionary { result = .dictionaryType(.anyType) } else if self.isObject { if let _ = self.toObject() as? Dictionary<AnyHashable, Any> { result = .dictionaryType(.anyType) } else { result = .objectType(nil) } } else { fatalError("Unknown type: \"\(self.description)\"") } return result } } public func toNativeValue() -> CNValue { let result: CNValue if let type = self.type { switch type { case .anyType, .voidType, .functionType(_, _), .interfaceType(_): CNLog(logLevel: .error, message: "Can not assign native value", atFunction: #function, inFile: #file) result = CNValue.null case .boolType: result = .boolValue(self.toBool()) case .numberType: result = .numberValue(self.toNumber()) case .stringType: result = .stringValue(self.toString()) case .enumType: if let eval = self.toEnum() { result = CNValue.enumValue(eval) } else { result = CNValue.null } case .arrayType: let srcarr = self.toArray()! var dstarr: Array<CNValue> = [] for elm in srcarr { if let object = elementToValue(any: elm) { dstarr.append(object) } else { CNLog(logLevel: .error, message: "Failed to convert to Array", atFunction: #function, inFile: #file) } } result = .arrayValue(dstarr) case .setType: if let val = CNValueSet.fromJSValue(scriptValue: self) { result = val } else { CNLog(logLevel: .error, message: "Failed to convert to set", atFunction: #function, inFile: #file) result = CNValue.null } case .dictionaryType: var dstdict: Dictionary<String, CNValue> = [:] if let srcdict = self.toDictionary() as? Dictionary<String, Any> { for (key, value) in srcdict { if let obj = elementToValue(any: value) { dstdict[key] = obj } else { CNLog(logLevel: .error, message: "Failed to convert to Dictionary: key=\(key), value=\(value)", atFunction: #function, inFile: #file) } } } else { CNLog(logLevel: .error, message: "Failed to convert to Dictionary: \(String(describing: self.toDictionary()))", atFunction: #function, inFile: #file) } if let scalar = CNValue.dictionaryToValue(dictionary: dstdict) { result = scalar } else { result = .dictionaryValue(dstdict) } case .objectType: if let obj = self.toObject() { result = .objectValue(obj as AnyObject) } else { CNLog(logLevel: .error, message: "Failed to convert to Object", atFunction: #function, inFile: #file) result = CNValue.null } @unknown default: CNLog(logLevel: .error, message: "Unknown case", atFunction: #function, inFile: #file) result = CNValue.null } } else { result = CNValue.null } return result } private func elementToValue(any value: Any) -> CNValue? { if let val = value as? JSValue { return val.toNativeValue() } else if let val = value as? KLURL { if let url = val.url { return CNValue.anyToValue(object: url) } else { CNLog(logLevel: .error, message: "Null URL", atFunction: #function, inFile: #file) return CNValue.null } } else if let val = value as? KLImage { if let image = val.coreImage { return CNValue.anyToValue(object: image) } else { CNLog(logLevel: .error, message: "Null Image", atFunction: #function, inFile: #file) return CNValue.null } } else { return CNValue.anyToValue(object: value) } } public func toScript() -> CNText { let native = self.toNativeValue() return native.toScript() } }
lgpl-2.1
a587ce1a38157e00f968029f9a498af5
23.245509
154
0.644604
3.164517
false
false
false
false
aktowns/swen
Sources/Swen/Sprite.swift
1
4566
// // Sprite.swift created on 9/01/16 // Swen project // // Copyright 2016 Ashley Towns <[email protected]> // // 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 Signals public protocol PhysicsBody { var position: Vector { get set } var velocity: Vector { get set } var size: Size { get set } var mass: Double { get set } var elasticity: Double { get set } var friction: Double { get set } var moment: Double { get set } var radius: Double { get set } } extension PhysicsBody { public var bodyRect: Rect { return Rect(x: position.x, y: position.y, sizeX: size.sizeX, sizeY: size.sizeY) } } public protocol PhysicsUpdatable { func willUpdatePosition(position: Vector) func willUpdateVelocity(velocity: Vector) } public protocol CustomVelocityPhysics { func velocityUpdate(body: PhyBody, gravity: Vector, damping: Double, dt: Double) } public protocol CustomPositionPhysics { func positionUpdate(body: PhyBody, dt: Double) } public class Sprite: PhysicsUpdatable, PhysicsBody { public let pipeline: ContentPipeline let onPositionChanged = Signal<Vector>() let onVelocityChanged = Signal<Vector>() let onSizeChanged = Signal<Size>() let onMassChanged = Signal<Double>() let onElasticityChanged = Signal<Double>() let onFrictionChanged = Signal<Double>() public var position: Vector { didSet { onPositionChanged => position } } public var velocity: Vector { didSet { onVelocityChanged => velocity } } public var size: Size { didSet { onSizeChanged => size } } public var mass: Double { didSet { onMassChanged => mass } } public var elasticity: Double { didSet { onElasticityChanged => elasticity } } public var friction: Double { didSet { onFrictionChanged => friction } } public var moment = Double.infinity public var radius = 10.0 public var spriteMainBody: PhyBody? public var spriteMainShape: PhyShape? public init(pipeline: ContentPipeline) throws { self.pipeline = pipeline self.position = Vector.zero self.velocity = Vector.zero self.size = Size.zero self.mass = 1.0 self.elasticity = 0.0 self.friction = 0.0 self.spriteMainBody = Optional.None self.spriteMainShape = Optional.None setup() } public func setup() { } public func willUpdatePosition(position: Vector) { self.position = position } public func willUpdateVelocity(velocity: Vector) { self.velocity = velocity } public func registerInSpace(space: PhySpace, withTag tag: String) { self.spriteMainBody = PhyBody(mass: self.mass, moment: self.moment) self.spriteMainShape = PhyShape(boxShapeFrom: spriteMainBody!, box: PhyBoundingBox(size: self.size), radius: self.radius) let body = space.addBody(self.spriteMainBody!) body.position = self.position body.onPositionChanged.listen(self) { (newPos) in if self.position != newPos { self.willUpdatePosition(newPos) } } body.onVelocityChanged.listen(self) { (newVel) in if self.velocity != newVel { self.willUpdateVelocity(newVel) } } self.onPositionChanged.listen(body) { (newPos) in body.position = newPos } self.onVelocityChanged.listen(body) { (newVel) in body.velocity = newVel } self.onMassChanged.listen(body) { (newMass) in body.mass = newMass } switch self { case let spr as CustomVelocityPhysics: body.setVelocityUpdateFunc(spr.velocityUpdate) case let spr as CustomPositionPhysics: body.setPositionUpdateFunc(spr.positionUpdate) default: Void() } let shape = space.addShape(self.spriteMainShape!) shape.elasticity = self.elasticity shape.friction = self.friction shape.collisionType = 1 shape.tag = tag self.onElasticityChanged.listen(shape) { (newElas) in shape.elasticity = newElas } self.onFrictionChanged.listen(shape) { (newFric) in shape.friction = newFric } } }
apache-2.0
0627a85bca20ffc15863991242852b27
24.50838
104
0.687473
3.840202
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Data/KLColor.swift
1
1374
/** * @file KLColor.swift * @brief Define KLColor class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import KiwiEngine import CoconutData import JavaScriptCore import Foundation @objc public protocol KLColorProtocol: JSExport { var red: JSValue { get } var green: JSValue { get } var blue: JSValue { get } var alpha: JSValue { get } func toString() -> JSValue } @objc public class KLColor: NSObject, KLColorProtocol { private var mColor: CNColor private var mContext: KEContext public var core: CNColor { get { return mColor }} public init(color col: CNColor, context ctxt: KEContext) { mColor = col mContext = ctxt } public var red: JSValue { get { return anyComponent(component: mColor.redComponent) }} public var green: JSValue { get { return anyComponent(component: mColor.greenComponent) }} public var blue: JSValue { get { return anyComponent(component: mColor.blueComponent) }} public var alpha: JSValue { get { return anyComponent(component: mColor.alphaComponent) }} public func toString() -> JSValue { let (red, green, blue, alpha) = mColor.toRGBA() let str = "Color(red=\(red), green=\(green), blue=\(blue), alpha=\(alpha))" return JSValue(object: str, in: mContext) } private func anyComponent(component comp: CGFloat) -> JSValue { return JSValue(double: Double(comp), in: mContext) } }
lgpl-2.1
997fa290cf9f773fdc62c106f07c7fd5
27.040816
92
0.71179
3.514066
false
false
false
false
Anvics/Amber
Amber/Classes/AmberRouter.swift
1
8767
// // AmberRouter.swift // TrainBrain // // Created by Nikita Arkhipov on 09.10.2017. // Copyright © 2017 Nikita Arkhipov. All rights reserved. // import UIKit enum AmberPresentationType{ case present, show, embed } public protocol AmberEmbedder { func embed<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, inView view: UIView, outputListener: Module.OutputActionListener?) -> Module.InputActionListener } public extension AmberEmbedder{ func embed<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, inView view: UIView) -> Module.InputActionListener{ return embed(module, data: data, inView: view, outputListener: nil) } func embed<Module: AmberController>(_ module: Module.Type, inView view: UIView, outputListener: Module.OutputActionListener? = nil) -> Module.InputActionListener where Module.Reducer.State.RequiredData == Void { return embed(module, data: (), inView: view, outputListener: outputListener) } } public protocol AmberRoutePerformer: AmberEmbedder { func replace<Module: AmberController>(with module: Module.Type, data: Module.Reducer.State.RequiredData, animation: UIViewAnimationOptions) func show<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener func present<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener func baseReplace(storyboardFile: String, storyboardID: String, animation: UIViewAnimationOptions) func baseShow(storyboardFile: String, storyboardID: String) func basePresent(storyboardFile: String, storyboardID: String) func close() func dismiss() func pop() func popToRoot() } public extension AmberRoutePerformer{ func replace<Module: AmberController>(with module: Module.Type, animation: UIViewAnimationOptions = .transitionCrossDissolve) where Module.Reducer.State.RequiredData == Void{ replace(with: module, data: (), animation: animation) } func replace<Module: AmberController>(with module: Module.Type, data: Module.Reducer.State.RequiredData){ replace(with: module, data: data, animation: .transitionCrossDissolve) } func baseReplace(storyboardFile: String, storyboardID: String){ baseReplace(storyboardFile: storyboardFile, storyboardID: storyboardID, animation: .transitionCrossDissolve) } func show<Module: AmberController>(_ module: Module.Type, outputListener: Module.OutputActionListener? = nil) -> Module.InputActionListener where Module.Reducer.State.RequiredData == Void{ return show(module, data: (), outputListener: outputListener) } func show<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData) -> Module.InputActionListener{ return show(module, data: data, outputListener: nil) } func present<Module: AmberController>(_ module: Module.Type, outputListener: Module.OutputActionListener? = nil) -> Module.InputActionListener where Module.Reducer.State.RequiredData == Void{ return present(module, data: (), outputListener: outputListener) } } public class FakeAmberRoutePerformer: AmberRoutePerformer{ public func embed<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, inView view: UIView, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ return { _ in } } public func replace<Module: AmberController>(with module: Module.Type, data: Module.Reducer.State.RequiredData, animation: UIViewAnimationOptions){ } public func show<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ return { _ in } } public func present<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ return { _ in } } public func baseReplace(storyboardFile: String, storyboardID: String, animation: UIViewAnimationOptions){ } public func baseShow(storyboardFile: String, storyboardID: String){ } public func basePresent(storyboardFile: String, storyboardID: String){ } public func close(){ } public func dismiss(){ } public func pop(){ } public func popToRoot(){ } } final class AmberRoutePerformerImplementation<T: AmberController, U: AmberController>: AmberRoutePerformer { weak var controller: T? weak var embedder: U? init(controller: T, embedder: U) { self.controller = controller self.embedder = embedder } func replace<Module: AmberController>(with module: Module.Type, data: Module.Reducer.State.RequiredData, animation: UIViewAnimationOptions){ let (vc, _) = AmberControllerHelper.create(module: module, data: data, outputListener: nil) replaceWith(vc, animation: animation) } func show<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ return route(module: module, data: data, presentation: .show, outputListener: outputListener) } func present<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ return route(module: module, data: data, presentation: .present, outputListener: outputListener) } func baseReplace(storyboardFile: String, storyboardID: String, animation: UIViewAnimationOptions){ let vc = createController(storyboardFile: storyboardFile, storyboardID: storyboardID) replaceWith(vc, animation: animation) } func baseShow(storyboardFile: String, storyboardID: String){ let vc = createController(storyboardFile: storyboardFile, storyboardID: storyboardID) controller?.show(vc, animated: true) } func basePresent(storyboardFile: String, storyboardID: String){ let vc = createController(storyboardFile: storyboardFile, storyboardID: storyboardID) controller?.present(vc, animated: true, completion: nil) } func close() { controller?.close(animated: true) } func dismiss(){ controller?.dismiss(animated: true) } func pop() { controller?.pop(animated: true) } func popToRoot() { controller?.popToRoot(animated: true) } func embed<Module: AmberController>(_ module: Module.Type, data: Module.Reducer.State.RequiredData, inView view: UIView, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ let (vc, output) = AmberControllerHelper.create(module: module, data: data, route: controller!, outputListener: outputListener) guard let uicontroller = controller as? UIViewController else { fatalError() } vc.embedIn(view: view, container: uicontroller) return output } private func replaceWith(_ vc: UIViewController, animation: UIViewAnimationOptions){ guard let currentVC = UIApplication.shared.keyWindow?.rootViewController else { fatalError() } UIView.transition(from: currentVC.view, to: vc.view, duration: 0.4, options: animation) { _ in UIApplication.shared.keyWindow?.rootViewController = vc } } private func createController(storyboardFile: String, storyboardID: String) -> UIViewController{ return UIStoryboard(name: storyboardFile, bundle: nil).instantiateViewController(withIdentifier: storyboardID) } fileprivate func route<Module: AmberController>(module: Module.Type, data: Module.Reducer.State.RequiredData, presentation: AmberPresentationType, outputListener: Module.OutputActionListener?) -> Module.InputActionListener{ let (vc, output) = AmberControllerHelper.create(module: module, data: data, outputListener: outputListener) switch presentation { case .present: controller?.present(vc, animated: true, completion: nil) case .show: controller?.show(vc, animated: true) case .embed: fatalError("Call embed instead of route") } return output } } public protocol AmberRouter{ associatedtype Reducer: AmberReducer func perform(transition: Reducer.Transition, route: AmberRoutePerformer, reducer: Reducer, performAction: @escaping (Reducer.Action) -> Void) } typealias AmberRouterBlock<Reducer: AmberReducer> = (Reducer.Transition, AmberRoutePerformer, Reducer, @escaping (Reducer.Action) -> Void) -> Void
mit
0cf2a3662f78f65204ff9a0d0a81903a
48.806818
227
0.743326
4.341753
false
false
false
false
TouchInstinct/LeadKit
TIUIElements/Sources/Helpers/DefaultAnimators/ParalaxAnimator.swift
1
817
import UIKit final public class ParalaxAnimator: CollapsibleViewsAnimator { public var fractionComplete: CGFloat = 0 { didSet { navBar?.topItem?.titleView?.alpha = fractionComplete == 1 ? 1 : 0 } } public var currentContentOffset: CGPoint { didSet { tableHeaderView?.layout(for: currentContentOffset) } } private weak var navBar: UINavigationBar? private weak var tableHeaderView: ParallaxTableHeaderView? public init(tableHeaderView: ParallaxTableHeaderView, navBar: UINavigationBar? = nil, // if nil - no alpha animation currentContentOffset: CGPoint) { self.currentContentOffset = currentContentOffset self.tableHeaderView = tableHeaderView self.navBar = navBar } }
apache-2.0
315561f5f2cf1a062297d5b082b69305
30.423077
78
0.658507
5.713287
false
false
false
false
kevinjcliao/iosStopwatch
Navigation Bars/ViewController.swift
1
1288
// // ViewController.swift // Navigation Bars // // Created by Kevin Liao on 7/4/15. // Copyright (c) 2015 Kevin Liao. All rights reserved. // import UIKit class ViewController: UIViewController { var started = false var timeToRestart = false @IBOutlet weak var timeDisplay: UILabel! @IBOutlet weak var stopOrResetButton: UIBarButtonItem! @IBAction func onStartPress(sender: AnyObject) { timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true) } @IBAction func onStopOrResetPress(sender: AnyObject) { if timeToRestart { count = 0 timeDisplay.text = String(count) } else { timer.invalidate() timeToRestart = true stopOrResetButton.title = "Reset" } } var timer = NSTimer() var count = 1 func result(){ println(count) timeDisplay.text = String(count) count += 1 } override func viewDidLoad() { super.viewDidLoad() timeDisplay.text = "0" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
unlicense
5a4c0fdf04694d41d1c4c7e5270291b8
22
131
0.609472
4.616487
false
false
false
false
J1aDong/GoodBooks
GoodBooks/bookDetailView.swift
1
3311
// // bookDetailView.swift // GoodBooks // // Created by J1aDong on 2017/2/2. // Copyright © 2017年 J1aDong. All rights reserved. // import UIKit class bookDetailView: UIView { var VIEW_WIDTH:CGFloat? var VIEW_HEIGHT:CGFloat? var bookName:UILabel? var editor:UILabel? var userName:UILabel? var date:UILabel? var more:UILabel? var scroe:LDXScore? var cover:UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.VIEW_WIDTH = frame.size.width self.VIEW_HEIGHT = frame.size.height self.backgroundColor = UIColor.white self.cover = UIImageView(frame: CGRect(x: 8, y: 8, width: (VIEW_HEIGHT!-16)/1.273, height: VIEW_HEIGHT!-16)) self.addSubview(self.cover!) self.bookName = UILabel(frame: CGRect(x: (VIEW_HEIGHT!-16)/1.273+16, y: 8, width: VIEW_WIDTH! - (VIEW_HEIGHT! - 16)/1.273-16, height: VIEW_HEIGHT!/4)) self.bookName?.font = UIFont(name: MY_FONT, size: 18) self.addSubview(self.bookName!) self.editor = UILabel(frame: CGRect(x: (VIEW_HEIGHT!-16)/1.273+16, y: 8+VIEW_HEIGHT!/4, width: VIEW_WIDTH! - (VIEW_HEIGHT! - 16)/1.273-16, height: VIEW_HEIGHT!/4)) self.editor?.font = UIFont(name: MY_FONT, size: 18) self.addSubview(self.editor!) self.userName = UILabel(frame: CGRect(x:(VIEW_HEIGHT!-16)/1.273+16,y:24+VIEW_HEIGHT!/4+VIEW_HEIGHT!/6,width:VIEW_WIDTH!-(VIEW_HEIGHT! - 16)/1.273-16,height:VIEW_HEIGHT!/6)) self.userName?.font = UIFont(name: MY_FONT, size: 13) self.userName?.textColor = RGB(r: 35, g: 87, b: 13) self.addSubview(self.userName!) self.date = UILabel(frame: CGRect(x: (VIEW_HEIGHT!-16)/1.273+16, y: 16+VIEW_HEIGHT!/4+VIEW_HEIGHT!/6*2, width: 80, height: VIEW_HEIGHT!/6)) self.date?.textColor = UIColor.gray self.date?.font = UIFont(name: MY_FONT, size: 13) self.addSubview(self.date!) self.scroe = LDXScore(frame: CGRect(x: (VIEW_HEIGHT!-16)/1.273+16+80, y: 16+VIEW_HEIGHT!/4+VIEW_HEIGHT!/6*2, width: 80, height: VIEW_HEIGHT!/6)) self.scroe?.isSelect = false self.scroe?.normalImg = UIImage(named: "btn_star_evaluation_normal") self.scroe?.highlightImg = UIImage(named: "btn_star_evaluation_press") self.scroe?.max_star = 5 self.scroe?.show_star = 5 self.addSubview(self.scroe!) self.more = UILabel(frame: CGRect(x:(VIEW_HEIGHT!-16)/1.273+16,y:8+VIEW_HEIGHT!/4+VIEW_HEIGHT!/6*3,width:VIEW_WIDTH!-(VIEW_HEIGHT! - 16)/1.273-16,height:VIEW_HEIGHT!/6)) self.more?.textColor = UIColor.gray self.more?.font = UIFont(name: MY_FONT, size: 13) self.addSubview(self.more!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.setLineWidth(0.5) context?.setStrokeColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1) context?.move(to: CGPoint(x: 8, y: VIEW_HEIGHT!-2)) context?.addLine(to: CGPoint(x: VIEW_WIDTH! - 8, y: VIEW_HEIGHT! - 2)) context?.strokePath() } }
mit
0e8fb3fed997e4f84dfd811c7f503075
40.35
180
0.616082
3.28827
false
false
false
false
sjtu-meow/iOS
Meow/AnswerTableViewCell.swift
1
1234
// // QuestionAnswerPageAnswerCell.swift // Meow // // Created by 林武威 on 2017/7/10. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit protocol AnswerCellDelegate { func onTitleTapped(answer: AnswerSummary) } class AnswerTableViewCell: UITableViewCell { var model: AnswerSummary? var delegate: AnswerCellDelegate? @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var likeCountLabel: UILabel! @IBOutlet weak var commentCountLabel: UILabel! override func awakeFromNib() { let tapAction = UITapGestureRecognizer(target: self, action: #selector(self.onTitleTapped(_:))) titleLabel.addGestureRecognizer(tapAction) } func configure(model: AnswerSummary) { self.model = model titleLabel.text = model.questionTitle contentLabel.text = model.content likeCountLabel.text = "\(model.likeCount ?? 0)" commentCountLabel.text = "\(model.commentCount ?? 0)" } func onTitleTapped(_ sender: UITapGestureRecognizer) { guard let model = model else { return } delegate?.onTitleTapped(answer: model) } }
apache-2.0
a54298ca5d3afa9e4a1305ab0763703a
27.209302
103
0.674361
4.492593
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/UIComponents/UIComponentsKit/LayoutConstants.swift
1
1483
import SwiftUI public enum LayoutConstants { public static let buttonCornerRadious: CGFloat = 8 public static let buttonMinHeight: CGFloat = 48 } extension LayoutConstants { public enum VerticalSpacing { public static let betweenContentGroups: CGFloat = 16 public static let betweenContentGroupsLarge: CGFloat = 24 public static let withinButtonsGroup: CGFloat = 16 public static let withinFormGroup: CGFloat = 4 } } extension LayoutConstants { enum Text { enum FontSize { static let title: CGFloat = 20 static let heading: CGFloat = 16 static let subheading: CGFloat = 14 static let body: CGFloat = 14 static let formField: CGFloat = 16 } enum LineHeight { static let title: CGFloat = 30 static let heading: CGFloat = 24 static let subheading: CGFloat = 20 static let body: CGFloat = 20 static let formField: CGFloat = 24 } enum LineSpacing { static let title: CGFloat = LineHeight.title - FontSize.title static let heading: CGFloat = LineHeight.heading - FontSize.heading static let subheading: CGFloat = LineHeight.subheading - FontSize.subheading static let body: CGFloat = LineHeight.body - FontSize.body static let formField: CGFloat = LineHeight.formField - FontSize.formField } } }
lgpl-3.0
7ae5b2254744d053bfa7f1a4afd86f57
30.553191
88
0.633176
5.334532
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Coincore/AssetLoader/DynamicAssetLoader.swift
1
4187
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import Foundation import MoneyKit import ToolKit /// An AssetLoader that loads some CryptoAssets straight away, and lazy load others. final class DynamicAssetLoader: AssetLoader { // MARK: Properties var loadedAssets: [CryptoAsset] { storage.value .sorted { lhs, rhs in lhs.key < rhs.key } .map(\.value) } // MARK: Private Properties private let enabledCurrenciesService: EnabledCurrenciesServiceAPI private let erc20AssetFactory: ERC20AssetFactoryAPI private let storage: Atomic<[CryptoCurrency: CryptoAsset]> = .init([:]) // MARK: Init init( enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve(), erc20AssetFactory: ERC20AssetFactoryAPI = resolve() ) { self.enabledCurrenciesService = enabledCurrenciesService self.erc20AssetFactory = erc20AssetFactory } // MARK: Methods func initAndPreload() -> AnyPublisher<Void, Never> { Deferred { [storage, enabledCurrenciesService, erc20AssetFactory] in Future<Void, Never> { subscriber in let allEnabledCryptoCurrencies = enabledCurrenciesService.allEnabledCryptoCurrencies let nonCustodialCoinCodes = NonCustodialCoinCode.allCases.map(\.rawValue) // Crypto Assets for coins with Non Custodial support (BTC, BCH, ETH, XLM) let nonCustodialAssets: [CryptoAsset] = allEnabledCryptoCurrencies .filter(\.isCoin) .filter { nonCustodialCoinCodes.contains($0.code) } .map { cryptoCurrency -> CryptoAsset in DIKit.resolve(tag: cryptoCurrency) } // Crypto Currencies with Custodial support. let custodialCryptoCurrencies: [CryptoCurrency] = allEnabledCryptoCurrencies .filter { cryptoCurrency in cryptoCurrency.supports(product: .custodialWalletBalance) } .filter { cryptoCurrency in !nonCustodialCoinCodes.contains(cryptoCurrency.code) } // Crypto Assets for any currency with Custodial support. let custodialAssets: [CryptoAsset] = custodialCryptoCurrencies .compactMap { [erc20AssetFactory] cryptoCurrency -> CryptoAsset? in createCryptoAsset( cryptoCurrency: cryptoCurrency, erc20AssetFactory: erc20AssetFactory ) } storage.mutate { storage in storage.removeAll() nonCustodialAssets.forEach { asset in storage[asset.asset] = asset } custodialAssets.forEach { asset in storage[asset.asset] = asset } } subscriber(.success(())) } } .eraseToAnyPublisher() } // MARK: - Subscript subscript(cryptoCurrency: CryptoCurrency) -> CryptoAsset { storage.mutateAndReturn { [erc20AssetFactory] storage in guard let cryptoAsset = storage[cryptoCurrency] else { let cryptoAsset: CryptoAsset = createCryptoAsset( cryptoCurrency: cryptoCurrency, erc20AssetFactory: erc20AssetFactory ) storage[cryptoCurrency] = cryptoAsset return cryptoAsset } return cryptoAsset } } } private func createCryptoAsset( cryptoCurrency: CryptoCurrency, erc20AssetFactory: ERC20AssetFactoryAPI ) -> CryptoAsset { switch cryptoCurrency.assetModel.kind { case .coin, .celoToken: return CustodialCryptoAsset(asset: cryptoCurrency) case .erc20: return erc20AssetFactory.erc20Asset(erc20AssetModel: cryptoCurrency.assetModel) case .fiat: impossible() } }
lgpl-3.0
07226c8344b48aa9acd157bb0635e247
35.086207
100
0.590779
5.515152
false
false
false
false
manGoweb/S3
Sources/S3Kit/Extensions/S3+List.swift
1
1685
import Foundation import NIO import NIOHTTP1 // Helper S3 extension for getting file indexes extension S3 { /// Get list of objects public func list(bucket: String, region: Region? = nil, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<BucketResults> { let region = region ?? signer.config.region guard let baseUrl = URL(string: region.hostUrlString(bucket: bucket)), let host = baseUrl.host, var components = URLComponents(string: baseUrl.absoluteString) else { return eventLoop.makeFailedFuture(S3.Error.invalidUrl) } components.queryItems = [ URLQueryItem(name: "list-type", value: "2") ] guard let url = components.url else { return eventLoop.makeFailedFuture(S3.Error.invalidUrl) } let awsHeaders: HTTPHeaders do { var headers = headers headers["host"] = host awsHeaders = try signer.headers(for: .GET, urlString: url.absoluteString, region: region, bucket: bucket, headers: headers, payload: .none) } catch let error { return eventLoop.makeFailedFuture(error) } return make(request: url, method: .GET, headers: awsHeaders, data: Data(), on: eventLoop).flatMapThrowing { response in try self.check(response) return try response.decode(to: BucketResults.self) } } /// Get list of objects public func list(bucket: String, region: Region? = nil, on eventLoop: EventLoop) -> EventLoopFuture<BucketResults> { return list(bucket: bucket, region: region, headers: [:], on: eventLoop) } }
mit
d8e8dfa10b586f7270e78a17ecbe7425
37.295455
151
0.636202
4.566396
false
false
false
false
blue42u/swift-t
stc/tests/688-app-node-target.swift
4
552
import assert; import files; import io; import string; import location; app (file o) hostname() { "hostname" @stdout=o; } (string o) extract_hostname(file f) { o = trim(read(f)); } main { string host1 = extract_hostname(hostname()); int rank = hostmapOneRank(host1); location loc = location(rank, HARD, NODE); foreach i in [1:500] { string host2 = extract_hostname(@location=loc hostname()); printf("Hostname %i: %s", i, host2); /* Check that apps run on the correct host! */ assertEqual(host2, host1, "hosts"); } }
apache-2.0
5d2cb0fc2b729ee6ec1c879863e29b3a
18.714286
62
0.650362
3.190751
false
false
false
false
bangslosan/TipCalculator
TipCalculator/ViewController.swift
2
1759
// // ViewController.swift // TipCalculator // // Created by Charles Rice on 20/10/2014. // Copyright (c) 2014 Cake Solutions. All rights reserved. // import UIKit class ViewController: UIViewController { //UI Setup and linking @IBOutlet var totalTextField : UITextField! @IBOutlet var taxPctSlider : UISlider! @IBOutlet var taxPctLabel : UILabel! @IBOutlet var resultsTextView : UITextView! @IBAction func calculateTapped(sender : AnyObject) { tipCalc.total = Double((totalTextField.text as NSString).doubleValue) let possibleTips = tipCalc.returnPossibleTips() var results = "" for(tipPct, tipValue) in possibleTips { results += "\(tipPct)%: \(tipValue)\n" } resultsTextView.text = results } @IBAction func taxPercentageChanged(sender : AnyObject) { tipCalc.taxPct = Double(taxPctSlider.value) / 100.0 refreshUI() } @IBAction func viewTapped(sender : AnyObject) { totalTextField.resignFirstResponder() } //Everything else let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06) func refreshUI(){ totalTextField.text = String(format: "%0.2f", tipCalc.total) taxPctSlider.value = Float(tipCalc.taxPct) * 100.0 taxPctLabel.text = "Tax Percentage (\(Int(taxPctSlider.value))%)" resultsTextView.text = "" } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refreshUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
89fa86d04b06e463b65f009d2d2c8faa
27.852459
80
0.640136
4.641161
false
false
false
false
yarshure/Surf
Surf/DebugViewController.swift
1
3603
// // DebugViewController.swift // Surf // // Created by networkextension on 7/18/16. // Copyright © 2016 yarshure. All rights reserved. // import UIKit class DebugViewController: SFTableViewController { let config:[String] = ["DNS","WI-FI","CELL"] var dns:[String] = [] override func viewDidLoad() { super.viewDidLoad() let edit = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(DebugViewController.loadXX(_:))) navigationItem.rightBarButtonItem = edit // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } func loadXX(_ sender:AnyObject){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return config.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "debug", for: indexPath) // Configure the cell... cell.textLabel?.text = config[indexPath.row] switch indexPath.row { case 0: cell.detailTextLabel?.text = "" default: break } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
3e581a0ac00cd5b00ed6f0fb8a8623aa
32.981132
157
0.665741
5.328402
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift
66
1738
import Foundation /// A Nimble matcher that succeeds when the actual value is less than the expected value. public func beLessThan<T: Comparable>(_ expectedValue: T?) -> Predicate<T> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" if let actual = try actualExpression.evaluate(), let expected = expectedValue { return actual < expected } return false }.requireNonNil } /// A Nimble matcher that succeeds when the actual value is less than the expected value. public func beLessThan(_ expectedValue: NMBComparable?) -> Predicate<NMBComparable> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" let actualValue = try actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedAscending return matches }.requireNonNil } public func <<T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beLessThan(rhs)) } public func < (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) { lhs.to(beLessThan(rhs)) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func beLessThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let expr = actualExpression.cast { $0 as? NMBComparable } return try! beLessThan(expected).matches(expr, failureMessage: failureMessage) } } } #endif
mit
b4d2ef9b425839b187bed78676995704
41.390244
120
0.708861
4.9375
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/Browser/LoginsHelper.swift
2
8700
/* 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 Storage import XCGLogger import WebKit import Deferred import SwiftyJSON private let log = Logger.browserLogger class LoginsHelper: TabContentScript { fileprivate weak var tab: Tab? fileprivate let profile: Profile fileprivate var snackBar: SnackBar? // Exposed for mocking purposes var logins: BrowserLogins { return profile.logins } class func name() -> String { return "LoginsHelper" } required init(tab: Tab, profile: Profile) { self.tab = tab self.profile = profile } func scriptMessageHandlerName() -> String? { return "loginsManagerMessageHandler" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard var res = message.body as? [String: AnyObject] else { return } guard let type = res["type"] as? String else { return } // Check to see that we're in the foreground before trying to check the logins. We want to // make sure we don't try accessing the logins database while we're backgrounded to avoid // the system from terminating our app due to background disk access. // // See https://bugzilla.mozilla.org/show_bug.cgi?id=1307822 for details. guard UIApplication.shared.applicationState == .active && !profile.isShutdown else { return } // We don't use the WKWebView's URL since the page can spoof the URL by using document.location // right before requesting login data. See bug 1194567 for more context. if let url = message.frameInfo.request.url { // Since responses go to the main frame, make sure we only listen for main frame requests // to avoid XSS attacks. if message.frameInfo.isMainFrame && type == "request" { res["username"] = "" as AnyObject? res["password"] = "" as AnyObject? if let login = Login.fromScript(url, script: res), let requestId = res["requestId"] as? String { requestLogins(login, requestId: requestId) } } else if type == "submit" { if self.profile.prefs.boolForKey("saveLogins") ?? true { if let login = Login.fromScript(url, script: res) { setCredentials(login) } } } } } class func replace(_ base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString { var ranges = [NSRange]() var string = base for (index, key) in keys.enumerated() { let replace = replacements[index] let range = string.range(of: key, options: .literal, range: nil, locale: nil)! string.replaceSubrange(range, with: replace) let nsRange = NSRange(location: string.distance(from: string.startIndex, to: range.lowerBound), length: replace.count) ranges.append(nsRange) } var attributes = [String: AnyObject]() attributes[NSFontAttributeName] = UIFont.systemFont(ofSize: 13, weight: UIFontWeightRegular) attributes[NSForegroundColorAttributeName] = UIColor.darkGray let attr = NSMutableAttributedString(string: string, attributes: attributes) let font: UIFont = UIFont.systemFont(ofSize: 13, weight: UIFontWeightMedium) for range in ranges { attr.addAttribute(NSFontAttributeName, value: font, range: range) } return attr } func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> { return profile.logins.getLoginsForProtectionSpace(protectionSpace) } func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success { return profile.logins.updateLoginByGUID(guid, new: new, significant: significant) } func setCredentials(_ login: LoginData) { if login.password.isEmpty { log.debug("Empty password") return } profile.logins .getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username) .uponQueue(.main) { res in if let data = res.successValue { log.debug("Found \(data.count) logins.") for saved in data { if let saved = saved { if saved.password == login.password { self.profile.logins.addUseOfLoginByGUID(saved.guid) return } self.promptUpdateFromLogin(login: saved, toLogin: login) return } } } self.promptSave(login) } } fileprivate func promptSave(_ login: LoginData) { guard login.isValid.isSuccess else { return } let promptMessage: String if let username = login.username { promptMessage = String(format: Strings.SaveLoginUsernamePrompt, username, login.hostname) } else { promptMessage = String(format: Strings.SaveLoginPrompt, login.hostname) } if let existingPrompt = self.snackBar { tab?.removeSnackbar(existingPrompt) } snackBar = TimerSnackBar(text: promptMessage, img: UIImage(named: "key")) let dontSave = SnackButton(title: Strings.LoginsHelperDontSaveButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.dontSaveButton") { bar in self.tab?.removeSnackbar(bar) self.snackBar = nil return } let save = SnackButton(title: Strings.LoginsHelperSaveLoginButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.saveLoginButton") { bar in self.tab?.removeSnackbar(bar) self.snackBar = nil self.profile.logins.addLogin(login) LeanPlumClient.shared.track(event: .savedLoginAndPassword) } snackBar?.addButton(dontSave) snackBar?.addButton(save) tab?.addSnackbar(snackBar!) } fileprivate func promptUpdateFromLogin(login old: LoginData, toLogin new: LoginData) { guard new.isValid.isSuccess else { return } let guid = old.guid let formatted: String if let username = new.username { formatted = String(format: Strings.UpdateLoginUsernamePrompt, username, new.hostname) } else { formatted = String(format: Strings.UpdateLoginPrompt, new.hostname) } if let existingPrompt = self.snackBar { tab?.removeSnackbar(existingPrompt) } snackBar = TimerSnackBar(text: formatted, img: UIImage(named: "key")) let dontSave = SnackButton(title: Strings.LoginsHelperDontSaveButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.dontSaveButton") { bar in self.tab?.removeSnackbar(bar) self.snackBar = nil return } let update = SnackButton(title: Strings.LoginsHelperUpdateButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.updateButton") { bar in self.tab?.removeSnackbar(bar) self.snackBar = nil self.profile.logins.updateLoginByGUID(guid, new: new, significant: new.isSignificantlyDifferentFrom(old)) } snackBar?.addButton(dontSave) snackBar?.addButton(update) tab?.addSnackbar(snackBar!) } fileprivate func requestLogins(_ login: LoginData, requestId: String) { profile.logins.getLoginsForProtectionSpace(login.protectionSpace).uponQueue(.main) { res in var jsonObj = [String: Any]() if let cursor = res.successValue { log.debug("Found \(cursor.count) logins.") jsonObj["requestId"] = requestId jsonObj["name"] = "RemoteLogins:loginsFound" jsonObj["logins"] = cursor.map { $0!.toDict() } } let json = JSON(jsonObj) let src = "window.__firefox__.logins.inject(\(json.stringValue()!))" self.tab?.webView?.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in }) } } }
mpl-2.0
8012fa769cb07e1e3781672edef19ec7
38.908257
152
0.609885
5.111633
false
false
false
false
xedin/swift
test/expr/cast/as_coerce.swift
5
5965
// RUN: %target-typecheck-verify-swift -enable-objc-interop // Test the use of 'as' for type coercion (which requires no checking). @objc protocol P1 { func foo() } class A : P1 { @objc func foo() { } } @objc class B : A { func bar() { } } func doFoo() {} func test_coercion(_ a: A, b: B) { // Coercion to a protocol type let x = a as P1 x.foo() // Coercion to a superclass type let y = b as A y.foo() } class C : B { } class D : C { } func prefer_coercion(_ c: inout C) { let d = c as! D c = d } // Coerce literals var i32 = 1 as Int32 var i8 = -1 as Int8 // Coerce to a superclass with generic parameter inference class C1<T> { func f(_ x: T) { } } class C2<T> : C1<Int> { } var c2 = C2<()>() var c1 = c2 as C1 c1.f(5) @objc protocol P {} class CC : P {} let cc: Any = CC() if cc is P { doFoo() } if let p = cc as? P { doFoo() _ = p } // Test that 'as?' coercion fails. let strImplicitOpt: String! = nil _ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}} class C3 {} class C4 : C3 {} class C5 {} var c: AnyObject = C3() if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}} // Only suggest replacing 'as' with 'as!' if it would fix the error. C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}} C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}} // Diagnostic shouldn't include @lvalue in type of c3. var c3 = C3() c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}} // <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions 1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}} 1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} ["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}} ([1, 2, 1.0], 1) as ([String], Int) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} // expected-error@-2 {{cannot convert value of type 'Double' to expected element type 'String'}} [[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} (1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}} (1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} (1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} _ = [1] as! [String] // expected-warning{{cast from '[Int]' to unrelated type '[String]' always fails}} _ = [(1, (1, 1))] as! [(Int, (String, Int))] // expected-warning{{cast from '[(Int, (Int, Int))]' to unrelated type '[(Int, (String, Int))]' always fails}} // <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type _ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}} // <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its func f(_ x : String) {} f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}} f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} // <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests let s : AnyObject = C3() s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}} // SR-6022 func sr6022() -> Any { return 0 } func sr6022_1() { return; } protocol SR6022_P {} _ = sr6022 as! SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{11-11=()}} _ = sr6022 as? SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'}}{{11-11=()}} _ = sr6022_1 as! SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}} _ = sr6022_1 as? SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}} func testSR6022_P<T: SR6022_P>(_: T.Type) { _ = sr6022 as! T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}} _ = sr6022 as? T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}} _ = sr6022_1 as! T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} _ = sr6022_1 as? T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} } func testSR6022_P_1<U>(_: U.Type) { _ = sr6022 as! U // Okay _ = sr6022 as? U // Okay _ = sr6022_1 as! U // Okay _ = sr6022_1 as? U // Okay } _ = sr6022 as! AnyObject // expected-warning {{forced cast from '() -> Any' to 'AnyObject' always succeeds; did you mean to use 'as'?}} _ = sr6022 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}} _ = sr6022_1 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}} _ = sr6022_1 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}}
apache-2.0
9215b184163f6475dfef7a668f91bb31
42.540146
185
0.642414
3.149419
false
false
false
false
xedin/swift
test/SILGen/indirect_enum.swift
8
25604
// RUN: %target-swift-emit-silgen -module-name indirect_enum -Xllvm -sil-print-debuginfo %s | %FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () { func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $TreeA<T>, [[ARG3:%.*]] : @guaranteed $TreeA<T>): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[T_BUF]] : $*T // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK-NEXT: dealloc_stack [[T_BUF]] : $*T let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeA<T>.Branch(left: l, right: r) } // CHECK: // end sil function '$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () { func TreeA_reabstract(_ f: @escaping (Int) -> Int) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK: [[THUNK:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]]) // CHECK-NEXT: store [[FN]] to [init] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[LEAF]] // CHECK: return let _ = TreeA<(Int) -> Int>.Leaf(f) } // CHECK: } // end sil function '$s13indirect_enum16TreeA_reabstractyyS2icF' enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[T_BUF]] // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1 // CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] // CHECK-NEXT: dealloc_stack [[T_BUF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[ARG1_COPY:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: copy_addr %1 to [initialization] [[ARG1_COPY]] : $*TreeB<T> // CHECK-NEXT: [[ARG2_COPY:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: copy_addr %2 to [initialization] [[ARG2_COPY]] : $*TreeB<T> // CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr [take] [[ARG1_COPY]] to [initialization] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr [take] [[ARG2_COPY]] to [initialization] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1 // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] // CHECK-NEXT: dealloc_stack [[ARG2_COPY]] // CHECK-NEXT: dealloc_stack [[ARG1_COPY]] let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> () func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) { // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed $TreeInt, [[ARG3:%.*]] : @guaranteed $TreeInt): // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NOT: destroy_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, [[ARG1]] // CHECK-NOT: destroy_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $TreeInt // CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] : $TreeInt // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]] // CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: destroy_value [[BRANCH]] let _ = TreeInt.Branch(left: l, right: r) } // CHECK: } // end sil function '$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF' enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(_ x: T) {} func c<T>(_ x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () { func switchTreeA<T>(_ x: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): // -- x +0 // CHECK: switch_enum [[ARG]] : $TreeA<T>, // CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]], // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE:bb2]], // CHECK: case #TreeA.Branch!enumelt.1: [[BRANCH_CASE:bb3]], switch x { // CHECK: [[NIL_CASE]]: // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +0 // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : @guaranteed $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]] // CHECK: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: switch_enum [[LEFT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]], // CHECK: default [[FAIL_LEFT:bb[0-9]+]] // CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: switch_enum [[RIGHT]] : $TreeA<T>, // CHECK: case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]], // CHECK: default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_RIGHT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_LEFT]]([[DEFAULT_VAL:%.*]] : @guaranteed // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +0 default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 } // CHECK: } // end sil function '$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F func switchTreeB<T>(_ x: TreeB<T>) { // CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: function_ref @$s13indirect_enum1ayyF // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] : // CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] : // CHECK: function_ref @$s13indirect_enum1c{{[_0-9a-zA-Z]*}}F // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // -- box +0 // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[RIGHT_FAIL]]: // CHECK: destroy_addr [[LEFT_LEAF]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_value [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: function_ref @$s13indirect_enum1dyyF // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: return } // Make sure that switchTreeInt obeys ownership invariants. // // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F func switchTreeInt(_ x: TreeInt) { switch x { case .Nil: a() case .Leaf(let x): b(x) case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) default: d() } } // CHECK: } // end sil function '$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F func guardTreeA<T>(_ tree: TreeA<T>) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>): do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO1:bb[0-9]+]] // CHECK: [[YES]]: guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO4:bb[0-9]+]] // CHECK: [[NO4]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]: // CHECK: br if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO5:bb[0-9]+]] // CHECK: [[NO5]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]] // CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]] // CHECK: end_borrow [[TUPLE]] // CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_value [[R]] // CHECK: destroy_value [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO2]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: [[NO1]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>): // CHECK: destroy_value [[ORIGINAL_VALUE]] } // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F func guardTreeB<T>(_ tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [initialization] [[TMP1:%.*]] : // CHECK: switch_enum_addr [[TMP1]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP1]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP2:%.*]] : // CHECK: switch_enum_addr [[TMP2]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP2]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP2]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP3:%.*]] : // CHECK: switch_enum_addr [[TMP3]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP3]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: destroy_value [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } // CHECK: [[NO3]]: // CHECK: destroy_addr [[TMP3]] // CHECK: [[NO2]]: // CHECK: destroy_addr [[TMP2]] // CHECK: [[NO1]]: // CHECK: destroy_addr [[TMP1]] } // Just run guardTreeInt through the ownership verifier // // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum12guardTreeInt{{[_0-9a-zA-Z]*}}F func guardTreeInt(_ tree: TreeInt) { do { guard case .Nil = tree else { return } guard case .Leaf(let x) = tree else { return } guard case .Branch(left: let l, right: let r) = tree else { return } } do { if case .Nil = tree { } if case .Leaf(let x) = tree { } if case .Branch(left: let l, right: let r) = tree { } } } // SEMANTIC ARC TODO: This test needs to be made far more comprehensive. // CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () { func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $TrivialButIndirect): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt.1: [[NO:bb[0-9]+]] // guard case .Direct(let foo) = x else { return } // CHECK: [[YES]]({{%.*}} : $Int): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt.1: [[NO2:bb[0-9]+]] // CHECK: [[YES]]([[BOX:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[BOX]] // CHECK: [[NO2]]({{%.*}} : $Int): // CHECK-NOT: destroy_value // CHECK: [[NO]]([[PAYLOAD:%.*]] : @owned ${ var Int }): // CHECK: destroy_value [[PAYLOAD]] guard case .Indirect(let bar) = x else { return } } // CHECK: } // end sil function '$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF' // Make sure that in these cases we do not break any ownership invariants. class Box<T> { var value: T init(_ inputValue: T) { value = inputValue } } enum ValueWithInlineStorage<T> { case inline(T) indirect case box(Box<T>) } func switchValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) { switch v { case .inline: return case .box(let box): return } } func guardValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) { do { guard case .inline = v else { return } guard case .box(let box) = v else { return } } do { if case .inline = v { return } if case .box(let box) = v { return } } }
apache-2.0
4f026a980a4edd7986f351ebc6889eb5
42.717949
185
0.546979
3.074657
false
false
false
false
iOSDevLog/iOSDevLog
StoreSearch/StoreSearch/AppDelegate.swift
1
2011
// // AppDelegate.swift // StoreSearch // // Created by iosdevlog on 16/2/22. // Copyright © 2016年 iosdevlog. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - property var window: UIWindow? // MARK: - delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { customizeAppearance() detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() searchViewController.splitViewDetail = detailViewController splitViewController.delegate = self return true } // MARK: - helper func customizeAppearance() { let barTintColor = UIColor(red: 20/255, green: 160/255, blue: 160/255, alpha: 1) UISearchBar.appearance().barTintColor = barTintColor window!.tintColor = UIColor(red: 10/255, green: 80/255, blue: 80/255, alpha: 1) } var splitViewController: UISplitViewController { return window!.rootViewController as! UISplitViewController } var searchViewController: SearchViewController { return splitViewController.viewControllers.first as! SearchViewController } var detailNavigationController: UINavigationController { return splitViewController.viewControllers.last as! UINavigationController } var detailViewController: DetailViewController { return detailNavigationController.topViewController as! DetailViewController } } // MARK: - UISplitViewControllerDelegate extension AppDelegate: UISplitViewControllerDelegate { func splitViewController(svc: UISplitViewController, willChangeToDisplayMode displayMode: UISplitViewControllerDisplayMode) { print(__FUNCTION__) if displayMode == .PrimaryOverlay { svc.dismissViewControllerAnimated(true, completion: nil) } } }
mit
dec4eb5572b1046c8cdd74a38568f534
32.466667
129
0.712151
5.871345
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Objects/Project/PBXOutputSettings.swift
1
6089
import Foundation /// Code for controlling sorting of files in an pbxproj file. // MARK: - Core sort functions // Because of the number of optional data items in PBXBuildFiles, we've externalised the core code in these two functions. // Note, PBXBuildFile's contains PBXFileElements so this first function is an optional handling wrapper driving the second. // Also note that we use the .fileName() function to retrieve the name as both .path and .name properties can be nil. private func sortUsingNames(_ lhs: PBXBuildFile, _ rhs: PBXBuildFile) -> Bool { if let lhsFile = lhs.file, let rhsFile = rhs.file { return sortUsingNames(lhsFile, rhsFile) } return lhs.uuid < rhs.uuid } private func sortUsingNames(_ lhs: PBXFileElement, _ rhs: PBXFileElement) -> Bool { if let lhsFilename = lhs.fileName(), let rhsFilename = rhs.fileName() { return lhsFilename == rhsFilename ? lhs.uuid < rhs.uuid : lhsFilename < rhsFilename } return lhs.uuid < rhs.uuid } // MARK: - Sorting enums /// Defines the sorting applied to files within the file lists. Defaults to by UUID. public enum PBXFileOrder { /// Sort files by Xcode's UUID case byUUID /// Sort files by their file name. This is a case sensistive sort with lower case names coming after uppercase names. case byFilename internal func sort<Object>(lhs: (PBXObjectReference, Object), rhs: (PBXObjectReference, Object)) -> Bool where Object: PlistSerializable & Equatable { lhs.0 < rhs.0 } internal func sort(lhs: (PBXObjectReference, PBXBuildFile), rhs: (PBXObjectReference, PBXBuildFile)) -> Bool { switch self { case .byFilename: return sortUsingNames(lhs.1, rhs.1) default: return lhs.0 < rhs.0 } } internal func sort(lhs: (PBXObjectReference, PBXBuildPhaseFile), rhs: (PBXObjectReference, PBXBuildPhaseFile)) -> Bool { switch self { case .byFilename: return sortUsingNames(lhs.1.buildFile, rhs.1.buildFile) default: return lhs.0 < rhs.0 } } internal func sort(lhs: (PBXObjectReference, PBXFileReference), rhs: (PBXObjectReference, PBXFileReference)) -> Bool { switch self { case .byFilename: return sortUsingNames(lhs.1, rhs.1) default: return lhs.0 < rhs.0 } } } private extension PBXFileElement { var isGroup: Bool { switch self { case is PBXVariantGroup, is XCVersionGroup: return false case is PBXGroup: return true default: return false } } } /// Defines the sorting applied to groups with the project navigator and various build phases. public enum PBXNavigatorFileOrder { /// Leave the files unsorted. case unsorted /// Sort the file by their file name. This is a case sensitive sort with uppercase name preceeding lowercase names. case byFilename /// Sorts the files by their file names with all groups appear at the top of the list. case byFilenameGroupsFirst internal var sort: ((PBXFileElement, PBXFileElement) -> Bool)? { switch self { case .byFilename: return { sortUsingNames($0, $1) } case .byFilenameGroupsFirst: return { lhs, rhs in let lhsIsGroup = lhs.isGroup if lhsIsGroup != rhs.isGroup { return lhsIsGroup } return sortUsingNames(lhs, rhs) } default: return nil // Don't sort. } } } /// Defines the sorting of file within a build phase. public enum PBXBuildPhaseFileOrder { /// Leave the files unsorted. case unsorted /// Sort the files by their file name. This is a case sensitive sort with uppercase names appearing before lowercase names. case byFilename internal var sort: ((PBXBuildFile, PBXBuildFile) -> Bool)? { switch self { case .byFilename: return { lhs, rhs in sortUsingNames(lhs, rhs) } default: return nil // Don't sort. } } } /// Defines the format of project file references public enum PBXReferenceFormat { /// Adds prefix and suffix characters to the references. /// The prefix characters identify the type of reference generated (e.g. BP for Build Phase). /// The suffix number is only added for uniqueness if clashes occur. case withPrefixAndSuffix /// Standard 24 char format that XCode generates. /// Note: Not guaranteed to be the same as XCode generates - only the format is the same. case xcode } /// Struct of output settings passed to various methods. public struct PBXOutputSettings { /// The sorting order for the list of files in Xcode's project file. let projFileListOrder: PBXFileOrder /// The sort order for files and groups that appear in the Xcode Project Navigator. let projNavigatorFileOrder: PBXNavigatorFileOrder /// The sort order for lists of files in build phases. let projBuildPhaseFileOrder: PBXBuildPhaseFileOrder /// The format of project file references let projReferenceFormat: PBXReferenceFormat /** Default initializer - Parameter projFileListOrder: Defines the sort order for internal file lists in the project file. - Parameter projNavigatorFileOrder: Defines the order of files in the project navigator groups. - Parameter projBuildPhaseFileOrder: Defines the sort order of files in build phases. */ public init(projFileListOrder: PBXFileOrder = .byUUID, projNavigatorFileOrder: PBXNavigatorFileOrder = .unsorted, projBuildPhaseFileOrder: PBXBuildPhaseFileOrder = .unsorted, projReferenceFormat: PBXReferenceFormat = .xcode) { self.projFileListOrder = projFileListOrder self.projNavigatorFileOrder = projNavigatorFileOrder self.projBuildPhaseFileOrder = projBuildPhaseFileOrder self.projReferenceFormat = projReferenceFormat } }
mit
1ef283fedb8e1a9d9d8a645ae9fdf099
34.401163
127
0.669897
4.609387
false
false
false
false
ovenbits/Alexandria
Sources/String+Extensions.swift
1
11563
// // String+Extensions.swift // // Created by Jonathan Landon on 4/15/15. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation extension String { /// Converts self to an unsigned byte array. public var bytes: [UInt8] { return utf8.map { $0 } } /** Converts string to camel-case. Examples: ``` "os version".camelCasedString // "osVersion" "HelloWorld".camelCasedString // "helloWorld" "someword With Characters".camelCasedString // "somewordWithCharacters" ``` */ public var camelCased: String { guard !characters.isEmpty else { return self } if characters.contains(" ") { let first = self[0].lowercased() let cammel = capitalized.replacingOccurrences(of: " ", with: "") let rest = String(cammel.characters.dropFirst()) return first + rest } else { let first = self[0].lowercased() let rest = String(characters.dropFirst()) return first + rest } } /** The base64 encoded version of self. Credit: http://stackoverflow.com/a/29365954 */ public var base64Encoded: String? { let utf8str = data(using: .utf8) return utf8str?.base64EncodedString() } /** The decoded value of a base64 encoded string Credit: http://stackoverflow.com/a/29365954 */ public var base64Decoded: String? { guard let data = Data(base64Encoded: self, options: []) else { return nil } return String(data: data, encoding: .utf8) } /** Returns true if every character within the string is a numeric character. Empty strings are considered non-numeric. */ public var isNumeric: Bool { guard !isEmpty else { return false } return trimmingCharacters(in: .decimalDigits).isEmpty } /** Replaces all occurences of the pattern on self in-place. Examples: ``` "hello".regexInPlace("[aeiou]", "*") // "h*ll*" "hello".regexInPlace("([aeiou])", "<$1>") // "h<e>ll<o>" ``` */ public mutating func formRegex(_ pattern: String, _ replacement: String) { do { let expression = try NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: characters.count) self = expression.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement) } catch { return } } /** Returns a string containing replacements for all pattern matches. Examples: ``` "hello".regex("[aeiou]", "*") // "h*ll*" "hello".regex("([aeiou])", "<$1>") // "h<e>ll<o>" ``` */ public func regex(_ pattern: String, _ replacement: String) -> String { var replacementString = self replacementString.formRegex(pattern, replacement) return replacementString } /** Replaces pattern-matched strings, operated upon by a closure, on self in-place. - parameter pattern: The pattern to match against. - parameter matches: The closure in which to handle matched strings. Example: ``` "hello".regexInPlace(".") { let s = $0.unicodeScalars let v = s[s.startIndex].value return "\(v) " } // "104 101 108 108 111 " */ public mutating func formRegex(_ pattern: String, _ matches: (String) -> String) { let expression: NSRegularExpression do { expression = try NSRegularExpression(pattern: "(\(pattern))", options: []) } catch { print("regex error: \(error)") return } let range = NSMakeRange(0, self.characters.count) var startOffset = 0 let results = expression.matches(in: self, options: [], range: range) for result in results { var endOffset = startOffset for i in 1..<result.numberOfRanges { var resultRange = result.range resultRange.location += startOffset let startIndex = self.index(self.startIndex, offsetBy: resultRange.location) let endIndex = self.index(self.startIndex, offsetBy: resultRange.location + resultRange.length) let replacementRange = startIndex ..< endIndex let match = expression.replacementString(for: result, in: self, offset: startOffset, template: "$\(i)") let replacement = matches(match) self.replaceSubrange(replacementRange, with: replacement) endOffset += replacement.characters.count - resultRange.length } startOffset = endOffset } } /** Returns a string with pattern-matched strings, operated upon by a closure. - parameter pattern: The pattern to match against. - parameter matches: The closure in which to handle matched strings. - returns: String containing replacements for the matched pattern. Example: ``` "hello".regex(".") { let s = $0.unicodeScalars let v = s[s.startIndex].value return "\(v) " } // "104 101 108 108 111 " */ public func regex(_ pattern: String, _ matches: (String) -> String) -> String { var replacementString = self replacementString.formRegex(pattern, matches) return replacementString } /// Substring at index public subscript(i: Int) -> String { return String(self[index(startIndex, offsetBy: i)]) } /// Substring for range public subscript(r: Range<Int>) -> String { return substring(with: index(startIndex, offsetBy: r.lowerBound) ..< index(startIndex, offsetBy: r.upperBound)) } /// Substring for closed range public subscript(r: ClosedRange<Int>) -> String { return substring(with: index(startIndex, offsetBy: r.lowerBound) ..< index(startIndex, offsetBy: r.upperBound + 1)) } /** Truncates the string to length characters, optionally appending a trailing string. If the string is shorter than the required length, then this function is a non-op. - parameter length: The length of string required. - parameter trailing: An optional addition to the end of the string (increasing "length"), such as ellipsis. - returns: The truncated string. Examples: ``` "hello there".truncated(to: 5) // "hello" "hello there".truncated(to: 5, trailing: "...") // "hello..." ``` */ public func truncated(to length: Int, trailing: String = "") -> String { guard !characters.isEmpty && characters.count > length else { return self } return self.substring(to: index(startIndex, offsetBy: length)) + trailing } public mutating func truncate(to length: Int, trailing: String = "") { self = truncated(to: length, trailing: trailing) } /** A bridge for invoking `String.localizedStandardContainsString()`, which is available in iOS 9 and later. If you need to support iOS versions prior to iOS 9, use `compatibleStandardContainsString()` as a means to bridge functionality. If you can support iOS 9 or greater only, use `localizedStandardContainsString()` directly. From Apple's Swift 2.1 documentation: `localizedStandardContainsString()` is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time. - parameter string: The string to determine if is contained by self. - returns: Returns true if self contains string, taking the current locale into account. */ public func compatibleStandardContains(_ string: String) -> Bool { if #available(iOS 9.0, *) { return localizedStandardContains(string) } return range(of: string, options: [.caseInsensitive, .diacriticInsensitive], locale: .current) != nil } /** Convert an NSRange to a Range. There is still a mismatch between the regular expression libraries and NSString/String. This makes it easier to convert between the two. Using this allows complex strings (including emoji, regonial indicattors, etc.) to be manipulated without having to resort to NSString instances. Note that it may not always be possible to convert from an NSRange as they are not exactly the same. Taken from: http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index - parameter nsRange: The NSRange instance to covert to a Range. - returns: The Range, if it was possible to convert. Otherwise nil. */ public func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } /** Convert a Range to an NSRange. There is still a mismatch between the regular expression libraries and NSString/String. This makes it easier to convert between the two. Using this allows complex strings (including emoji, regonial indicattors, etc.) to be manipulated without having to resort to NSString instances. Taken from: http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index - parameter range: The Range instance to conver to an NSRange. - returns: The NSRange converted from the input. This will always succeed. */ public func nsRange(from range: Range<String.Index>) -> NSRange { let from = String.UTF16View.Index(range.lowerBound, within: utf16) let to = String.UTF16View.Index(range.upperBound, within: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to)) } }
mit
750bb2115d8458e55f6c8c2ce832555e
36.3
290
0.635648
4.664381
false
false
false
false
Tuslareb/JBDatePicker
JBDatePicker/Classes/JBDatePickerManager.swift
1
10086
// // JBDatePickerManager.swift // JBDatePicker // // Created by Joost van Breukelen on 12-10-16. // Copyright © 2016 Joost van Breukelen. All rights reserved. // import UIKit final class JBDatePickerManager { // MARK: - Properties private var components: DateComponents private unowned let datePickerView: JBDatePickerView private var calendar: Calendar = .current private var currentDate: Date = Date() private var startdayOfWeek: Int // MARK: - Initialization init(datePickerView: JBDatePickerView) { self.datePickerView = datePickerView self.components = calendar.dateComponents([.month, .day], from: currentDate) startdayOfWeek = (datePickerView.delegate?.firstWeekDay.rawValue)! //let user preference prevail about default calendar.firstWeekday = startdayOfWeek } // MARK: - Date information /** Gets the startdate and the enddate of the month of a certain date and also the amount of weeks for that month and all the days with their weekViewIndex and value - Parameter date: the Date object of the month that we want the info about - Returns: a tuple holding the startdate, the enddate, the number of weeks and an array holding dictionaries with the weekDayIndex as key and a JBDay object as value. The JBDay object holds the value (like 17) and a bool that determines that the day involved is included in the month or not. */ func getMonthInfoForDate(_ date: Date) -> (monthStartDay: Date, monthEndDay: Date, numberOfWeeksInMonth: Int, weekDayInfo: [[Int:JBDay]]) { var components = calendar.dateComponents([.year, .month, .weekOfMonth], from: date) //first day of the month components.day = 1 let monthValue = components.month! let yearValue = components.year! let monthStartDay = calendar.date(from: components)! //last day of the month components.month! += 1 let nextMonthValue = components.month! let nextYearValue = components.year! components.day! -= 1 let monthEndDay = calendar.date(from: components)! //reset components components = calendar.dateComponents([.year, .month, .weekOfMonth], from: date) //last day of the previous month. We have to substract two because we went up to get the next month components.month! -= 1 let previousMonthEndDay = calendar.date(from: components)! let previousMonthValue = components.month! let previousYearValue = components.year! //count of weeks in month var numberOfWeeksInMonth: Int = calendar.range(of: .weekOfMonth, in: .month, for: date)!.count //get dates that fall within the month let datesInRange = calendar.range(of: .day, in: .month, for: date) var monthDatesArray = [Int]() for value in 1..<datesInRange!.upperBound { monthDatesArray.append(value) } //find weekday index of first- and lastDay of month in their week. let firstDayIndexInWeekView = indexForDate(calendar.dateComponents([.weekday], from: monthStartDay).weekday!) let lastDayIndexInWeekView = indexForDate(calendar.dateComponents([.weekday], from: monthEndDay).weekday!) //get dates that fall within next month var nextMonthDatesArray = [Int]() let numberOfDaysInNextMonth = 6 - lastDayIndexInWeekView if numberOfDaysInNextMonth > 0 { for value in 1...numberOfDaysInNextMonth { nextMonthDatesArray.append(value) } } //get dates that fall within previous month var previousMonthDatesArray = [Int]() let datesInRangeOfPreviousMonth = calendar.range(of: .day, in: .month, for: previousMonthEndDay) let numberOfDaysInPreviousMonth = 7 - (7 - firstDayIndexInWeekView) let subRangeLowerBound = (datesInRangeOfPreviousMonth?.upperBound)! - numberOfDaysInPreviousMonth let upperBound = (datesInRangeOfPreviousMonth?.upperBound)! if subRangeLowerBound < upperBound { for value in subRangeLowerBound..<upperBound { previousMonthDatesArray.append(value) } } //if the total amount of dates is larger then the amount of weeks * 7, give an extra week if monthDatesArray.count + previousMonthDatesArray.count + nextMonthDatesArray.count > numberOfWeeksInMonth * 7 { numberOfWeeksInMonth += 1 } //create array of dictionaries that we well return in the end var weeksInMonthInformationToReturn = [[Int:JBDay]]() //this value holds 0 to the number of days in a month var dayOfMonthIndex: Int = 0 for weekIndex in 0..<numberOfWeeksInMonth { //this value holds 0 to 6 (the index of the day in the week) var dayOfWeekIndex: Int = 0 switch weekIndex { case 0: var weekInformationToReturn = [Int:JBDay]() //get the last days of the previous month for i in 0..<previousMonthDatesArray.count { let dayInPreviousMonthValue = previousMonthDatesArray[i] let dayInPreviousMonth = JBDay(dayValue: dayInPreviousMonthValue, monthValue: previousMonthValue, yearValue: previousYearValue, isInMonth: false) weekInformationToReturn[i] = dayInPreviousMonth } //get the first days of the month let amountOfFirstDays = 7 - firstDayIndexInWeekView guard amountOfFirstDays >= 1 else {continue} dayOfWeekIndex = firstDayIndexInWeekView for _ in 0..<amountOfFirstDays { let dayInFirstWeekOfMonth = monthDatesArray[dayOfMonthIndex] let dayInWeek = JBDay(dayValue: dayInFirstWeekOfMonth, monthValue: monthValue, yearValue: yearValue, isInMonth: true) weekInformationToReturn[dayOfWeekIndex] = dayInWeek dayOfWeekIndex += 1 dayOfMonthIndex += 1 } weeksInMonthInformationToReturn.append(weekInformationToReturn) case numberOfWeeksInMonth - 1: var weekInformationToReturn = [Int:JBDay]() //get the last days of the month let amountOfLastDays = 7 - (6 - lastDayIndexInWeekView) guard dayOfMonthIndex < monthDatesArray.count else { //remove unnecessary week line numberOfWeeksInMonth -= 1 continue } for _ in 0..<amountOfLastDays { let dayInLastWeekOfMonth = monthDatesArray[dayOfMonthIndex] let dayInWeek = JBDay(dayValue: dayInLastWeekOfMonth, monthValue: monthValue, yearValue: yearValue, isInMonth: true) weekInformationToReturn[dayOfWeekIndex] = dayInWeek dayOfWeekIndex += 1 dayOfMonthIndex += 1 } //get the first days of the next month for i in 0..<nextMonthDatesArray.count { let dayInNextMontValue = nextMonthDatesArray[i] let dayInNextMonth = JBDay(dayValue: dayInNextMontValue, monthValue: nextMonthValue, yearValue: nextYearValue, isInMonth: false) weekInformationToReturn[dayOfWeekIndex + i] = dayInNextMonth } weeksInMonthInformationToReturn.append(weekInformationToReturn) default: //this is the default case (the 'middle weeks') guard dayOfMonthIndex < monthDatesArray.count else {continue} var weekInformationToReturn = [Int:JBDay]() for _ in 0...6 { let dayInWeekOfMonth = monthDatesArray[dayOfMonthIndex] let dayInWeek = JBDay(dayValue: dayInWeekOfMonth, monthValue: monthValue, yearValue: yearValue, isInMonth: true) weekInformationToReturn[dayOfWeekIndex] = dayInWeek dayOfWeekIndex += 1 dayOfMonthIndex += 1 } weeksInMonthInformationToReturn.append(weekInformationToReturn) } } return (monthStartDay, monthEndDay, numberOfWeeksInMonth, weeksInMonthInformationToReturn) } // MARK: - Helpers private func basicComponentsForDate(_ date: Date) -> DateComponents { return calendar.dateComponents([.year, .month, .weekOfMonth, .day], from: date) } /** This is a correctionFactor. A day that falls on a thursday will always have weekday 5. Sunday is 1, Saterday is 7. However, in the weekView, this will be indexnumber 4 when week starts at sunday, and indexnumber 3 when week starts on a monday. If the week was to start on a thursday, the correctionfactor will be 5. Because this day will get index 0 in the weekView in that case. The function basically returns this dictionary: [-6:1, -5:2, -4:3, -3:4, -2:5, -1:6, 0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6] */ private func indexForDate(_ weekDay: Int) -> Int { let basicIndex = weekDay - startdayOfWeek if basicIndex < 0 { return basicIndex + 7 } else{ return basicIndex } } }
mit
14a22a7dea853b7b1829607a31ad2251
40.673554
385
0.595439
5.230809
false
false
false
false
wfleming/SwiftLint
Source/SwiftLintFramework/Rules/TrailingSemicolonRule.swift
2
2857
// // TrailingSemiColonRule.swift // SwiftLint // // Created by JP Simard on 2015-11-17. // Copyright (c) 2015 Realm. All rights reserved. // import Foundation import SourceKittenFramework extension File { private func violatingTrailingSemicolonRanges() -> [NSRange] { return matchPattern("(;+([^\\S\\n]?)*)+;?$", excludingSyntaxKinds: SyntaxKind.commentAndStringKinds()) } } public struct TrailingSemicolonRule: CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.Warning) public init() {} public static let description = RuleDescription( identifier: "trailing_semicolon", name: "Trailing Semicolon", description: "Lines should not have trailing semicolons.", nonTriggeringExamples: [ "let a = 0\n" ], triggeringExamples: [ "let a = 0↓;\n", "let a = 0↓;\nlet b = 1\n", "let a = 0↓;;\n", "let a = 0↓; ;;\n", "let a = 0↓; ; ;\n" ], corrections: [ "let a = 0;\n": "let a = 0\n", "let a = 0;\nlet b = 1\n": "let a = 0\nlet b = 1\n", "let a = 0;;\n": "let a = 0\n", "let a = 0; ;;\n": "let a = 0\n", "let a = 0; ; ;\n": "let a = 0\n" ] ) public func validateFile(file: File) -> [StyleViolation] { return file.violatingTrailingSemicolonRanges().map { StyleViolation(ruleDescription: self.dynamicType.description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correctFile(file: File) -> [Correction] { let violatingRanges = file.ruleEnabledViolatingRanges( file.violatingTrailingSemicolonRanges(), forRule: self ) let adjustedRanges = violatingRanges.reduce([NSRange]()) { adjustedRanges, element in let adjustedLocation = element.location - adjustedRanges.count let adjustedRange = NSRange(location: adjustedLocation, length: element.length) return adjustedRanges + [adjustedRange] } if adjustedRanges.isEmpty { return [] } var correctedContents = file.contents for range in adjustedRanges { if let indexRange = correctedContents.nsrangeToIndexRange(range) { correctedContents = correctedContents .stringByReplacingCharactersInRange(indexRange, withString: "") } } file.write(correctedContents) return adjustedRanges.map { Correction(ruleDescription: self.dynamicType.description, location: Location(file: file, characterOffset: $0.location)) } } }
mit
41df8c67aae57e391a3f98c2bcfbf50d
34.5875
93
0.58307
4.434579
false
false
false
false
oisdk/ContiguousDeque
ContiguousDequeTests/ContiguousListSliceTests.swift
1
17766
import XCTest import Foundation @testable import ContiguousDeque internal func makeListSliceTuple<S : SequenceType>(from: S) -> (S, ContiguousListSlice<S.Generator.Element>) { return (from, ContiguousListSlice(from)) } internal func makeListSliceTuple<T>(from: [T]) -> ([T], ContiguousListSlice<T>) { return (from, ContiguousListSlice(from)) } class ContiguousListSliceTests: XCTestCase { func testDebugDesciption() { let expectation = "[1, 2, 3, 4, 5]" let reality = ContiguousListSlice([1, 2, 3, 4, 5]).debugDescription XCTAssert(expectation == reality) } func testArrayLiteralConvertible() { let expectation = [2, 3, 4, 5, 6] let reality: ContiguousListSlice = [2, 3, 4, 5, 6] XCTAssert(expectation.elementsEqual(reality)) } func testArrayInit() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testDropFirst() { (0...10) .map(randomArray) .map(makeListSliceTuple) .map{ (ar, de) in (ar.dropFirst(), de.dropFirst()) } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testDropFirstN() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...20).map { (ar.dropFirst($0), de.dropFirst($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testDropLast() { (0...10) .map(randomArray) .map(makeListSliceTuple) .map { ($0.0.dropLast(), $0.1.dropLast()) } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testDropLastN() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...20).map { (ar.dropLast($0), de.dropLast($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrefix() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...20).map { (ar.prefix($0), de.prefix($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrefixUpTo() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in ar.indices.map { (ar.prefixUpTo($0), de.prefixUpTo($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrefixUpToNative() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in zip(ar.indices, de.indices).map { (a, d) in (ar.prefixUpTo(a), de.prefixUpTo(d)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrefixThrough() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in ar.indices .dropLast() .map { (ar.prefixThrough($0), de.prefixThrough($0)) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrefixThroughNative() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in zip(ar.indices, de.indices) .dropLast() .map { (a, d) in (ar.prefixThrough(a), de.prefixThrough(d)) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testSuffix() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...20).map { (ar.suffix($0), de.suffix($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testSuffixFrom() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in ar.indices.map { (ar.suffixFrom($0), de.suffixFrom($0)) } } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testSuffixFromNative() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in zip(ar.indices, de.indices).map {(a, d) in (ar.suffixFrom(a), de.suffixFrom(d))}} .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testSplit() { let divr = Int(arc4random_uniform(10)) + 2 let splitFunc = { $0 % divr == 0 } (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in [true, false].flatMap { empties in (0...10).flatMap { zip( ar.split($0, allowEmptySlices: empties, isSeparator: splitFunc), de.split($0, allowEmptySlices: empties, isSeparator: splitFunc)) } } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testIndexing() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in ar.indices .forEach { i in XCTAssert(ar[i] == de[i]) var (array, list) = (ar, de) let n = Int(arc4random_uniform(10000)) (array[i], list[i]) = (n, n) XCTAssert(array.elementsEqual(list)) } } } func testNativeIndexing() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in zip(ar.indices, de.indices) .forEach { (ia, id) in XCTAssert(ar[ia] == de[id]) var (array, list) = (ar, de) let n = Int(arc4random_uniform(10000)) (array[ia], list[id]) = (n, n) XCTAssert(array.elementsEqual(list)) } } } func testCount() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in XCTAssert(ar.count == de.count) } } func testFirst() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in XCTAssert(ar.first == de.first) } } func testLast() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in XCTAssert(ar.last == de.last) } } func testIsEmpty() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in XCTAssert(ar.isEmpty == de.isEmpty) } } func testPopLast() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (var ar, var de) in while let deqEl = de.popLast() { XCTAssert(ar.popLast() == deqEl) XCTAssert(ar.elementsEqual(de)) } } } func testPopFirst() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (var ar, var de) in while let deqEl = de.popFirst() { XCTAssert(ar.popFirst() == deqEl) XCTAssert(ar.elementsEqual(de)) } } } func testReverse() { (0...10) .map(randomArray) .map(makeListSliceTuple) .map { (ar, de) in (ar.reverse(), de.reverse()) } .forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testIndsRange() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in ar.indices.flatMap { start in (start...ar.endIndex).map { end in (ar[start..<end], de[start..<end]) } } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testIndsRangeNative() { let tuples = (0...10) .map(randomArray) .map(makeListSliceTuple) let toTest = tuples .flatMap { (ar, de) in zip(ar.indices, de.indices).flatMap { (aStart, dStart) in zip( (aStart...ar.endIndex), (dStart...de.endIndex) ).map { (aEnd, dEnd) in (ar[aStart..<aEnd], de[dStart..<dEnd]) } } } for (ar, de) in toTest { XCTAssert(ar.elementsEqual(de)) } } func testIndsRangeSet() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in ar.indices.forEach { start in (start...ar.endIndex).forEach { end in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let replacement = randomArray(end - start) array[start..<end] = ArraySlice(replacement) list[start..<end] = ContiguousListSlice(replacement) XCTAssert(array.elementsEqual(list)) } } } } func testIndsRangeSetNative() { let tuples = (0...10) .map(randomArray) .map(makeListSliceTuple) tuples .flatMap { (ar, de) in zip(ar.indices, de.indices).flatMap { (aStart, dStart) in zip( (aStart...ar.endIndex), (dStart...de.endIndex) ).forEach { (aEnd, dEnd) in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let replacement = randomArray(aEnd - aStart) array[aStart..<aEnd] = ArraySlice(replacement) list[dStart..<dEnd] = ContiguousListSlice(replacement) XCTAssert(array.elementsEqual(list)) } } } } func testEmptyInit() { XCTAssert(ContiguousListSlice<Int>().isEmpty) } func testAppend() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...10).map { (n: Int) -> ([Int], ContiguousListSlice<Int>) in var (array, list) = (ar, de) for _ in 0..<n { let x = Int(arc4random_uniform(UInt32.max)) array.append(x) list.append(x) } return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testExtend() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar, de) in (0...10).map { (n: Int) -> ([Int], ContiguousListSlice<Int>) in var (array, list) = (ar, de) for _ in 0..<n { let x = randomArray(Int(arc4random_uniform(8))) array.extend(x) list.extend(x) } return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testInsert() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in (0...ar.endIndex).map { (i: Int) -> ([Int], ContiguousListSlice<Int>) in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let x = Int(arc4random_uniform(UInt32.max)) array.insert(x, atIndex: i) list.insert(x, atIndex: i) return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testInsertNative() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in zip( (0...ar.endIndex), (de.startIndex...de.endIndex) ).map { (i: Int, d: ContiguousListIndex) -> ([Int], ContiguousListSlice<Int>) in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let x = Int(arc4random_uniform(UInt32.max)) array.insert(x, atIndex: i) list.insert(x, atIndex: d) return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testPrepend() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in (0...10).map { (n: Int) -> ([Int], ContiguousListSlice<Int>) in var (array, list) = (ar, de) for _ in 0..<n { let x = Int(arc4random_uniform(UInt32.max)) array = [x] + array list.prepend(x) } return (array, list) } }.forEach { (ar: [Int], de: ContiguousListSlice<Int>) in XCTAssert(ar.elementsEqual(de)) } } func testPrextend() { (0...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in (0...10).map { i in var (array, list) = (ar, de) let x = randomArray(i) array = x + array list.prextend(x) return (array, list) } }.forEach { (ar: [Int], de: ContiguousListSlice<Int>) in XCTAssert(ar.elementsEqual(de)) } } func testRemoveAll() { var list = ContiguousListSlice(randomArray(8)) list.removeAll() XCTAssert(list.isEmpty) } func testRemove() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in ar.indices .forEach { i in var (array, list) = (ar, de) XCTAssert(array.removeAtIndex(i) == list.removeAtIndex(i)) XCTAssert(array.elementsEqual(list)) } } } func testRemoveNative() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in zip(ar.indices, de.indices) .forEach { (i, d) in var (array, list) = (ar, de) XCTAssert(array.removeAtIndex(i) == list.removeAtIndex(d)) XCTAssert(array.elementsEqual(list)) } } } func testRemoveFirst() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (var ar, var de) in while !de.isEmpty { XCTAssert(ar.removeFirst() == de.removeFirst()) XCTAssert(ar.elementsEqual(de)) } } } func testRemoveLast() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (var ar, var de) in while !de.isEmpty { XCTAssert(ar.removeLast() == de.removeLast()) XCTAssert(ar.elementsEqual(de)) } } } func testRemoveFirstN() { (1...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in (0...ar.endIndex).map { (n: Int) -> ([Int], ContiguousListSlice<Int>) in var (array, list) = (ar, de) array.removeFirst(n) list.removeFirst(n) return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de)) } } func testRemoveLastN() { (1...10) .map(randomArray) .map(makeListSliceTuple) .flatMap { (ar: [Int], de: ContiguousListSlice<Int>) in (0...ar.endIndex).map { (n: Int) -> ([Int], ContiguousListSlice<Int>) in var (array, list) = (ar, de) array.removeRange((ar.endIndex - n)..<ar.endIndex) list.removeLast(n) return (array, list) } }.forEach { (ar, de) in XCTAssert(ar.elementsEqual(de), ar.debugDescription + " != " + de.debugDescription) } } func testRemoveRange() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in ar.indices.forEach { start in (start...ar.endIndex).forEach { end in var array: [Int] = ar var list: ContiguousListSlice<Int> = de array.removeRange(start..<end) list.removeRange(start..<end) XCTAssert(array.elementsEqual(list), array.debugDescription + " != " + list.debugDescription) } } } } func testRemoveRangeNative() { let tuples = (0...10) .map(randomArray) .map(makeListSliceTuple) tuples .flatMap { (ar, de) in zip(ar.indices, de.indices).flatMap { (aStart, dStart) in zip( (aStart...ar.endIndex), (dStart...de.endIndex) ).forEach { (aEnd, dEnd) in var array: [Int] = ar var list: ContiguousListSlice<Int> = de array.removeRange(aStart..<aEnd) list.removeRange(dStart..<dEnd) XCTAssert(array.elementsEqual(list)) } } } } func testReplaceRange() { (0...10) .map(randomArray) .map(makeListSliceTuple) .forEach { (ar, de) in ar.indices.forEach { start in (start...ar.endIndex).forEach { end in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let replacement = randomArray(Int(arc4random_uniform(20))) array.replaceRange(start..<end, with: replacement) list.replaceRange(start..<end, with: replacement) XCTAssert(array.elementsEqual(list), array.debugDescription + " != " + list.debugDescription) } } } } func testReplaceRangeNative() { let tuples = (0...10) .map(randomArray) .map(makeListSliceTuple) tuples .flatMap { (ar, de) in zip(ar.indices, de.indices).flatMap { (aStart, dStart) in zip( (aStart...ar.endIndex), (dStart...de.endIndex) ).forEach { (aEnd, dEnd) in var array: [Int] = ar var list: ContiguousListSlice<Int> = de let replacement = randomArray(Int(arc4random_uniform(20))) array.replaceRange(aStart..<aEnd, with: replacement) list.replaceRange(dStart..<dEnd, with: replacement) XCTAssert(array.elementsEqual(list), array.debugDescription + " != " + list.debugDescription) } } } } func testReserveCapacity() { var d = ContiguousListSlice<Int>() d.reserveCapacity(20) } }
mit
171d6ca2e91c3f3cbefc301af2f5910d
25.51791
113
0.530114
3.60146
false
true
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/Common/GLTransformation.swift
1
2524
// // GLTransformation.swift // SwiftGL // // Created by jerry on 2015/5/22. // Copyright (c) 2015年 Scott Bennett. All rights reserved. // import Foundation import SwiftGL import OpenGLES.ES2 public class GLTransformation{ var projectionMatrix = Mat4.identity() var modelViewMatrix = Mat4.identity() public static var instance:GLTransformation! public init() { GLTransformation.instance = self //qubeTest() } public var width:Float! public var height:Float! public func getTransformPercentMatrix(_ left:Float,right:Float,top:Float,bottom:Float)->Mat4 { projectionMatrix = Mat4.ortho(left: left*width, right: right*width, bottom: bottom*height, top:top*height, near: -1, far: 1 ); // this sample uses a constant identity modelView matrix modelViewMatrix = Mat4.identity(); mvpMatrix = projectionMatrix * modelViewMatrix return mvpMatrix } public func resize(_ width:GLint,height:GLint) { self.width = Float(width) self.height = Float(height) //orthoview of full screen, original width mvpMatrix = Mat4.ortho(left: 0, right:self.width, bottom: 0, top:Float(height), near: -1, far: 1 ); // this sample uses a constant identity modelView matrix //modelViewMatrix = Mat4.identity(); //mvpMatrix = projectionMatrix * modelViewMatrix //GLContextBuffer.shader.bind("MVP", MVPMatrix) glViewport(0, 0, GLsizei(width), GLsizei(height)) //print("width and height:\(width) \(height)") //GLShaderBinder.instance.shader.bind("Matrix", projection * Mat4.translate(x: 0, y: 0, z: -5) * modelview) //GLShaderBinder.instance.bindMVP(MVPMatrix) DLog("\(self.width)") //shift half size of screen mvpShiftedMatrix = mvpMatrix * Mat4.translate(Vec2(self.width/2,0)) GLShaderBinder.instance.bindMVPBrush(mvpMatrix) GLShaderBinder.instance.bindMVPRenderTexture(mvpShiftedMatrix) } var mvpShiftedMatrix:Mat4 = Mat4.identity() var mvpMatrix:Mat4 = Mat4.identity() public func calTransformMat(_ translation:Vec2,rotation:Float,scale:Float) { modelview = Mat4.identity()*Mat4.translate(translation) * Mat4.rotateZ(rotation) * Mat4.scale(scale) //GLShaderBinder.instance.bindMVP(MVPMatrix) } var modelview = Mat4.identity() var projection = Mat4.identity() }
mit
4fa68f0f1180bf3ddf3328bf402d7ed3
34.027778
134
0.649485
3.904025
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/Issue.swift
1
4185
// // Issue.swift // Tentacle // // Created by Romain Pouclet on 2016-05-23. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension Repository { /// A request for issues in the repository. /// /// https://developer.github.com/v3/issues/#list-issues-for-a-repository public var issues: Request<[Issue]> { return Request(method: .get, path: "/repos/\(owner)/\(name)/issues") } /// A request for an issue in the repository /// /// https://developer.github.com/v3/issues/#get-a-single-issue public func issue(id: ID<Issue>) -> Request<Issue> { return Request(method: .get, path: "/repos/\(owner)/\(name)/issues/\(id.string)") } } /// An Issue on Github public struct Issue: CustomStringConvertible, ResourceType, Identifiable { public enum State: String, ResourceType { case open = "open" case closed = "closed" } /// The id of the issue public let id: ID<Issue> /// The URL to view this issue in a browser public let url: URL? /// The number of the issue in the repository it belongs to public let number: Int /// The state of the issue, open or closed public let state: State /// The title of the issue public let title: String /// The body of the issue public let body: String /// The author of the issue public let user: UserInfo? /// The labels associated to this issue, if any public let labels: [Label] /// The user assigned to this issue, if any public let assignees: [UserInfo] /// The milestone this issue belongs to, if any public let milestone: Milestone? /// True if the issue has been closed by a contributor public let isLocked: Bool /// The number of comments public let commentCount: Int /// Contains the informations like the diff URL when the issue is a pull-request public let pullRequest: PullRequest? /// The date this issue was closed at, if it ever were public let closedAt: Date? /// The date this issue was created at public let createdAt: Date /// The date this issue was updated at public let updatedAt: Date public var description: String { return title } public init(id: ID<Issue>, url: URL?, number: Int, state: State, title: String, body: String, user: UserInfo, labels: [Label], assignees: [UserInfo], milestone: Milestone?, isLocked: Bool, commentCount: Int, pullRequest: PullRequest?, closedAt: Date?, createdAt: Date, updatedAt: Date) { self.id = id self.url = url self.number = number self.state = state self.title = title self.body = body self.user = user self.milestone = milestone self.isLocked = isLocked self.commentCount = commentCount self.pullRequest = pullRequest self.labels = labels self.assignees = assignees self.closedAt = closedAt self.createdAt = createdAt self.updatedAt = updatedAt } private enum CodingKeys: String, CodingKey { case id case url = "html_url" case number case state case title case body case user case labels case assignees case milestone case isLocked = "locked" case commentCount = "comments" case pullRequest = "pull_request" case closedAt = "closed_at" case createdAt = "created_at" case updatedAt = "updated_at" } } extension Issue: Equatable { public static func ==(lhs: Issue, rhs: Issue) -> Bool { return lhs.id == rhs.id && lhs.url == rhs.url && lhs.number == rhs.number && lhs.state == rhs.state && lhs.title == rhs.title && lhs.body == rhs.body && lhs.isLocked == rhs.isLocked && lhs.commentCount == rhs.commentCount && lhs.createdAt == rhs.createdAt && lhs.updatedAt == rhs.updatedAt && lhs.labels == rhs.labels && lhs.milestone == rhs.milestone && lhs.pullRequest == rhs.pullRequest } }
mit
3e2f73be8f43baf405f32b83990e101e
28.673759
291
0.61066
4.418163
false
false
false
false
ps2/rileylink_ios
NightscoutUploadKit/Models/Treatments/BGCheckNightscoutTreatment.swift
1
1486
// // BGCheckNightscoutTreatment.swift // RileyLink // // Created by Pete Schwamb on 3/10/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class BGCheckNightscoutTreatment: NightscoutTreatment { let glucose: Double let glucoseType: GlucoseType let units: Units public init(timestamp: Date, enteredBy: String, glucose: Double, glucoseType: GlucoseType, units: Units, notes: String? = nil) { self.glucose = glucose self.glucoseType = glucoseType self.units = units super.init(timestamp: timestamp, enteredBy: enteredBy, notes: notes, eventType: .bloodGlucoseCheck) } required public init?(_ entry: [String : Any]) { guard let glucose = entry["glucose"] as? Double, let glucoseTypeRaw = entry["glucoseType"] as? String, let glucoseType = GlucoseType(rawValue: glucoseTypeRaw), let unitsRaw = entry["units"] as? String, let units = Units(rawValue: unitsRaw) else { return nil } self.glucose = glucose self.glucoseType = glucoseType self.units = units super.init(entry) } override public var dictionaryRepresentation: [String: Any] { var rval = super.dictionaryRepresentation rval["glucose"] = glucose rval["glucoseType"] = glucoseType.rawValue rval["units"] = units.rawValue return rval } }
mit
d5948b4959f039a950d93cfc0c0bb8e4
29.306122
132
0.63165
4.446108
false
false
false
false
dduan/swift
stdlib/public/core/EmptyCollection.swift
1
2547
//===--- EmptyCollection.swift - A collection with no elements ------------===// // // 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 // //===----------------------------------------------------------------------===// // // Sometimes an operation is best expressed in terms of some other, // larger operation where one of the parameters is an empty // collection. For example, we can erase elements from an Array by // replacing a subrange with the empty collection. // //===----------------------------------------------------------------------===// /// An iterator that never produces an element. /// /// - SeeAlso: `EmptyCollection<Element>`. public struct EmptyIterator<Element> : IteratorProtocol, Sequence { /// Construct an instance. public init() {} /// Returns `nil`, indicating that there are no more elements. public mutating func next() -> Element? { return nil } } /// A collection whose element type is `Element` but that is always empty. public struct EmptyCollection<Element> : Collection { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Int /// Construct an instance. public init() {} /// Always zero, just like `endIndex`. public var startIndex: Index { return 0 } /// Always zero, just like `startIndex`. public var endIndex: Index { return 0 } /// Returns an empty iterator. /// /// - Complexity: O(1). public func makeIterator() -> EmptyIterator<Element> { return EmptyIterator() } /// Access the element at `position`. /// /// Should never be called, since this collection is always empty. public subscript(position: Index) -> Element { _preconditionFailure("Index out of range") } /// The number of elements (always zero). public var count: Int { return 0 } } @available(*, unavailable, renamed: "EmptyIterator") public struct EmptyGenerator<Element> {} extension EmptyIterator { @available(*, unavailable, renamed: "iterator") public func generate() -> EmptyIterator<Element> { fatalError("unavailable function can't be called") } }
apache-2.0
4d528b145eeab5c2ae16dfa6c0f92246
30.060976
80
0.647821
4.673394
false
false
false
false
PlanTeam/BSON
Sources/BSON/Document/Document+Dictionary.swift
1
9258
import Foundation import NIO extension Document: ExpressibleByDictionaryLiteral { /// Gets all top level keys in this Document public var keys: [String] { var keys = [String]() keys.reserveCapacity(32) var index = 4 while index < storage.readableBytes { guard let typeNum = storage.getInteger(at: index, as: UInt8.self), let type = TypeIdentifier(rawValue: typeNum) else { // If typeNum == 0, end of document return keys } index += 1 guard let length = storage.firstRelativeIndexOf(startingAt: index), let key = storage.getString(at: index, length: length) else { return keys } keys.append(key) index += length + 1 // including null terminator guard skipValue(ofType: type, at: &index) else { return keys } } return keys } public func containsKey(_ key: String) -> Bool { var index = 4 let keyLength = key.utf8.count while index < storage.readableBytes { guard let typeNum = storage.getInteger(at: index, as: UInt8.self), let type = TypeIdentifier(rawValue: typeNum) else { // If typeNum == 0, end of document return false } index += 1 guard let length = storage.firstRelativeIndexOf(startingAt: index) else { return false } if length == keyLength { let isMatchingKey = storage.withUnsafeReadableBytes { pointer in memcmp(pointer.baseAddress! + index, key, length) == 0 } if isMatchingKey { return true } } index += length + 1 // including null terminator guard skipValue(ofType: type, at: &index) else { return false } } return false } /// Tries to extract a value of type `P` from the value at key `key` internal subscript<P: Primitive>(key: String, as type: P.Type) -> P? { return self[key] as? P } /// Creates a new Document from a Dictionary literal public init(dictionaryLiteral elements: (String, Primitive)...) { self.init(elements: elements) } public mutating func append(contentsOf document: Document) { for (key, value) in document { self.appendValue(value, forKey: key) } } public mutating func insert(_ value: Primitive, forKey key: String, at index: Int) { Swift.assert(index <= count, "Value inserted at \(index) exceeds current count of \(count)") var document = Document() var pairs = self.pairs var i = 0 while let pair = pairs.next() { if i == index { document.appendValue(value, forKey: key) } document.appendValue(pair.value, forKey: pair.key) i += 1 } if index == i { document.appendValue(value, forKey: key) } self = document } public mutating func removeValue(forKey key: String) -> Primitive? { if let value = self[key] { self[key] = nil return value } return nil } public mutating func appendValue(_ value: Primitive, forKey key: String) { defer { usedCapacity = Int32(self.storage.readableBytes) } func writeKey(_ type: TypeIdentifier) { storage.moveWriterIndex(to: storage.writerIndex - 1) storage.writeInteger(type.rawValue) storage.writeString(key) storage.writeInteger(0x00 as UInt8) } switch value { case let double as Double: // 0x01 writeKey(.double) storage.writeInteger(double.bitPattern, endianness: .little) case let string as String: // 0x02 writeKey(.string) let lengthIndex = storage.writerIndex storage.writeInteger(Int32(0), endianness: .little) storage.writeString(string) storage.writeInteger(0, endianness: .little, as: UInt8.self) let length = storage.writerIndex - 4 - lengthIndex storage.setInteger(Int32(length), at: lengthIndex, endianness: .little) case var document as Document: // 0x03 (embedded document) or 0x04 (array) writeKey(document.isArray ? .array : .document) storage.writeBuffer(&document.storage) case let binary as Binary: // 0x05 writeKey(.binary) storage.writeInteger(Int32(binary.count), endianness: .little) storage.writeInteger(binary.subType.identifier, endianness: .little) var buffer = binary.storage storage.writeBuffer(&buffer) // 0x06 is deprecated case let objectId as ObjectId: // 0x07 writeKey(.objectId) storage.writeInteger(objectId._timestamp, endianness: .big) storage.writeInteger(objectId._random, endianness: .big) case let bool as Bool: // 0x08 writeKey(.boolean) let bool: UInt8 = bool ? 0x01 : 0x00 storage.writeInteger(bool, endianness: .little) case let date as Date: // 0x09 writeKey(.datetime) let milliseconds = Int(date.timeIntervalSince1970 * 1000) storage.writeInteger(milliseconds, endianness: .little) case is Null: // 0x0A writeKey(.null) case let regex as RegularExpression: // 0x0B writeKey(.regex) Swift.assert(!regex.pattern.contains("\0")) Swift.assert(!regex.options.contains("\0")) // string counts + null terminators storage.writeString(regex.pattern) storage.writeInteger(0x00, endianness: .little, as: UInt8.self) storage.writeString(regex.options) storage.writeInteger(0x00, endianness: .little, as: UInt8.self) // 0x0C is deprecated (DBPointer) // 0x0E is deprecated (Symbol) case let int as Int32: // 0x10 writeKey(.int32) storage.writeInteger(int, endianness: .little) case let stamp as Timestamp: writeKey(.timestamp) storage.writeInteger(stamp.increment, endianness: .little) storage.writeInteger(stamp.timestamp, endianness: .little) case let int as _BSON64BitInteger: // 0x12 writeKey(.int64) storage.writeInteger(int, endianness: .little) case let decimal128 as Decimal128: writeKey(.decimal128) storage.writeBytes(decimal128.storage) case is MaxKey: // 0x7F writeKey(.maxKey) case is MinKey: // 0xFF writeKey(.minKey) case let javascript as JavaScriptCode: writeKey(.javascript) let codeLengthWithNull = javascript.code.utf8.count + 1 storage.writeInteger(Int32(codeLengthWithNull), endianness: .little) storage.writeString(javascript.code) storage.writeInteger(0, endianness: .little, as: UInt8.self) case let javascript as JavaScriptCodeWithScope: writeKey(.javascriptWithScope) var scopeBuffer = javascript.scope.makeByteBuffer() let codeLength = javascript.code.utf8.count + 1 // code, null terminator let codeLengthWithHeader = 4 + codeLength let primitiveLength = 4 + codeLengthWithHeader + scopeBuffer.readableBytes // int32(code_w_s size), code, scope doc storage.writeInteger(Int32(primitiveLength), endianness: .little) // header storage.writeInteger(Int32(codeLength), endianness: .little) // string (code) storage.writeString(javascript.code) storage.writeInteger(0, endianness: .little, as: UInt8.self) storage.writeBuffer(&scopeBuffer) case let bsonData as BSONPrimitiveRepresentable: self.appendValue(bsonData.primitive, forKey: key) return default: assertionFailure("Currently unsupported type \(value)") return } storage.writeInteger(0, endianness: .little, as: UInt8.self) } /// Creates a new Document with the given elements public init<S: Sequence>(elements: S, isArray: Bool = false) where S.Element == (String, Primitive) { self.init(isArray: isArray) for (key, value) in elements { self.appendValue(value, forKey: key) } } } extension Dictionary: BSONPrimitiveRepresentable, Primitive where Key == String, Value: Primitive { public var primitive: Primitive { var document = Document(isArray: false) for (key, value) in self { document[key] = value } return document } }
mit
51deb0139754ab96a82d7d17e1d25ee1
35.738095
127
0.57129
4.692347
false
false
false
false
PlanTeam/BSON
Sources/BSON/Types/Decimal128.swift
1
1232
import NIO /// A BSON Decimal128 value /// /// OpenKitten BSON currently does not support the handling of Decimal128 values. The type is a stub and provides no API. It serves as a point for future implementation. public struct Decimal128: Primitive, Hashable { var storage: [UInt8] internal init(_ storage: [UInt8]) { Swift.assert(storage.count == 16) self.storage = storage } public func encode(to encoder: Encoder) throws { let container = encoder.singleValueContainer() if var container = container as? AnySingleValueBSONEncodingContainer { try container.encode(primitive: self) } else { throw UnsupportedDecimal128() } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let container = container as? AnySingleValueBSONDecodingContainer { self = try container.decodeDecimal128() } else { throw UnsupportedDecimal128() } } } fileprivate struct UnsupportedDecimal128: Error { init() {} let message = "Decimal128 did not yet implement Codable using non-BSON encoders" }
mit
499d7f5ec5f191086273806098ca3a7b
29.8
169
0.643669
5.00813
false
false
false
false
donggaizhi/DHAudioPlayer
AudioPlayer/AudioPlayer/DHAudioPlayer/DHAudioPlayUtils.swift
1
3338
// // AudioPlayUtils.swift // AudioPlayer // // Created by MY on 2017/6/8. // Copyright © 2017年 xxoo. All rights reserved. // import UIKit import AVFoundation import MediaPlayer class DHAudioPlayUtils: NSObject { static let share = DHAudioPlayUtils() private override init() {} var beginInterruption : (()->())? var endInterruption : (()->())? var earphoneIn : (()->())? var earphoneOut : (()->())? } extension DHAudioPlayUtils { // 开启后台播放模式 class func setupBackgroundPlayMode() { let session = AVAudioSession.sharedInstance() guard ((try? session.setCategory(AVAudioSessionCategoryPlayback)) != nil), (try? session.setActive(true)) != nil else { return } } // 中断处理 func interruptionDeal(beginInterruption : (()->())?, endInterruption : (()->())? = nil) { self.beginInterruption = beginInterruption self.endInterruption = endInterruption NotificationCenter.default.addObserver(self, selector: #selector(audioSessionInterrupted), name: NSNotification.Name.AVAudioSessionInterruption, object: nil) } @objc fileprivate func audioSessionInterrupted(notification : NSNotification) { guard let userInfo = notification.userInfo , let interruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber, let type = AVAudioSessionInterruptionType(rawValue: interruptionType.uintValue) else { return } switch type { case AVAudioSessionInterruptionType.began: self.beginInterruption?() case AVAudioSessionInterruptionType.ended: self.endInterruption?() } } // 耳机插入拔出处理 func earphoneDeal(earphoneIn : (()->())?, earphoneOut : (()->())? = nil) { NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListenerCallback(notification:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil) self.earphoneIn = earphoneIn self.earphoneOut = earphoneOut } @objc private func audioRouteChangeListenerCallback(notification : Notification) { guard let userInfo = notification.userInfo, let routeChangeReason = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber, let reason = AVAudioSessionRouteChangeReason(rawValue: routeChangeReason.uintValue) else { return } switch reason { case .newDeviceAvailable: // 耳机插入 DispatchQueue.main.sync(execute: { self.earphoneIn?() }) case .oldDeviceUnavailable: // 耳机拔出 DispatchQueue.main.sync(execute: { self.earphoneOut?() }) default: return } } } // MARK: - tools extension DHAudioPlayUtils { class func strTime(seconds : TimeInterval) -> String { var min = Int(seconds) / 60 let sec = Int(seconds) % 60 var hour : Int = 0 if min >= 60 { hour = min / 60 min = min % 60 if hour > 0 { return String(format: "%02d:%02d:%02d", hour, min, sec) } } return String(format: "%02d:%02d", min, sec) } }
mit
7830c818828078fcdb83b91e6b15bbe0
32.804124
188
0.616346
4.79386
false
false
false
false
mrketchup/cooldown
Widget/TodayViewController.swift
1
3017
// // Copyright © 2018 Matt Jones. All rights reserved. // // This file is part of Cooldown. // // Cooldown 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. // // Cooldown 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 Cooldown. If not, see <http://www.gnu.org/licenses/>. // import UIKit import NotificationCenter import Combine import Core_iOS final class TodayViewController: UIViewController { @IBOutlet private var cooldownLabel: UILabel! @IBOutlet private var plusButton: UIButton! private var displayLink: CADisplayLink? private let viewModel = TodayViewController.container.cooldownViewModel() private var cancellables: Set<AnyCancellable> = [] deinit { displayLink?.invalidate() cancellables.forEach { $0.cancel() } } override func viewDidLoad() { super.viewDidLoad() cooldownLabel.font = .monospacedDigitSystemFont(ofSize: 80, weight: .light) displayLink = CADisplayLink(target: self, selector: #selector(refresh)) displayLink?.preferredFramesPerSecond = 4 displayLink?.add(to: RunLoop.main, forMode: .common) let colorAndStyle = viewModel.$primaryColor .map { [unowned self] in ($0, self.traitCollection.userInterfaceStyle) } colorAndStyle .map { UIColor.backgroundColor(from: $0, for: $1, withPreferredDarkBackground: .clear) } .assign(to: \.backgroundColor, on: view) .store(in: &cancellables) let textColor = colorAndStyle .map { UIColor.textColor(from: $0, for: $1) } textColor .assign(to: \.textColor, on: cooldownLabel) .store(in: &cancellables) textColor .assign(to: \.tintColor, on: plusButton) .store(in: &cancellables) viewModel.$timeRemaining .map(Optional.init) .assign(to: \.text, on: cooldownLabel) .store(in: &cancellables) viewModel.redZoneWarning .sink { UINotificationFeedbackGenerator().notificationOccurred(.warning) } .store(in: &cancellables) } @IBAction private func addButtonPressed(_ sender: UIButton) { viewModel.incrementCooldown() } @objc private func refresh() { viewModel.refresh() } } extension TodayViewController: NCWidgetProviding { static let container = Container() func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { completionHandler(.newData) } }
gpl-3.0
6f203e555736ee0f38b66cb92648374a
34.482353
100
0.660809
4.749606
false
false
false
false
sora0077/StatisticsKit
Sources/Statistics.swift
1
2994
// // Statistics.swift // Statistics // // Created by 林 達也 on 2017/02/10. // Copyright © 2017年 林 達也. All rights reserved. // import Foundation public protocol ApplicationHost { var currentVersion: String { get } } public extension ApplicationHost { var currentVersion: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "" } } public protocol Backend { var latestVersion: String? { get } func update(version: String) func write<T>(_ value: T?, forKey key: String) func read<T>(forKey key: String) -> T? func remove(forKey key: String) func removeAll() } private let versionKey = "_Statistics::version" public final class Statistics { public struct Data { private init() {} } private(set) var backend: Backend let current: Version var previous: Version? { return backend.latestVersion.flatMap(Version.init(semanticVersioningString:)) } fileprivate private(set) static var shared: Statistics! private init(backend: Backend, version: String) { self.backend = backend current = Version(semanticVersioningString: version)! } func _key(_ key: String) -> String { return "Statistics::\(current)::\(key)" } private func checkUpdate(once: (_ old: Version?) throws -> Void) rethrows { func doOnceIfNeeded(_ closure: (Version?) throws -> Void) rethrows { guard let old = previous, current <= old else { try closure(previous) return } } try doOnceIfNeeded(once) backend.update(version: current.description) } public static func launch(with backend: Backend, host: ApplicationHost, updated: (_ old: Version?) throws -> Void = { _ in }) rethrows { shared = Statistics(backend: backend, version: host.currentVersion) try shared.checkUpdate(once: updated) } public static func launch(with backend: Backend, host: ApplicationHost, updated: (_ old: Version?) -> Void = { _ in }) { shared = Statistics(backend: backend, version: host.currentVersion) shared.checkUpdate(once: updated) } public static func update<D: StatisticsData>(_ data: D) { shared.backend.update(data, forKey: shared._key(type(of: data).key)) } public static func reset() { shared.backend.removeAll() } public static func reset<D: StatisticsData>(for data: D.Type) { shared.backend.remove(forKey: shared._key(data.key)) } } private extension Backend { func update<D: StatisticsData>(_ data: D, forKey key: String) { write(data.update(old: read(forKey: key)), forKey: key) } } extension StatisticsData { public static var value: Value? { guard let _key = Statistics.shared?._key(key) else { return nil } return Statistics.shared?.backend.read(forKey: _key) } }
mit
7b2a7b55731a7ab31fc987b6c354f8d3
29.090909
140
0.63612
4.237553
false
false
false
false
gregomni/swift
test/AutoDiff/validation-test/property_wrappers.swift
10
5975
// RUN: %target-run-simple-swift // TODO(TF-1254): Support and test forward-mode differentiation. // TODO(TF-1254): %target-run-simple-swift(-Xfrontend -enable-experimental-forward-mode-differentiation) // REQUIRES: executable_test import StdlibUnittest import DifferentiationUnittest var PropertyWrapperTests = TestSuite("PropertyWrapperDifferentiation") @propertyWrapper struct SimpleWrapper<Value> { var wrappedValue: Value // stored property } @propertyWrapper struct Wrapper<Value> { private var value: Value var wrappedValue: Value { // computed property get { value } set { value = newValue } } init(wrappedValue: Value) { self.value = wrappedValue } } struct Struct: Differentiable { @Wrapper @SimpleWrapper var x: Tracked<Float> = 10 @SimpleWrapper @Wrapper var y: Tracked<Float> = 20 var z: Tracked<Float> = 30 } PropertyWrapperTests.test("SimpleStruct") { func getter(_ s: Struct) -> Tracked<Float> { return s.x } expectEqual(.init(x: 1, y: 0, z: 0), gradient(at: Struct(), of: getter)) func setter(_ s: Struct, _ x: Tracked<Float>) -> Tracked<Float> { var s = s s.x = s.x * x * s.z return s.x } expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: Struct(), 2, of: setter)) // TODO(SR-12640): Support `modify` accessors. /* func modify(_ s: Struct, _ x: Tracked<Float>) -> Tracked<Float> { var s = s s.x *= x * s.z return s.x } expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: Struct(), 2, of: modify)) */ } struct GenericStruct<T> { @Wrapper var x: Tracked<Float> = 10 @Wrapper @Wrapper @Wrapper var y: T var z: Tracked<Float> = 30 } extension GenericStruct: Differentiable where T: Differentiable {} PropertyWrapperTests.test("GenericStruct") { func getter<T>(_ s: GenericStruct<T>) -> T { return s.y } expectEqual(.init(x: 0, y: 1, z: 0), gradient(at: GenericStruct<Tracked<Float>>(y: 20), of: getter)) func getter2<T>(_ s: GenericStruct<T>) -> Tracked<Float> { return s.x * s.z } expectEqual(.init(x: 30, y: 0, z: 10), gradient(at: GenericStruct<Tracked<Float>>(y: 20), of: getter2)) func setter<T>(_ s: GenericStruct<T>, _ x: Tracked<Float>) -> Tracked<Float> { var s = s s.x = s.x * x * s.z return s.x } expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: GenericStruct<Tracked<Float>>(y: 20), 2, of: setter)) // TODO(SR-12640): Support `modify` accessors. /* func modify<T>(_ s: GenericStruct<T>, _ x: Tracked<Float>) -> Tracked<Float> { var s = s s.x *= x * s.z return s.x } expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: GenericStruct<Tracked<Float>>(y: 1), 2, of: modify)) */ } // TF-1149: Test class with loadable type but address-only `TangentVector` type. class Class: Differentiable { @differentiable(reverse) @Wrapper @Wrapper var x: Tracked<Float> = 10 @differentiable(reverse) @Wrapper var y: Tracked<Float> = 20 @differentiable(reverse) var z: Tracked<Float> = 30 } PropertyWrapperTests.test("SimpleClass") { func getter(_ c: Class) -> Tracked<Float> { return c.x } expectEqual(.init(x: 1, y: 0, z: 0), gradient(at: Class(), of: getter)) func setter(_ c: Class, _ x: Tracked<Float>) -> Tracked<Float> { var c = c c.x = c.x * x * c.z return c.x } // FIXME(TF-1175): Class operands should always be marked active. // This is relevant for `Class.x.setter`, which has type // `$@convention(method) (@in Tracked<Float>, @guaranteed Class) -> ()`. expectEqual((.init(x: 1, y: 0, z: 0), 0), gradient(at: Class(), 2, of: setter)) /* expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: Class(), 2, of: setter)) */ // TODO(SR-12640): Support `modify` accessors. /* func modify(_ c: Class, _ x: Tracked<Float>) -> Tracked<Float> { var c = c c.x *= x * c.z return c.x } expectEqual((.init(x: 60, y: 0, z: 20), 300), gradient(at: Class(), 2, of: modify)) */ } // From: https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md#proposed-solution // Tests the following functionality: // - Enum property wrapper. @propertyWrapper enum Lazy<Value> { case uninitialized(() -> Value) case initialized(Value) init(wrappedValue: @autoclosure @escaping () -> Value) { self = .uninitialized(wrappedValue) } var wrappedValue: Value { // TODO(TF-1250): Replace with actual mutating getter implementation. // Requires differentiation to support functions with multiple results. get { switch self { case .uninitialized(let initializer): let value = initializer() // NOTE: Actual implementation assigns to `self` here. return value case .initialized(let value): return value } } set { self = .initialized(newValue) } } } // From: https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md#clamping-a-value-within-bounds @propertyWrapper struct Clamping<V: Comparable> { var value: V let min: V let max: V init(wrappedValue: V, min: V, max: V) { value = wrappedValue self.min = min self.max = max assert(value >= min && value <= max) } var wrappedValue: V { get { return value } set { if newValue < min { value = min } else if newValue > max { value = max } else { value = newValue } } } } struct RealPropertyWrappers: Differentiable { @Lazy var x: Float = 3 @Clamping(min: -10, max: 10) var y: Float = 4 } PropertyWrapperTests.test("RealPropertyWrappers") { @differentiable(reverse) func multiply(_ s: RealPropertyWrappers) -> Float { return s.x * s.y } expectEqual(.init(x: 4, y: 3), gradient(at: RealPropertyWrappers(x: 3, y: 4), of: multiply)) } runAllTests()
apache-2.0
92456e138a93fa22930e223b0b7bb6ba
26.036199
128
0.621757
3.457755
false
true
false
false
tinrobots/Mechanica
Sources/StandardLibrary/Sequence+Utils.swift
1
7402
/// A Sequence can be either finite or infinite. extension Sequence { /// **Mechanica** /// /// Checks if all the elements in collection satisfiy the given predicate. /// /// Example: /// /// [2, 2, 4, 4].all(matching: {$0 % 2 == 0}) -> true /// [1, 2, 2, 4].all(matching: {$0 % 2 == 0}) -> false /// /// - Parameter predicate: condition to evaluate each element against. /// - Returns: true when all elements in the array match the specified condition. /// - Attention: the sequence must be finite. public func all(matching predicate: (Element) throws -> Bool) rethrows -> Bool { return try !contains { try !predicate($0) } } /// **Mechanica** /// /// Checks if no elements in collection satisfiy the given predicate. /// /// Example: /// /// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false /// [1, 3, 5].none(matching: {$0 % 2 == 0}) -> true /// /// - Parameter predicate: condition to evaluate each element against. /// - Returns: true when no elements satisfy the specified condition. /// - Attention: the sequence must be finite. public func none(matching predicate: (Element) throws -> Bool) rethrows -> Bool { return try !contains { try predicate($0) } } /// **Mechanica** /// /// Checks if any elements in collection satisfiy the given predicate. /// /// Example: /// /// [2, 2, 4].any(matching: {$0 % 2 == 0}) -> false /// [1, 3, 5, 7].any(matching: {$0 % 2 == 0}) -> true /// /// - Parameter predicate: condition to evaluate each element against. /// - Returns: true when no elements satisfy the specified condition. /// - Attention: the sequence must be finite. public func any(matching predicate: (Element) throws -> Bool) rethrows -> Bool { return try contains { try predicate($0) } } /// **Mechanica** /// /// Returns the last element that satisfies the given predicate, or `nil` if no element does. /// /// Example: /// /// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4 /// /// - Parameter predicate: condition to evaluate each element against. /// - Returns: the last element satisfying the given predicate. (optional) /// - Attention: the sequence must be finite. func last(where predicate: (Element) throws -> Bool) rethrows -> Element? { var result: Element? for element in self { if try predicate(element) { result = element } } return result } /// **Mechanica** /// /// Returns true if there is at least one element satisfying the given predicate. /// - Parameters: /// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Attention: the sequence must be finite. public func hasAny(where predicate: (Element) -> Bool) -> Bool { return first { predicate($0) } != nil } /// **Mechanica** /// /// Returns true if all the elements satisfy the predicate. /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Attention: the sequence must be finite. public func hasAll(where predicate: (Element) -> Bool) -> Bool { return first { !predicate($0) } == nil } /// **Mechanica** /// /// - Parameter criteria: The criteria closure takes an `Element` and returns its classification. /// - Returns: A grouped dictionary with the keys that the criteria function returns. /// - Attention: the sequence must be finite. public func grouped<Key>(by criteria: (Element) -> (Key)) -> [Key: [Element]] { return Dictionary(grouping: self, by: { return criteria($0) }) } /// **Mechanica** /// /// Splits `self` into partitions of a given `length`. /// /// Example: /// /// let string = "Hello" /// string.split(by: 2) -> ["He", "ll", "o"] /// /// - Attention: the sequence must be finite. public func split(by length: Int) -> [[Element]] { guard length != 0 else { return [] } var result: [[Element]] = [] var batch: [Element] = [] for element in self { batch.append(element) if batch.count == length { result.append(batch) batch = [] } } if !batch.isEmpty { result.append(batch) } return result } /// **Mechanica** /// /// Returns a sequence that contains no duplicates according to the generic hash and equality comparisons on the keys reuteruned by the given key generating block. /// If an element occurs multiple times, the later occurrences are discarded /// /// - Parameter keyGenerator: The key generating block. public func distinctElements<Key: Hashable>(by keyGenerator: (Element) -> Key) -> [Element] { var seen = [Key: Bool]() return filter { seen.updateValue(true, forKey: keyGenerator($0)) == nil } } } // MARK: - Equatable extension Sequence where Element: Equatable { /// **Mechanica** /// /// Returns a collection of unique elements preserving their original order. /// - Attention: the sequence must be finite. func uniqueOrderedElements() -> [Element] { var result: [Element] = [] for element in self { if !result.contains(where: { $0 == element }) { result.append(element) } } return result } } // MARK: - Hashable extension Sequence where Element: Hashable { /// **Mechanica** /// /// Returns true if the `Sequence` contains all the given elements. /// /// Example: /// /// [1, 2, 3, 4, 5].contains([1, 2]) -> true /// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true /// /// - Attention: the sequence must be finite. public func contains(_ elements: [Element]) -> Bool { // return Set(elements).isSubset(of: Set(self)) guard !elements.isEmpty else { return true } for element in elements { if !contains(element) { return false } } return true } /// **Mechanica** /// /// Returns a collection of tuples where it's indicated the frequencies of the elements in the sequence. /// - Attention: the sequence must be finite. public var frequencies: [(Element, Int)] { var result = [Element: Int]() for element in self { result[element] = (result[element] ?? 0) + 1 } return result.sorted { $0.1 > $1.1 } } /// **Mechanica** /// /// - Returns: Returns true if the `Sequence` contains duplicates /// - Attention: the sequence must be finite. public func hasDuplicates() -> Bool { var set = Set<Element>() for element in self { if !set.insert(element).inserted { return true } } return false } } // MARK: - AnyObject extension Sequence where Element: AnyObject { /// **Mechanica** /// /// Returns true if the `Sequence` contains an element identical (referential equality) to an `object`. /// - Attention: the sequence must be finite. public func containsObjectIdentical(to object: AnyObject) -> Bool { return contains { $0 === object } } } // MARK: - Numeric extension Sequence where Element: Numeric { /// **Mechanica** /// /// Sums of all elements in array. /// /// Example: /// /// [1, 2, 3, 4].sum() -> 10 /// /// - Attention: the sequence must be finite. public func sum() -> Element { return reduce(0, { $0 + $1 }) } }
mit
e0b29d638d7a801cebc5de401fc4bfbe
29.212245
165
0.610646
3.99892
false
false
false
false
exo-codefest/2015-team-C
mobile-ios/KittenSavior/Views/ILTranslucentView.swift
1
8737
import UIKit class ILTranslucentView: UIView { private var _translucent = true var translucent : Bool { set { _translucent = newValue if self.toolbarBG == nil { return } self.toolbarBG!.translucent = newValue if newValue { self.toolbarBG!.hidden = false self.toolbarBG!.barTintColor = self.ilColorBG self.backgroundColor = UIColor.clearColor() } else { self.toolbarBG!.hidden = true self.backgroundColor = self.ilColorBG } } get { return _translucent } } private var _translucentAlpha : CGFloat = 1.0 public var translucentAlpha : CGFloat { set { if newValue > 1 { _translucentAlpha = 1 } else if (newValue < 0) { _translucentAlpha = 0 } else { _translucentAlpha = newValue } if self.toolbarBG != nil { self.toolbarBG!.alpha = _translucentAlpha } } get { return _translucentAlpha } } var translucentStyle : UIBarStyle { set { if self.toolbarBG != nil { self.toolbarBG!.barStyle = newValue } } get { if self.toolbarBG != nil { return self.toolbarBG!.barStyle } else { return UIBarStyle.Default } } } private var _translucentTintColor = UIColor.clearColor() var translucentTintColor : UIColor { set { _translucentTintColor = newValue if (self.isItClearColor(newValue)) { self.toolbarBG!.barTintColor = self.ilDefaultColorBG } else { self.toolbarBG!.barTintColor = self.translucentTintColor } } get { return _translucentTintColor } } private var ilColorBG : UIColor? private var ilDefaultColorBG : UIColor? private var toolbarBG : UIToolbar? private var nonExistentSubview : UIView? private var toolbarContainerClipView : UIView? private var overlayBackgroundView : UIView? private var initComplete = false override init(frame: CGRect) { super.init(frame: frame) self.createUI() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.createUI() } } extension ILTranslucentView { private func createUI() { self.ilColorBG = self.backgroundColor self.translucent = true self.translucentAlpha = 1 var _nonExistentSubview = UIView(frame: self.bounds) _nonExistentSubview.backgroundColor = UIColor.clearColor() _nonExistentSubview.clipsToBounds = true _nonExistentSubview.autoresizingMask = (UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin) self.nonExistentSubview = _nonExistentSubview self.insertSubview(self.nonExistentSubview, atIndex: 0) var _toolbarContainerClipView = UIView(frame: self.bounds) _toolbarContainerClipView.backgroundColor = UIColor.clearColor() _toolbarContainerClipView.clipsToBounds = true _toolbarContainerClipView.autoresizingMask = (UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin) self.toolbarContainerClipView = _toolbarContainerClipView self.nonExistentSubview!.addSubview(self.toolbarContainerClipView!) var rect = self.bounds rect.origin.y -= 1 rect.size.height += 1 var _toolbarBG = UIToolbar(frame: rect) _toolbarBG.autoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight) self.toolbarBG = _toolbarBG self.toolbarContainerClipView!.addSubview(self.toolbarBG!) self.ilDefaultColorBG = self.toolbarBG!.barTintColor var _overlayBackgroundView = UIView(frame: self.bounds) _overlayBackgroundView.backgroundColor = self.backgroundColor _overlayBackgroundView.autoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight) self.overlayBackgroundView = _overlayBackgroundView self.toolbarContainerClipView!.addSubview(self.overlayBackgroundView!) self.backgroundColor = UIColor.clearColor() self.initComplete = true } private func isItClearColor(color: UIColor) -> Bool { var red : CGFloat = 0.0 var green : CGFloat = 0.0 var blue : CGFloat = 0.0 var alpha : CGFloat = 0.0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return red == 0.0 && green == 0.0 && blue == 0.0 && alpha == 0.0 } @objc override var frame : CGRect { set { if self.toolbarContainerClipView == nil { super.frame = newValue return } var rect = newValue rect.origin = CGPointZero var width = CGRectGetWidth(self.toolbarContainerClipView!.frame) if width > CGRectGetWidth(rect) { rect.size.width = width } var height = CGRectGetHeight(self.toolbarContainerClipView!.frame) if height > CGRectGetHeight(rect) { rect.size.height = height } self.toolbarContainerClipView!.frame = rect super.frame = newValue self.nonExistentSubview!.frame = self.bounds } get { return super.frame } } @objc override var bounds : CGRect { set { var rect = newValue rect.origin = CGPointZero var width = CGRectGetWidth(self.toolbarContainerClipView!.bounds) if width > CGRectGetWidth(rect) { rect.size.width = width } var height = CGRectGetHeight(self.toolbarContainerClipView!.bounds) if height > CGRectGetHeight(rect) { rect.size.height = height } self.toolbarContainerClipView!.bounds = rect super.bounds = newValue self.nonExistentSubview!.frame = self.bounds } get { return super.bounds } } @objc override var backgroundColor : UIColor! { set { if self.initComplete { self.ilColorBG = newValue if (self.translucent) { self.overlayBackgroundView!.backgroundColor = newValue super.backgroundColor = UIColor.clearColor() } } else { super.backgroundColor = self.ilColorBG } } get { return super.backgroundColor } } @objc override var subviews : Array<AnyObject> { if self.initComplete { var array = super.subviews as! Array<UIView> var index = 0 for view in array { if view == self.nonExistentSubview { break } index++ } if index < array.count { array.removeAtIndex(index) } return array } else { return super.subviews } } override func sendSubviewToBack(view: UIView!) { if self.initComplete { self.insertSubview(view, aboveSubview: self.toolbarContainerClipView!) } else { super.sendSubviewToBack(view) } } override func insertSubview(view: UIView!, atIndex index: Int) { if self.initComplete { super.insertSubview(view, atIndex: index + 1) } else { super.insertSubview(view, atIndex: index) } } override func exchangeSubviewAtIndex(index1: Int, withSubviewAtIndex index2: Int) { if self.initComplete { super.exchangeSubviewAtIndex((index1 + 1), withSubviewAtIndex: (index2 + 1)) } else { super.exchangeSubviewAtIndex(index1, withSubviewAtIndex: index2) } } }
lgpl-3.0
3d76ce9c0b0d30e3339e63351fe86708
31.722846
214
0.561863
5.416615
false
false
false
false
loudnate/LoopKit
LoopKit/GlucoseKit/StoredGlucoseSample.swift
1
2572
// // StoredGlucoseSample.swift // LoopKit // // Copyright © 2018 LoopKit Authors. All rights reserved. // import HealthKit public struct StoredGlucoseSample: GlucoseSampleValue { public let sampleUUID: UUID // MARK: - HealthKit Sync Support public let syncIdentifier: String public let syncVersion: Int // MARK: - SampleValue public let startDate: Date public let quantity: HKQuantity // MARK: - GlucoseSampleValue public let isDisplayOnly: Bool public let provenanceIdentifier: String init(sample: HKQuantitySample) { self.init( sampleUUID: sample.uuid, syncIdentifier: sample.metadata?[HKMetadataKeySyncIdentifier] as? String, syncVersion: sample.metadata?[HKMetadataKeySyncVersion] as? Int ?? 1, startDate: sample.startDate, quantity: sample.quantity, isDisplayOnly: sample.isDisplayOnly, provenanceIdentifier: sample.provenanceIdentifier ) } public init( sampleUUID: UUID, syncIdentifier: String?, syncVersion: Int, startDate: Date, quantity: HKQuantity, isDisplayOnly: Bool, provenanceIdentifier: String ) { self.sampleUUID = sampleUUID self.syncIdentifier = syncIdentifier ?? sampleUUID.uuidString self.syncVersion = syncVersion self.startDate = startDate self.quantity = quantity self.isDisplayOnly = isDisplayOnly self.provenanceIdentifier = provenanceIdentifier } } extension StoredGlucoseSample: Equatable, Hashable, Comparable { public static func <(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool { return lhs.startDate < rhs.startDate } public static func ==(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool { return lhs.sampleUUID == rhs.sampleUUID } public func hash(into hasher: inout Hasher) { hasher.combine(sampleUUID) } } extension StoredGlucoseSample { init(managedObject: CachedGlucoseObject) { self.init( sampleUUID: managedObject.uuid!, syncIdentifier: managedObject.syncIdentifier, syncVersion: Int(managedObject.syncVersion), startDate: managedObject.startDate, quantity: HKQuantity(unit: HKUnit(from: managedObject.unitString!), doubleValue: managedObject.value), isDisplayOnly: managedObject.isDisplayOnly, provenanceIdentifier: managedObject.provenanceIdentifier! ) } }
mit
e663e3185d89438064055eecc73b74b8
28.215909
114
0.668611
4.934741
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Groups/AddGroupMember/AddGroupMemberViewController.swift
1
11701
// // CreateGroupsViewController.swift // GetSocialInternalDemo // // Created by Gábor Vass on 09/10/2020. // Copyright © 2020 GrambleWorld. All rights reserved. // import Foundation import UIKit class AddGroupMemberViewController: UIViewController { var onGroupMemberAdded: (() -> Void)? var model: AddGroupMemberModel private let scrollView = UIScrollView() private let userIdLabel = UILabel() private let userIdText = UITextFieldWithCopyPaste() private let providerIdLabel = UILabel() private let providerIdText = UITextFieldWithCopyPaste() private let roleLabel = UILabel() private let roleSegmentedControl = UISegmentedControl() private let statusLabel = UILabel() private let statusSegmentedControl = UISegmentedControl() private let addButton = UIButton(type: .roundedRect) required init(_ groupId: String) { self.model = AddGroupMemberModel(groupId: groupId) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { setup() setupModel() } deinit { NotificationCenter.default.removeObserver(self) } private func setupModel() { self.model.onMemberAdded = { [weak self] in self?.hideActivityIndicatorView() self?.onGroupMemberAdded?() self?.dismiss(animated: true, completion: { self?.showAlert(withText: "Member was added") }) } self.model.onError = { [weak self] error in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Error", andText: "Failed to add member, error: \(error)") } } private func setup() { // setup keyboard observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) self.view.backgroundColor = UIDesign.Colors.viewBackground self.scrollView.translatesAutoresizingMaskIntoConstraints = false self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height + 300) self.view.addSubview(self.scrollView) NSLayoutConstraint.activate([ self.scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor), self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), ]) setupUserIdRow() setupProviderIdRow() setupRoleRow() setupStatusRow() setupAddButton() } private func setupUserIdRow() { self.userIdLabel.translatesAutoresizingMaskIntoConstraints = false self.userIdLabel.text = "User ID" self.userIdLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.userIdLabel) NSLayoutConstraint.activate([ self.userIdLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.userIdLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.userIdLabel.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 8), self.userIdLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.userIdText.translatesAutoresizingMaskIntoConstraints = false self.userIdText.borderStyle = .roundedRect self.userIdText.isEnabled = true self.scrollView.addSubview(self.userIdText) NSLayoutConstraint.activate([ self.userIdText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.userIdText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.userIdText.topAnchor.constraint(equalTo: self.userIdLabel.bottomAnchor, constant: 4), self.userIdText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupProviderIdRow() { self.providerIdLabel.translatesAutoresizingMaskIntoConstraints = false self.providerIdLabel.text = "Provider ID" self.providerIdLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.providerIdLabel) NSLayoutConstraint.activate([ self.providerIdLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.providerIdLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.providerIdLabel.topAnchor.constraint(equalTo: self.userIdText.bottomAnchor, constant: 8), self.providerIdLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.providerIdText.autocapitalizationType = UITextAutocapitalizationType.none self.providerIdText.translatesAutoresizingMaskIntoConstraints = false self.providerIdText.borderStyle = .roundedRect self.scrollView.addSubview(self.providerIdText) NSLayoutConstraint.activate([ self.providerIdText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.providerIdText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.providerIdText.topAnchor.constraint(equalTo: self.providerIdLabel.bottomAnchor, constant: 4), self.providerIdText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupRoleRow() { self.roleLabel.translatesAutoresizingMaskIntoConstraints = false self.roleLabel.text = "Role" self.roleLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.roleLabel) NSLayoutConstraint.activate([ self.roleLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.roleLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.roleLabel.topAnchor.constraint(equalTo: self.providerIdText.bottomAnchor, constant: 8), self.roleLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.roleSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.roleSegmentedControl.insertSegment(withTitle: "Admin", at: 0, animated: false) self.roleSegmentedControl.insertSegment(withTitle: "Member", at: 1, animated: false) self.roleSegmentedControl.selectedSegmentIndex = 0 self.view.addSubview(self.roleSegmentedControl) NSLayoutConstraint.activate([ self.roleSegmentedControl.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.roleSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.roleSegmentedControl.topAnchor.constraint(equalTo: self.roleLabel.bottomAnchor, constant: 8), self.roleSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupStatusRow() { self.statusLabel.translatesAutoresizingMaskIntoConstraints = false self.statusLabel.text = "Status" self.statusLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.statusLabel) NSLayoutConstraint.activate([ self.statusLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.statusLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.statusLabel.topAnchor.constraint(equalTo: self.roleSegmentedControl.bottomAnchor, constant: 8), self.statusLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.statusSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.statusSegmentedControl.insertSegment(withTitle: "Invite", at: 0, animated: false) self.statusSegmentedControl.insertSegment(withTitle: "Member", at: 1, animated: false) self.statusSegmentedControl.insertSegment(withTitle: "Rejected", at: 2, animated: false) self.statusSegmentedControl.selectedSegmentIndex = 0 self.scrollView.addSubview(self.statusSegmentedControl) NSLayoutConstraint.activate([ self.statusSegmentedControl.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.statusSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.statusSegmentedControl.topAnchor.constraint(equalTo: self.statusLabel.bottomAnchor, constant: 8), self.statusSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupAddButton() { self.addButton.translatesAutoresizingMaskIntoConstraints = false self.addButton.setTitle("Add", for: .normal) self.addButton.addTarget(self, action: #selector(executeAdd(sender:)), for: .touchUpInside) self.scrollView.addSubview(self.addButton) NSLayoutConstraint.activate([ self.addButton.topAnchor.constraint(equalTo: self.statusSegmentedControl.bottomAnchor, constant: 8), self.addButton.heightAnchor.constraint(equalToConstant: 40), self.addButton.widthAnchor.constraint(equalToConstant: 100), self.addButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.addButton.bottomAnchor.constraint(greaterThanOrEqualTo: self.scrollView.bottomAnchor, constant: -8) ]) } @objc private func executeAdd(sender: UIView) { guard let userId = self.userIdText.text else { self.showAlert(withText: "UserId cannot be empty") return } var status:MemberStatus switch self.statusSegmentedControl.selectedSegmentIndex { case 0: status = MemberStatus.invitationPending case 1: status = MemberStatus.member case 2: status = MemberStatus.rejected default: status = MemberStatus.member } let role = self.roleSegmentedControl.selectedSegmentIndex == 0 ? Role.admin : Role.member self.showActivityIndicatorView() self.model.addMember(userId: userId, providerId: self.providerIdText.text, role: role, status: status) } // MARK: Handle keyboard @objc private func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo if let keyboardSize = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: keyboardSize.height, right: self.scrollView.contentInset.right) } } @objc private func keyboardWillHide(notification: NSNotification) { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: 0, right: self.scrollView.contentInset.right) } }
apache-2.0
629e7316b1ace2217f354107445c8cb9
45.424603
212
0.6957
5.137901
false
false
false
false
marcosjvivar/WWE-iOS-Code-Test
WWEMobile/Service/DB/DBManager.swift
1
4655
// // DBManager.swift // WWEMobile // // Created by Marcos Jesús Vivar on 8/25/17. // Copyright © 2017 Spark Digital. All rights reserved. // import Foundation import RealmSwift import Realm private let _sharedInstance = DBManager() open class DBManager: NSObject { // MARK: - Instantiation var db: Realm? var currentUser: WWEUser? { if let db = db { let users = db.objects(WWEUser.self) if let user = users.first { return user } } let user = WWEUser() self.saveEntry(user) return user } // MARK: - Instantiation open class var sharedInstance: DBManager { return _sharedInstance } override init() { super.init() do { self.db = try Realm() } catch let error as NSError { NSLog("Error opening realm: \(error)") } } // MARK: - Internal func saveEntry(_ object: Object, isUpdate: Bool? = false) { if let db = db { do { db.beginWrite() db.add(object, update: isUpdate!) try db.commitWrite() } catch let error as NSError { NSLog("### Realm ### Error writing: \(error)") } } } // MARK: - User func getUserProfile() -> WWEUser? { if let user = currentUser { return user } else { let user = WWEUser() self.saveEntry(user) return user } } // MARK: - Recents func getRecents() -> List<WWEVideo>? { return currentUser?.recents } func addRecents(_ newFeed: WWEFeed) { let reversedArray = newFeed.videos.reversed() for video in reversedArray { self.addRecent(video) } } func addRecent(_ newRecentVideo: WWEVideo) { if let user = currentUser, let db = db { do { try db.write({ let recentsNew = user.recents.filter({ (recent) -> Bool in return recent.videoID == newRecentVideo.videoID }) guard recentsNew.count == 0 else { return } if user.recents.count == 20 { user.recents.removeLast() } user.recents.insert(newRecentVideo, at: 0) }) } catch let error as NSError { NSLog("### Realm ### Error writing a new recent : \(error)") } } else { let user = WWEUser() user.recents.append(newRecentVideo) self.saveEntry(user) } } func removeRecent(_ recentVideo: WWEVideo) { if let user = currentUser, let db = db { do { try db.write { if let indexLocation = user.recents.index(of: recentVideo) { user.recents.remove(at: indexLocation) } else { let video = user.recents.filter {($0.videoID == recentVideo.videoID)}[0] if let indexLocation = user.recents.index(of: video) { user.recents.remove(at: indexLocation) } } } } catch let error as NSError { NSLog("### Realm ### Error removing a video: \(error)") } } else { let user = WWEUser() self.saveEntry(user) } } func updateRecent(_ recentVideo: WWEVideo, isLiked: Bool, isDisliked: Bool) { if let user = currentUser, let db = db { do { try db.write { let video = user.recents.filter {($0.videoID == recentVideo.videoID)}[0] let indexLocation = user.recents.index(of: video) recentVideo.isLiked = isLiked recentVideo.isDisliked = isDisliked user.recents.replace(index: indexLocation!, object: recentVideo) } } catch let error as NSError { NSLog("### Realm ### Error updating a favorite : \(error)") } } } // MARK: - Tranforming Objects }
mit
bd6618a2509b0f9e4573f6ee5732b9b8
27.03012
96
0.450032
5.074155
false
false
false
false
bhanubirani/LithiumBook
LithiumBook/LithiumBook/Classes/ViewControllers/LBBooksListViewController.swift
1
1977
// // LBBooksListViewController.swift // LithiumBook // // Created by Bhanu.Birani on 3/10/17. // Copyright © 2017 MB Corp. All rights reserved. // import UIKit class LBBooksListViewController: UIViewController { @IBOutlet weak var bookListTV: UITableView! fileprivate var bookList:[LBBookObject]? fileprivate let bookListInteractor = LBBookListInteractor.sharedInstance override func viewDidLoad() { super.viewDidLoad() self.title = "Books" self.bookListTV.tableFooterView = UIView() bookListInteractor.delegate = self bookListInteractor.fetchBooks() } func pushBookDetail(book: LBBookObject) { let charVC = self.storyboard?.instantiateViewController(withIdentifier: "LBCharactersViewController") as! LBCharactersViewController charVC.bookObject = book self.navigationController?.pushViewController(charVC, animated: true) } } extension LBBooksListViewController: BookListInteractorProtocol { func didRecieveBookList(books: [LBBookObject]) { self.bookList = books; self.bookListTV.reloadData() } } extension LBBooksListViewController: UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.bookList != nil) ? (self.bookList!.count) : 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") let book = self.bookList?[indexPath.row] cell!.textLabel!.text = book?.name return cell! } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.pushBookDetail(book: (self.bookList?[indexPath.row])!) tableView.deselectRow(at: indexPath, animated: true) } }
apache-2.0
bfe18b1badb0ca9fdbe9b25fed318f30
30.365079
140
0.689271
4.761446
false
false
false
false
OscarSwanros/swift
benchmark/utils/TestsUtils.swift
2
6996
//===--- TestsUtils.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// A function that invokes the specific benchmark routine. public var runFunction: (Int) -> () /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: [BenchmarkCategory] /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction: (() -> ())? /// An optional function that if non-null is run immediately after a sample is /// taken. public var tearDownFunction: (() -> ())? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory]) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = nil self.tearDownFunction = nil } public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())?, tearDownFunction: (() -> ())?) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = setUpFunction self.tearDownFunction = tearDownFunction } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public var hashValue: Int { return name.hashValue } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s }
apache-2.0
4921b6ed32ce2b509a67570be3c41c4e
34.51269
92
0.697113
4.490372
false
false
false
false
Ossey/WUO-iOS
WUO/WUO/Classes/DetailPages/TrendDetail/XYTrendDetailController.swift
1
2640
// // XYTrendDetailController.swift // WUO // // Created by mofeini on 17/1/19. // Copyright © 2017年 com.test.demo. All rights reserved. // import UIKit class XYTrendDetailController: XYProfileBaseController { var trendDetailViewModel : XYTrendDetailViewModel? lazy var tableView : XYTrendDetailTableView = { let tableView = XYTrendDetailTableView() return tableView }() init(trendItem: XYTrendItem) { super.init(nibName: nil, bundle: nil) trendDetailViewModel = XYTrendDetailViewModel(item: trendItem, info: trendItem.info) tableView.trendDetailViewModel = trendDetailViewModel } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad(); setupUI() } deinit { print("XYTrendDetailController被销毁") } } // MARK: - 设置UI界面 extension XYTrendDetailController { func setupUI() -> Void { view.addSubview(tableView) tableView.frame = self.view.bounds let rightBtn = UIButton(type: .custom) rightBtn .setImage(UIImage.init(named: "Nav_more"), for: .normal) rightBtn.addTarget(self, action: #selector(moreEvent), for: .touchUpInside) rightBtn.sizeToFit() // 根据当前控制器所在导航控制器是不是XYCustomNavController判断,导航右侧按钮该显示在哪 if navigationController?.classForCoder == XYCustomNavController.self { self.automaticallyAdjustsScrollViewInsets = false tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) // 设置了tableView的contentInset但是并未触发scrollViewDidScroll事件,虽然contentInset没有问题,但是导致初次进入界面时tableView的偏移量不对,所以手动设置tableView.contentOffset tableView.setContentOffset(CGPoint.init(x: 0, y: -64), animated: true) self.xy_rightButton = rightBtn self.xy_topBar.backgroundColor = UIColor.white xy_setBackBarTitle(nil, titleColor: UIColor.black, image: UIImage.init(named: "Login_backSel"), for: .normal) navigationController?.setNavigationBarHidden(true, animated: true) } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn) } } } // MARK: - 事件响应 extension XYTrendDetailController { func moreEvent() -> Void { } }
apache-2.0
fc8ca1cf9213e7994d44e18dc903a7bc
27.011364
143
0.645436
4.564815
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/Avatar.swift
1
761
// // Avatar.swift // Percolator // // Created by Cirno MainasuK on 2015-8-20. // Copyright (c) 2015年 Cirno MainasuK. All rights reserved. // import Foundation import SwiftyJSON struct Avatar { let largeUrl: String let mediumUrl: String let smallUrl: String // Server always return avatar init(avatarDict: [String : JSON]) { largeUrl = avatarDict[BangumiKey.avatarLargeUrl]!.stringValue mediumUrl = avatarDict[BangumiKey.avatarMediumUrl]!.stringValue smallUrl = avatarDict[BangumiKey.avatarSmallUrl]!.stringValue } init(largeURL large: String, mediumURL medium: String, smallURL small: String) { largeUrl = large mediumUrl = medium smallUrl = small } }
mit
e184bf163316f09d21d5e6b4fe8fa93d
23.483871
84
0.666667
3.892308
false
false
false
false
ackratos/firefox-ios
Storage/SQL/SQLiteHistory.swift
4
28429
/* 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 = XCGLogger.defaultInstance() private let LogPII = false class NoSuchRecordError: ErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Result<T>> { if let err = err { log.debug("\(op) failed: \(err.localizedDescription)") return deferResult(DatabaseError(err: err)) } return deferResult(val) } func failOrSucceed(err: NSError?, op: String) -> Success { return failOrSucceed(err, op, ()) } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ func getMicrosecondFrecencySQL(visitDateColumn: String, visitCountColumn: String) -> String { let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "(\(now) - (\(visitDateColumn))) / \(microsecondsPerDay)" return "\(visitCountColumn) * max(1, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } extension SDRow { func getTimestamp(column: String) -> Timestamp? { return (self[column] as? NSNumber)?.unsignedLongLongValue } func getBoolean(column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ public class SQLiteHistory { let db: BrowserDB let favicons: FaviconsTable<Favicon> private var ignoredSchemes = ["about"] required public init(db: BrowserDB) { self.db = db self.favicons = FaviconsTable<Favicon>() db.createOrUpdate(self.favicons) // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. db.createOrUpdate(BrowserTable()) } } extension SQLiteHistory: BrowserHistory { public func removeHistoryForURL(url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)" let markArgs: Args = [NSDate.nowNumber(), url] let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?" return self.db.run(deleteVisits, withArgs: visitArgs) >>> { self.db.run(markDeleted, withArgs: markArgs) } } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. public func clearHistory() -> Success { let s: Site? = nil var err: NSError? = nil db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in err = conn.executeChange("DELETE FROM \(TableVisits)", withArgs: nil) if err == nil { err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil) } if err == nil { err = conn.executeChange("DELETE FROM \(TableHistory)", withArgs: nil) } return 1 } return failOrSucceed(err, "Clear") } private func isIgnoredURL(url: String) -> Bool { if let url = NSURL(string: url) { if let scheme = url.scheme { if let index = find(ignoredSchemes, scheme) { return true } } } return false } func recordVisitedSite(site: Site) -> Success { var error: NSError? = nil // Don't store visits to sites with about: protocols if isIgnoredURL(site.url) { return deferResult(IgnoredSiteError()) } db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in let now = NSDate.nowNumber() // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1 WHERE url = ?" let updateArgs: Args? = [site.title, now, site.url] if LogPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } error = conn.executeChange(update, withArgs: updateArgs) if error != nil { log.warning("Update failed with \(err?.localizedDescription)") return 0 } if conn.numberOfRowsModified > 0 { return conn.numberOfRowsModified } // Insert instead. let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload) VALUES (?, ?, ?, ?, 0, 1)" let insertArgs: Args? = [Bytes.generateGUID(), site.url, site.title, now] error = conn.executeChange(insert, withArgs: insertArgs) if error != nil { log.warning("Insert failed with \(err?.localizedDescription)") return 0 } return 1 } return failOrSucceed(error, "Record site") } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(visit: SiteVisit) -> Success { var error: NSError? = nil db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" + "(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)" let realDate = NSNumber(unsignedLongLong: visit.date) let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] error = conn.executeChange(insert, withArgs: insertArgs) if error != nil { log.warning("Insert visit failed with \(err?.localizedDescription)") return 0 } return 1 } return failOrSucceed(error, "Record visit") } public func addLocalVisit(visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Result<Cursor<Site>>> { let frecencySQL = getMicrosecondFrecencySQL("visitDate", "visitCount") let orderBy = "ORDER BY \(frecencySQL) DESC " return self.getFilteredSitesWithLimit(limit, whereURLContains: nil, orderBy: orderBy, includeIcon: true) } public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Result<Cursor<Site>>> { let frecencySQL = getMicrosecondFrecencySQL("visitDate", "visitCount") let orderBy = "ORDER BY \(frecencySQL) DESC " return self.getFilteredSitesWithLimit(limit, whereURLContains: filter, orderBy: orderBy, includeIcon: true) } public func getSitesByLastVisit(limit: Int) -> Deferred<Result<Cursor<Site>>> { let orderBy = "ORDER BY visitDate DESC " return self.getFilteredSitesWithLimit(limit, whereURLContains: nil, orderBy: orderBy, includeIcon: true) } private class func basicHistoryColumnFactory(row: SDRow) -> Site { let id = row["historyID"] as! Int let url = row["url"] as! String let title = row["title"] as! String let guid = row["guid"] as! String let site = Site(url: url, title: title) site.guid = guid site.id = id if let visitDate = row.getTimestamp("visitDate") { site.latestVisit = Visit(date: visitDate, type: VisitType.Unknown) } return site } private class func iconHistoryColumnFactory(row: SDRow) -> Site { let site = basicHistoryColumnFactory(row) if let iconType = row["iconType"] as? Int, let iconURL = row["iconURL"] as? String, let iconDate = row["iconDate"] as? Double, let iconID = row["iconID"] as? Int { let date = NSDate(timeIntervalSince1970: iconDate) let icon = Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!) site.icon = icon } return site } private func getFilteredSitesWithLimit(limit: Int, whereURLContains filter: String?, orderBy: String, includeIcon: Bool) -> Deferred<Result<Cursor<Site>>> { let args: Args? let whereClause: String if let filter = filter { args = ["%\(filter)%", "%\(filter)%"] // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " } else { args = [] whereClause = " WHERE (\(TableHistory).is_deleted = 0)" } let historySQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, " + "max(\(TableVisits).date) AS visitDate, " + "count(\(TableVisits).date) AS visitCount " + "FROM \(TableHistory) INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + whereClause + "GROUP BY \(TableHistory).id " + orderBy + "LIMIT \(limit) " if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = "SELECT " + "historyID, url, title, guid, visitDate, visitCount " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM (\(historySQL)) LEFT OUTER JOIN " + "view_history_id_favicon ON historyID = view_history_id_favicon.id" let factory = SQLiteHistory.iconHistoryColumnFactory return db.runQuery(sql, args: args, factory: factory) } let factory = SQLiteHistory.basicHistoryColumnFactory return db.runQuery(historySQL, args: args, factory: factory) } } extension SQLiteHistory: Favicons { public func clearFavicons() -> Success { var err: NSError? = nil db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil) if err == nil { err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil) } return 1 } return failOrSucceed(err, "Clear favicons") } public func addFavicon(icon: Favicon) -> Deferred<Result<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) return id ?? 0 } if err == nil { return deferResult(res) } return deferResult(DatabaseError(err: err)) } /** * This method assumes that the site has already been recorded * in the history table. */ public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Result<Int>> { if LogPII { log.verbose("Adding favicon \(icon.url) for site \(site.url).") } func doChange(query: String, args: Args?) -> Deferred<Result<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) // Now set up the mapping. err = conn.executeChange(query, withArgs: args) if let err = err { log.error("Got error adding icon: \(err).") return 0 } // Try to update the favicon ID column in the bookmarks table as well for this favicon // if this site has been bookmarked if let id = id { conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url]) } return id ?? 0 } if res == 0 { return deferResult(DatabaseError(err: err)) } return deferResult(icon.id!) } let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)" let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)" let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES " if let iconID = icon.id { // Easy! if let siteID = site.id { // So easy! let args: Args? = [siteID, iconID] return doChange("\(insertOrIgnore) (?, ?)", args) } // Nearly easy. let args: Args? = [site.url, iconID] return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args) } // Sigh. if let siteID = site.id { let args: Args? = [siteID, icon.url] return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args) } // The worst. let args: Args? = [site.url, icon.url] return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args) } // Fails on non-existence. private func getSiteIDForGUID(guid: GUID) -> Deferred<Result<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: SDRow -> Int = { return $0["id"] as! Int } return db.runQuery(query, args: args, factory: factory) >>== { cursor in if cursor.count == 0 { return deferResult(NoSuchRecordError(guid: guid)) } return deferResult(cursor[0]!) } } public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = NSNumber(unsignedLongLong: visit.date) let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } private struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } private func metadataForGUID(guid: GUID) -> Deferred<Result<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return db.runQuery(select, args: args, factory: factory) >>== { cursor in return deferResult(cursor[0]) } } public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Result<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = NSNumber(unsignedLongLong: modified) // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Result<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.debug("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferResult(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if metadata.localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } log.debug("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.debug("Updating local history item for guid \(place.guid).") let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.debug("Inserting remote history item for guid \(place.guid).") if LogPII { log.debug("Inserting: \(place.url).") } let insert = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload) VALUES (?, ?, ?, ?, 0, 0)" let args: Args = [place.guid, place.url, place.title, serverModified] return self.db.run(insert, withArgs: args) >>> always(place.guid) } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Result<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1" let f: SDRow -> String = { $0["guid"] as! String } return self.db.runQuery(sql, args: nil, factory: f) >>== { deferResult($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Result<[(Place, [Visit])]>> { // What we want to do: find all items flagged for update, selecting some number of their // visits alongside. // // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem in SQL. Please read and understand the solution // to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query! // // We can do this in a single query, rather than the N+1 that desktop takes. // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. let args: Args = [ 20, // Maximum number of visits to retrieve. ] // Exclude 'unknown' visits, because they're not syncable. let filter = "history.should_upload = 1 AND v1.type IS NOT 0" let sql = "SELECT " + "history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " + "v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " + "FROM " + "visits AS v1 " + "JOIN history ON history.id = v1.siteID AND \(filter) " + "LEFT OUTER JOIN " + "visits AS v2 " + "ON v1.siteID = v2.siteID AND v1.date < v2.date " + "GROUP BY v1.date " + "HAVING COUNT(*) < ? " + "ORDER BY v1.siteID, v1.date DESC" var places = [Int: Place]() var visits = [Int: [Visit]]() // Add a place to the accumulator, prepare to accumulate visits, return the ID. let ensurePlace: SDRow -> Int = { row in let id = row["siteID"] as! Int if places[id] == nil { let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) visits[id] = Array() } return id } // Store the place and the visit. let factory: SDRow -> Int = { row in let date = row.getTimestamp("visitDate")! let type = VisitType(rawValue: row["visitType"] as! Int)! let visit = Visit(date: date, type: type) let id = ensurePlace(row) visits[id]?.append(visit) return id } return db.runQuery(sql, args: args, factory: factory) >>== { c in // Consume every row, with the side effect of populating the places // and visit accumulators. let count = c.count var ids = Set<Int>() for row in c { // Collect every ID first, so that we're guaranteed to have // fully populated the visit lists, and we don't have to // worry about only collecting each place once. ids.insert(row!) } // Now we're done with the cursor. Close it. c.close() // Now collect the return value. return deferResult(map(ids, { return (places[$0]!, visits[$0]!) })) } } public func markAsDeleted(guids: [GUID]) -> Success { // TODO: support longer GUID lists. assert(guids.count < BrowserDB.MaxVariableNumber) if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM \(TableHistory) WHERE " + "is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) } public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> { // TODO: support longer GUID lists. assert(guids.count < 99) if guids.isEmpty { return deferResult(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") let inClause = BrowserDB.varlist(guids.count) let sql = "UPDATE \(TableHistory) SET " + "should_upload = 0, server_modified = \(modified) " + "WHERE guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) >>> always(modified) } public func onRemovedAccount() -> Success { log.info("Clearing history metadata after account removal.") let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1" let flag = "UPDATE \(TableHistory) SET " + "should_upload = 1, server_modified = NULL " return self.db.run(discard) >>> { self.db.run(flag) } } }
mpl-2.0
6abb30037395d18af3831002c2e4ad7b
40.992614
160
0.583594
4.602396
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Tools/MTLTexture+UIImage.swift
1
3620
// // MTLTexture+UIImage.swift // Pods // // Created by Mohssen Fathi on 9/11/16. // // import Foundation import Metal extension MTLTexture { // func image() -> UIImage? { // // let bytesPerPixel: Int = 4 // let imageByteCount = width * height * bytesPerPixel // let bytesPerRow = width * bytesPerPixel // var src = [UInt8](repeating: 0, count: Int(imageByteCount)) // // let region = MTLRegionMake2D(0, 0, width, height) // getBytes(&src, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0) // // let bitmapInfo = CGBitmapInfo(rawValue: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue)) // // let grayColorSpace = CGColorSpaceCreateDeviceRGB() // let bitsPerComponent = 8 // let context = CGContext(data: &src, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: grayColorSpace, bitmapInfo: bitmapInfo.rawValue); // // let dstImageFilter = context!.makeImage(); // // return UIImage(cgImage: dstImageFilter!, scale: 0.0, orientation: UIImageOrientation.downMirrored) // // } func bytes() -> UnsafeMutableRawPointer? { // guard pixelFormat == .rgba8Unorm else { return nil } let imageByteCount: Int = width * height * 4 guard let imageBytes = UnsafeMutableRawPointer(malloc(imageByteCount)) else { return nil } let bytesPerRow = width * 4 let region: MTLRegion = MTLRegionMake2D(0, 0, width, height) getBytes(imageBytes, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0) return imageBytes } var image: UIImage? { guard let imageBytes = bytes() else { return nil } let bytesPerRow = width * 4 let imageByteCount: Int = width * height * 4 let provider = CGDataProvider(dataInfo: nil, data: imageBytes, size: imageByteCount) { (rawPointer, pointer, i) in } let bitsPerComponent = 8 let bitsPerPixel = 32 let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: CGBitmapInfo! if pixelFormat == .bgra8Unorm { bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue).union(.byteOrder32Little) } else if pixelFormat == .rgba8Unorm { bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).union(.byteOrder32Big) } else { return nil } let renderingIntent = CGColorRenderingIntent.defaultIntent let imageRef = CGImage(width: width, height: height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: false, intent: renderingIntent) let image = UIImage(cgImage: imageRef!, scale: 0.0, orientation: .up) // free(imageBytes) return image; } func copy(device: MTLDevice) -> MTLTexture { let data = bytes()! let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height, mipmapped: false) let copy = device.makeTexture(descriptor: descriptor) copy?.replace(region: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0, withBytes: data, bytesPerRow: MemoryLayout<Float>.size * width) free(data) return copy! } }
mit
64f8063a01037f4d056c275b89fb413b
37.510638
278
0.639227
4.763158
false
false
false
false
clappr/clappr-ios
Sources/Clappr_tvOS/Classes/Base/Player.swift
1
12185
import AVKit @objcMembers open class Player: AVPlayerViewController { private var layerComposer = LayerComposer() open var playbackEventsToListen: [String] = [] private var playbackEventsListenIds: [String] = [] private(set) var core: Core? static var hasAlreadyRegisteredPlaybacks = false private let baseObject = BaseObject() public var chromelessMode: Bool { get { core?.options.bool(kChromeless) ?? false } set { core?.options[kChromeless] = newValue if newValue { enterChromelessMode() } else { exitChromelessMode() } } } private var nextFocusViewTag: Int? private var nextFocusEnvironment: UIFocusEnvironment? { guard let nextFocusViewTag = nextFocusViewTag else { return nil } return core?.view.viewWithTag(nextFocusViewTag) } override open func viewDidLoad() { super.viewDidLoad() core?.parentView = view if chromelessMode { enterChromelessMode() } if isMediaControlEnabled { core?.parentView = contentOverlayView core?.parentController = self } core?.trigger(.didAttachView) NotificationCenter.default.addObserver(self, selector: #selector(Player.willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) core?.render() } open var isMediaControlEnabled: Bool { return core?.options[kMediaControl] as? Bool ?? false } @objc private func willEnterForeground() { if let playback = activePlayback as? AVFoundationPlayback, !isMediaControlEnabled || chromelessMode { Logger.logDebug("forced play after return from background", scope: "Player") playback.play() } } override open var preferredFocusEnvironments: [UIFocusEnvironment] { if let nextFocusEnvironment = nextFocusEnvironment, nextFocusEnvironment.isFocusable { return [nextFocusEnvironment] } return super.preferredFocusEnvironments } public var focusEnvironments: [UIView] { contentOverlayView?.subviews.first?.subviews ?? [] } open override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool { true } open var activeContainer: Container? { return core?.activeContainer } open var activePlayback: Playback? { return core?.activePlayback } open var isFullscreen: Bool { guard let core = core else { return false } return core.isFullscreen } open var state: PlaybackState { return activePlayback?.state ?? .none } open var duration: Double { return activePlayback?.duration ?? 0 } open var position: Double { return activePlayback?.position ?? 0 } open var subtitles: [MediaOption]? { return activePlayback?.subtitles } open var audioSources: [MediaOption]? { return activePlayback?.audioSources } open var selectedSubtitle: MediaOption? { get { return activePlayback?.selectedSubtitle } set { activePlayback?.selectedSubtitle = newValue } } open var selectedAudioSource: MediaOption? { get { return activePlayback?.selectedAudioSource } set { activePlayback?.selectedAudioSource = newValue } } public init(options: Options = [:], externalPlugins: [Plugin.Type] = []) { super.init(nibName: nil, bundle: nil) Player.register(playbacks: []) Player.register(plugins: externalPlugins) Logger.logInfo("loading with \(options)", scope: "Clappr") playbackEventsToListen.append(contentsOf: [Event.ready.rawValue, Event.playing.rawValue, Event.didComplete.rawValue, Event.didPause.rawValue, Event.stalling.rawValue, Event.didStop.rawValue, Event.didUpdateBuffer.rawValue, Event.willPlay.rawValue, Event.didUpdatePosition.rawValue, Event.willPause.rawValue, Event.willStop.rawValue, Event.willSeek.rawValue, Event.didUpdateAirPlayStatus.rawValue, Event.didSeek.rawValue, Event.didFindSubtitle.rawValue, Event.didFindAudio.rawValue, Event.didSelectSubtitle.rawValue, Event.didSelectAudio.rawValue, Event.didUpdateBitrate.rawValue] ) setCore(with: options) bindCoreEvents() bindPlaybackEvents() core?.load() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setCore(with options: Options) { core = CoreFactory.create(with: options, layerComposer: layerComposer) } private func bindCoreEvents() { core?.on(Event.willChangeActivePlayback.rawValue) { [weak self] _ in self?.unbindPlaybackEvents() } core?.on(Event.didChangeActivePlayback.rawValue) { [weak self] _ in self?.bindPlaybackEvents() } core?.on(Event.didEnterFullscreen.rawValue) { [weak self] (info: EventUserInfo) in self?.forward(.requestFullscreen, userInfo: info) } core?.on(Event.didExitFullscreen.rawValue) { [weak self] (info: EventUserInfo) in self?.forward(.exitFullscreen, userInfo: info) } core?.on(Event.requestFocus.rawValue) { [weak self] (info: EventUserInfo) in self?.requestFocus(userInfo: info) } core?.on(Event.releaseFocus.rawValue) { [weak self] (info: EventUserInfo) in self?.releaseFocus(userInfo: info) } } private func requestFocus(userInfo: EventUserInfo) { guard let viewTag = userInfo?["viewTag"] as? Int, self.nextFocusViewTag == nil else { return } self.nextFocusViewTag = viewTag updateFocus() } private func releaseFocus(userInfo: EventUserInfo) { guard let viewTag = userInfo?["viewTag"] as? Int, self.nextFocusViewTag == viewTag else { return } self.nextFocusViewTag = nil updateFocus() } private func updateFocus() { setNeedsFocusUpdate() updateFocusIfNeeded() } open func load(_ source: String, mimeType: String? = nil) { guard let core = core else { return } let newOptions = core.options.merging([kSourceUrl: source, kMimeType: mimeType as Any], uniquingKeysWith: { _, second in second }) configure(options: newOptions) play() } open func configure(options: Options) { core?.options = options core?.load() } open func play() { activePlayback?.play() } open func pause() { activePlayback?.pause() } open func stop() { activePlayback?.stop() } open func seek(_ timeInterval: TimeInterval) { activePlayback?.seek(timeInterval) } open func mute(enabled: Bool) { activePlayback?.mute(enabled) } open func setFullscreen(_ fullscreen: Bool) { core?.setFullscreen(fullscreen) } open var options: Options? { return core?.options } open func getPlugin(name: String) -> Plugin? { var plugins: [Plugin] = core?.plugins ?? [] let containerPlugins: [Plugin] = activeContainer?.plugins ?? [] plugins.append(contentsOf: containerPlugins) return plugins.first(where: { $0.pluginName == name }) } @discardableResult open func on(_ event: Event, callback: @escaping EventCallback) -> String { return baseObject.on(event.rawValue, callback: callback) } @discardableResult public func on(_ eventName: String, callback: @escaping EventCallback) -> String { return baseObject.on(eventName, callback: callback) } open func trigger(_ eventName: String) { baseObject.trigger(eventName) } open func trigger(_ eventName: String, userInfo: EventUserInfo) { baseObject.trigger(eventName, userInfo: userInfo) } @discardableResult open func listenTo<T: EventProtocol>(_ contextObject: T, eventName: String, callback: @escaping EventCallback) -> String { return baseObject.listenTo(contextObject, eventName: eventName, callback: callback) } @discardableResult open func listenToOnce<T: EventProtocol>(_ contextObject: T, eventName: String, callback: @escaping EventCallback) -> String { return baseObject.listenToOnce(contextObject, eventName: eventName, callback: callback) } private func bindPlaybackEvents() { guard let playback = core?.activePlayback else { return } var listenId = "" playbackEventsToListen.forEach { event in listenId = listenTo(playback, eventName: event) { [weak self] (info: EventUserInfo) in self?.baseObject.trigger(event, userInfo: info) } playbackEventsListenIds.append(listenId) } listenId = listenToOnce(playback, eventName: Event.playing.rawValue, callback: { [weak self] _ in self?.bindPlayer(playback: playback) }) playbackEventsListenIds.append(listenId) listenId = listenTo(playback, eventName: Event.error.rawValue) { [weak self] info in self?.trigger(Event.error.rawValue, userInfo: self?.fillErrorWith(info)) } playbackEventsListenIds.append(listenId) } open func fillErrorWith(_ userInfo: EventUserInfo) -> EventUserInfo { return userInfo } private func bindPlayer(playback: Playback?) { if let avFoundationPlayback = (playback as? AVFoundationPlayback), let player = avFoundationPlayback.player { self.player = player delegate = avFoundationPlayback } } private func unbindPlaybackEvents() { for eventId in playbackEventsListenIds { baseObject.stopListening(eventId) } playbackEventsListenIds.removeAll() } open class func register(playbacks: [Playback.Type]) { if !hasAlreadyRegisteredPlaybacks { Loader.shared.register(playbacks: [AVFoundationPlayback.self]) hasAlreadyRegisteredPlaybacks = true } Loader.shared.register(playbacks: playbacks) } open class func register(plugins: [Plugin.Type]) { Loader.shared.register(plugins: plugins) } private func forward(_ event: Event, userInfo: EventUserInfo) { baseObject.trigger(event.rawValue, userInfo: userInfo) } private func enterChromelessMode() { showsPlaybackControls = false view.isUserInteractionEnabled = false contentOverlayView?.isHidden = true } private func exitChromelessMode() { showsPlaybackControls = true view.isUserInteractionEnabled = true contentOverlayView?.isHidden = false } open func destroy() { Logger.logDebug("destroying", scope: "Player") baseObject.stopListening() Logger.logDebug("destroying core", scope: "Player") core?.destroy() Logger.logDebug("destroying viewController", scope: "Player") destroyViewController() Logger.logDebug("destroyed", scope: "Player") } private func destroyViewController() { willMove(toParent: nil) view.removeFromSuperview() removeFromParent() } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if presentedViewController == nil { destroy() } } deinit { NotificationCenter.default.removeObserver(self) } } extension Player { private var isPaused: Bool { return activePlayback?.state == .paused } private var isPlaying: Bool { return activePlayback?.state == .playing } open override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { if presses.containsAny(pressTypes: [.select, .playPause]) && isPaused { activePlayback?.trigger(.willPlay) } super.pressesBegan(presses, with: event) } }
bsd-3-clause
d2e8482b02e334fc4b82f0bfe26e4696
30.649351
145
0.644891
4.812401
false
false
false
false
MailOnline/Reactor
ReactorTests/Tests/CacheTests.swift
1
1099
// // CacheTests.swift // Reactor // // Created by Rui Peres on 14/03/2016. // Copyright © 2016 Mail Online. All rights reserved. // import XCTest @testable import Reactor class CacheTests: XCTestCase { func testSetGet() { let cache = Cache<Article>() let article = Article(title: "Hello", body: "Body", authors: [], numberOfLikes: 1) cache[article.hashValue] = article XCTAssertEqual(cache[article.hashValue], article) } func testRemoveAll() { let cache = Cache<Article>() let article = Article(title: "Hello", body: "Body", authors: [], numberOfLikes: 1) cache[article.hashValue] = article cache.removeAll() XCTAssertEqual(cache.count, 0) } func testAll() { let cache = Cache<Article>() let article = Article(title: "Hello", body: "Body", authors: [], numberOfLikes: 1) cache[article.hashValue] = article let all = cache.all() XCTAssertEqual(all, [article]) } }
mit
0f0ac316da12bfa3444a1014ffbdaa34
23.4
90
0.564663
4.392
false
true
false
false
litt1e-p/LPScrollFullScreen-swift
LPScrollFullScreen-swiftSample/LPScrollFullScreen-swift/LPScrollFullScreen-swift/UIViewControllerExtension.swift
2
8342
// The MIT License (MIT) // // Copyright (c) 2015-2016 litt1e-p ( https://github.com/litt1e-p ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit let IOS7_OR_LATER = (UIDevice.currentDevice().systemVersion as NSString).doubleValue >= 7.0 let IOS8_OR_LATER = (UIDevice.currentDevice().systemVersion as NSString).doubleValue >= 8.0 let kNearZero = CGFloat(0.000001) extension UIViewController { func showNavigationBar(animated:Bool) { let statusBarHeight = self.statusBarHeight() let appKeyWindow = UIApplication.sharedApplication().keyWindow let appBaseView = appKeyWindow?.rootViewController?.view let viewControllerFrame = appBaseView?.convertRect((appBaseView?.bounds)!, toView: appKeyWindow) let overwrapStatusBarHeight = statusBarHeight - (viewControllerFrame?.origin.y)! self.setNavigationBarOriginY(overwrapStatusBarHeight, animated: animated) } private func statusBarHeight() -> CGFloat { let statuBarFrameSize = UIApplication.sharedApplication().statusBarFrame.size if IOS8_OR_LATER { return statuBarFrameSize.height } return UIApplication.sharedApplication().statusBarOrientation == .Portrait ? statuBarFrameSize.height : statuBarFrameSize.width } func hideNavigationBar(animated:Bool) { let statusBarHeight = self.statusBarHeight() let appKeyWindow = UIApplication.sharedApplication().keyWindow let appBaseView = appKeyWindow?.rootViewController?.view let viewControllerFrame = appBaseView?.convertRect((appBaseView?.bounds)!, toView: appKeyWindow) let overwrapStatusBarHeight = statusBarHeight - (viewControllerFrame?.origin.y)! let navigationBarHeight = self.navigationController?.navigationBar.frame.size.height let top = IOS7_OR_LATER ? -CGFloat(navigationBarHeight!) + overwrapStatusBarHeight : -CGFloat(navigationBarHeight!) self.setNavigationBarOriginY(top, animated: animated) } func moveNavigationBar(deltaY: CGFloat, animated: Bool) { let frame = self.navigationController?.navigationBar.frame let nextY = (frame?.origin.y)! + deltaY self.setNavigationBarOriginY(nextY, animated: animated) } func setNavigationBarOriginY(y: CGFloat, animated: Bool) { let statusBarHeight = self.statusBarHeight() let appKeyWindow = UIApplication.sharedApplication().keyWindow let appBaseView = appKeyWindow?.rootViewController?.view let viewControllerFrame = appBaseView?.convertRect((appBaseView?.bounds)!, toView: appKeyWindow) let overwrapStatusBarHeight = statusBarHeight - (viewControllerFrame?.origin.y)! var frame = self.navigationController?.navigationBar.frame let navigationBarHeight = frame?.size.height let topLimit = IOS7_OR_LATER ? -CGFloat(navigationBarHeight!) + CGFloat(overwrapStatusBarHeight) : -CGFloat(navigationBarHeight!) let bottomLimit = overwrapStatusBarHeight frame?.origin.y = fmin(fmax(y, topLimit), bottomLimit) let navBarHiddenRatio = overwrapStatusBarHeight > 0 ? (overwrapStatusBarHeight - (frame?.origin.y)!) / overwrapStatusBarHeight : 0 let alpha = max(1.0 - navBarHiddenRatio, kNearZero) UIView.animateWithDuration(animated ? 0.1 : 0.0) { () -> Void in self.navigationController?.navigationBar.frame = frame! var index = 0 for view: UIView in (self.navigationController?.navigationBar.subviews)! { index += 1 if index == 1 || view.hidden || view.alpha <= 0.0 { continue } view.alpha = alpha } if IOS7_OR_LATER { if let tintColor = self.navigationController?.navigationBar.tintColor { self.navigationController?.navigationBar.tintColor = tintColor.colorWithAlphaComponent(alpha) } } } } func showToolbar(animated: Bool) { let viewSize = self.navigationController?.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize!) let toolbarHeight = self.navigationController?.toolbar.frame.size.height self.setToolbarOriginY(viewHeight - toolbarHeight!, animated: animated) } private func bottomBarViewControlleViewHeightFromViewSize(viewSize: CGSize) -> CGFloat { var viewHeight: CGFloat = 0.0 if IOS8_OR_LATER { viewHeight = viewSize.height } else { viewHeight = UIApplication.sharedApplication().statusBarOrientation == .Portrait ? viewSize.height : viewSize.width } return viewHeight } func hideToolbar(animated: Bool) { let viewSize = self.navigationController?.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize!) self.setToolbarOriginY(viewHeight, animated: animated) } func moveToolbar(deltaY: CGFloat, animated: Bool) { let frame = self.navigationController?.toolbar.frame let nextY = (frame?.origin.y)! + deltaY self.setToolbarOriginY(nextY, animated: animated) } func setToolbarOriginY(y: CGFloat, animated: Bool) { var frame = self.navigationController?.toolbar.frame let toolBarHeight = frame?.size.height let viewSize = self.navigationController!.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize) let topLimit = viewHeight - toolBarHeight! let bottomLimit = viewHeight frame?.origin.y = fmin(fmax(y, topLimit), bottomLimit) UIView.animateWithDuration(animated ? 0.1 : 0) { () -> Void in self.navigationController?.toolbar.frame = frame! } } func showTabBar(animated: Bool) { let viewSize = self.tabBarController?.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize!) let toolbarHeight = self.tabBarController?.tabBar.frame.size.height self.setTabBarOriginY(viewHeight - toolbarHeight!, animated: animated) } func hideTabBar(animated: Bool) { let viewSize = self.tabBarController?.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize!) self.setTabBarOriginY(viewHeight, animated: animated) } func moveTabBar(deltaY: CGFloat, animated: Bool) { let frame = self.tabBarController?.tabBar.frame let nextY = (frame?.origin.y)! + deltaY self.setTabBarOriginY(nextY, animated: animated) } func setTabBarOriginY(y: CGFloat, animated: Bool) { var frame = self.tabBarController!.tabBar.frame let toolBarHeight = frame.size.height let viewSize = self.tabBarController!.view.frame.size let viewHeight = self.bottomBarViewControlleViewHeightFromViewSize(viewSize) let topLimit = viewHeight - toolBarHeight let bottomLimit = viewHeight frame.origin.y = fmin(fmax(y, topLimit), bottomLimit) UIView.animateWithDuration(animated ? 0.1 : 0.0) { () -> Void in self.tabBarController!.tabBar.frame = frame } } }
mit
ac8948b596887a018964fc37be728add
48.360947
138
0.695277
4.855646
false
false
false
false
dreamsxin/swift
test/IDE/complete_doc_keyword.swift
4
2627
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE1 | FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER1 | FileCheck %s -check-prefix=MEMBER1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER2 | FileCheck %s -check-prefix=MEMBER2 /** - keyword: C1, Class - recommended: C2 */ class C1 { /** - keyword: v1, Int - recommended: v2 */ var v1 : Int = 0 /** - keyword: v2, Int - recommendedover: v1 */ var v2 : Int = 0 /** - keyword: f1, func - recommended: f2 */ func f1() {} /** - keyword: f2, func - recommendedover: f1 */ func f2() {} } /** - keyword: C2, Class - recommendedover: C1 */ class C2 {} /** - keyword: S1, Struct - recommendedover: S2 */ struct S1 {} /** - keyword: S2, Struct - recommended: S1 */ struct S2 {} /** - keyword: E1, Enum - recommended: E2 */ enum E1{} /** - keyword: E2, Enum - recommendedover: E1 */ enum E2{} /** - keyword: S3, Struct */ struct S3 { /** - nonmutatingvariant: fooing */ mutating func foo() {} /** - mutatingvariant: foo */ func fooing() -> S3 {} } func foo1() { #^TYPE1^# // TYPE1: Begin completions // TYPE1-DAG: Decl[Class]/CurrModule/keyword[C1, Class]/recommended[C2]: C1[#C1#] // TYPE1-DAG: Decl[Struct]/CurrModule/keyword[S1, Struct]/recommendedover[S2]: S1[#S1#] // TYPE1-DAG: Decl[Enum]/CurrModule/keyword[E2, Enum]/recommendedover[E1]: E2[#E2#] // TYPE1-DAG: Decl[Struct]/CurrModule/keyword[S2, Struct]/recommended[S1]: S2[#S2#] // TYPE1-DAG: Decl[Class]/CurrModule/keyword[C2, Class]/recommendedover[C1]: C2[#C2#] // TYPE1-DAG: Decl[Enum]/CurrModule/keyword[E1, Enum]/recommended[E2]: E1[#E1#] // TYPE1-DAG: Decl[Struct]/CurrModule/keyword[S3, Struct]: S3[#S3#] } func foo2() { let c = C1() c.#^MEMBER1^# // MEMBER1: Begin completions // MEMBER1-NEXT: Decl[InstanceVar]/CurrNominal/keyword[v1, Int]/recommended[v2]: v1[#Int#] // MEMBER1-NEXT: Decl[InstanceVar]/CurrNominal/keyword[v2, Int]/recommendedover[v1]: v2[#Int#] // MEMBER1-NEXT: Decl[InstanceMethod]/CurrNominal/keyword[f1, func]/recommended[f2]: f1()[#Void#] // MEMBER1-NEXT: Decl[InstanceMethod]/CurrNominal/keyword[f2, func]/recommendedover[f1]: f2()[#Void#] } func foo3() { let s = S3() s.#^MEMBER2^# // MEMBER2: Begin completions // MEMBER2-NEXT: Decl[InstanceMethod]/CurrNominal/nonmutatingvariant[fooing]: foo()[#Void#] // MEMBER2-NEXT: Decl[InstanceMethod]/CurrNominal/mutatingvariant[foo]: fooing()[#S3#] }
apache-2.0
2fc7911175e2127af9f245a18e7e649e
23.324074
135
0.650933
2.93192
false
false
false
false
DavidSteuber/QRTest
QRTest/ViewController.swift
1
1957
// // ViewController.swift // QRTest // // Created by David Steuber on 4/4/15. // Copyright (c) 2015 David Steuber. // import UIKit import CoreImage class ViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var image: UIImageView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if let uiimage = image { let code = UIImage.qrCodeWithMessage("https://www.david-steuber.com") uiimage.image = code?.scaleQRCodeWithNoInterpolation(200) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITextFieldDelegate Methods. All of them are optional. func textFieldShouldBeginEditing(textField: UITextField) -> Bool { print("textFieldShouldBeginEditing called") return true } func textFieldDidBeginEditing(textField: UITextField) { print("textFieldDidBeginEditing called") } func textFieldShouldEndEditing(textField: UITextField) -> Bool { print("textFieldShouldEndEditing called") return true } func textFieldDidEndEditing(textField: UITextField) { print("textFieldDidEndEditing called") } func textFieldShouldClear(textField: UITextField) -> Bool { print("textFieldShouldClear called") textField.resignFirstResponder() return true } func textFieldShouldReturn(textField: UITextField) -> Bool { print("textFieldShouldReturn called") if let text = textField.text { print(text) let code = UIImage.qrCodeWithMessage(text) image.image = code?.scaleQRCodeWithNoInterpolation(200) } textField.resignFirstResponder() return true } }
unlicense
e634ad7d81122898368fc50bc7c5cf6a
28.208955
81
0.669903
5.346995
false
false
false
false
MyBar/MyBarMusic
MyBarMusic/MyBarMusic/Classes/Player/Controller/MBPlayerViewController.swift
1
12704
// // MBPlayerViewController.swift // MyBarMusic // // Created by lijingui2010 on 2017/7/8. // Copyright © 2017年 MyBar. All rights reserved. // import UIKit import Kingfisher class MBPlayerViewController: UIViewController, UIScrollViewDelegate { var scrollView: UIScrollView? var backgroudImageView: UIImageView? lazy var playerManager: MBPlayerManager = AppDelegate.delegate.playerManager lazy var playerControlPadView: MBPlayerControlPadView! = MBPlayerControlPadView.playerControlPadView lazy var playerAlbumCoverView: MBPlayerAlbumCoverView! = MBPlayerAlbumCoverView.playerAlbumCoverView var timer: Timer? //界面刷新定时器 var isAddTimer = false var albumCoverRotationAngle: CGFloat = 0.0 init(albumCoverRotationAngle: CGFloat) { super.init(nibName: nil, bundle: nil) self.albumCoverRotationAngle = albumCoverRotationAngle } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.setupBlurEffectForBackgroudImage() self.setupNavigation() self.setupScrollView() self.setupPlayerControlPadView() self.addTimer() //监听状态变化 NotificationCenter.default.addObserver(self, selector: #selector(self.observePlayerManagerStatus(_:)), name: NSNotification.Name("playerManagerStatus"), object: nil) NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: self.albumCoverRotationAngle) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.updateBlurEffectForBackgroudImage() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name("playerManagerStatus"), object: nil) self.playerAlbumCoverView.removeAnimation() self.removeTimer() } func setupBlurEffectForBackgroudImage() { self.backgroudImageView = UIImageView() self.backgroudImageView!.frame = self.view.bounds self.view.addSubview(self.backgroudImageView!) let effectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light)) effectView.frame = self.backgroudImageView!.bounds self.backgroudImageView!.addSubview(effectView) } func setupNavigation() { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() let color = UIColor.white let dict=[NSForegroundColorAttributeName: color] self.navigationController?.navigationBar.titleTextAttributes = dict; self.navigationItem.title = "QQ音乐,听我想听的歌" let leftBarButton = UIButton(type: UIButtonType.custom) leftBarButton.setBackgroundImage(UIImage(named: "player_btn_close_normal")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for: UIControlState.normal) leftBarButton.setBackgroundImage(UIImage(named: "player_btn_close_highlight")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for: UIControlState.highlighted) leftBarButton.frame.size = leftBarButton.currentBackgroundImage!.size leftBarButton.addTarget(self, action: #selector(MBPlayerViewController.clickNavigationBarButtonItemAction(_:)), for: UIControlEvents.touchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBarButton) let rightBarButton = UIButton(type: UIButtonType.custom) rightBarButton.setBackgroundImage(UIImage(named: "player_btn_more_normal")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for: UIControlState.normal) rightBarButton.setBackgroundImage(UIImage(named: "player_btn_more_highlight")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for: UIControlState.highlighted) rightBarButton.frame.size = rightBarButton.currentBackgroundImage!.size rightBarButton.addTarget(self, action: #selector(MBPlayerViewController.clickNavigationBarButtonItemAction(_:)), for: UIControlEvents.touchUpInside) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButton) } func setupScrollView() { self.automaticallyAdjustsScrollViewInsets = false let navigationBarAndStatusBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height var frame = self.view.bounds frame.origin.y = navigationBarAndStatusBarHeight frame.size.height = frame.size.height - navigationBarAndStatusBarHeight - self.playerControlPadView!.frame.height self.scrollView = UIScrollView(frame: frame) self.scrollView!.bounces = false self.scrollView!.isPagingEnabled = true self.scrollView!.showsHorizontalScrollIndicator = false self.scrollView?.backgroundColor = UIColor.clear self.scrollView!.delegate = self let width = self.scrollView!.frame.width let height = self.scrollView!.frame.height self.scrollView?.contentSize = CGSize(width: 3 * width, height: 0) for index in 0..<3 { switch index { case 0: let imageView = UIImageView(frame: CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)) imageView.image = UIImage(named: "Welcome_3.0_\(index + 1)") self.scrollView?.addSubview(imageView) case 1: self.playerAlbumCoverView.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height) self.playerAlbumCoverView.setupAlbumCoverView() self.scrollView?.addSubview(self.playerAlbumCoverView) case 2: let imageView = UIImageView(frame: CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)) imageView.image = UIImage(named: "Welcome_3.0_\(index + 1)") self.scrollView?.addSubview(imageView) default: print("No this Page of Index: \(index)") } } self.scrollView!.contentOffset.x = self.scrollView!.frame.width self.view.addSubview(self.scrollView!) } func setupPlayerControlPadView() { self.playerControlPadView!.backgroundColor = UIColor.clear self.view.addSubview(self.playerControlPadView!) } func clickNavigationBarButtonItemAction(_ sender: UIButton) { if sender == self.navigationItem.leftBarButtonItem?.customView { print("leftBarButtonItem") self.navigationController?.dismiss(animated: true, completion: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name("playerManagerStatus"), object: nil) self.playerAlbumCoverView.pauseAnimation() NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: self.playerAlbumCoverView.rotationAngle) } else if sender == self.navigationItem.rightBarButtonItem?.customView { print("rightBarButtonItem") } } /** UIScrollViewDelegate */ func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentPage = Int(scrollView.contentOffset.x / scrollView.frame.width + 0.5) self.playerControlPadView?.updatePageControlCurrentPage(currentPage) } } extension MBPlayerViewController { func observePlayerManagerStatus(_ notification: Notification) { let rotationAngle = (notification.object as? CGFloat) ?? self.playerAlbumCoverView.rotationAngle switch self.playerManager.playerManagerStatus { case .playing: print("MBPlayerViewController.playerManager.playerManagerStatus = playing") self.playerAlbumCoverView.initAnimation(with: rotationAngle) self.playerAlbumCoverView.resumeAnimation() if self.isAddTimer == false { self.addTimer() } case .paused: print("MBPlayerViewController.playerManager.playerManagerStatus = paused") self.playerAlbumCoverView.initAnimation(with: rotationAngle) self.playerAlbumCoverView.pauseAnimation() self.removeTimer() self.refreshUI() case .stopped: print("MBPlayerViewController.playerManager.playerManagerStatus = stopped") self.playerAlbumCoverView.removeAnimation() self.removeTimer() self.refreshUI() case .loadSongModel: print("MBPlayerViewController.playerManager.playerManagerStatus = loadSongModel") self.playerAlbumCoverView.updateAlbumCoverView(with: nil) self.updateBlurEffectForBackgroudImage() case .unknown: print("MBPlayerViewController.playerManager.playerManagerStatus = unknown") case .readyToPlay: print("MBPlayerViewController.playerManager.playerManagerStatus = readyToPlay") self.playerAlbumCoverView.initAnimation(with: rotationAngle) if self.isAddTimer == false { self.addTimer() } case .failed: print("MBPlayerViewController.playerManager.playerManagerStatus = failed") case .none: print("MBPlayerViewController.playerManager.playerManagerStatus = none") } } //#pragma mark - 定时器 func addTimer() { guard self.timer == nil else { return } print("======== addTimer - 定时器 =========") self.timer = Timer.scheduledTimer(timeInterval: 1.0 / 20.0, target: self, selector: #selector(self.refreshUI), userInfo: nil, repeats: true) RunLoop.main.add(self.timer!, forMode: RunLoopMode.commonModes) self.isAddTimer = true } func removeTimer() { guard self.timer != nil else { return } print("======== removeTimer - 定时器 =========") self.timer?.invalidate() self.timer = nil self.isAddTimer = false } func refreshUI() { self.navigationItem.title = self.playerManager.currentSongInfoModel?.title ?? "QQ音乐,听我想听的歌" if let artistName = self.playerManager.currentSongInfoModel?.artist_name { self.playerAlbumCoverView.singerLabel.text = "一 \(artistName) 一" } else { self.playerAlbumCoverView.singerLabel.text = nil } self.playerControlPadView.refreshProgress() } func updateBlurEffectForBackgroudImage() { guard self.backgroudImageView != nil else { return } var effectView: UIVisualEffectView! for subview in self.backgroudImageView!.subviews { if let view = (subview as? UIVisualEffectView) { effectView = view effectView.effect = UIBlurEffect(style: UIBlurEffectStyle.light) } } if let urlStr = self.playerManager.currentSongInfoModel?.pic_big { self.backgroudImageView?.kf.setImage(with: URL(string: urlStr), placeholder: UIImage(named: "player_albumblur_default"), options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, url) in effectView.effect = UIBlurEffect(style: UIBlurEffectStyle.dark) self.playerAlbumCoverView.updateAlbumCoverView(with: image) }) } else { effectView.effect = UIBlurEffect(style: UIBlurEffectStyle.light) self.backgroudImageView?.image = UIImage(named: "player_albumblur_default") } } }
mit
4cfa8d7a7c196b37ca61f1307881e0e5
37.821538
221
0.63779
5.45718
false
false
false
false
sugar2010/SwiftOptimizer
swix/twoD/twoD-simple-math.swift
2
3603
// // twoD-math.swift // swix // // Created by Scott Sievert on 7/10/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func apply_function(function: matrix->matrix, x: matrix2d)->matrix2d{ var y = function(x.flat) var z = zeros_like(x) z.flat = y return z } func sin(x: matrix2d) -> matrix2d{ return apply_function(sin, x) } func cos(x: matrix2d) -> matrix2d{ return apply_function(cos, x) } func tan(x: matrix2d) -> matrix2d{ return apply_function(tan, x) } func log(x: matrix2d) -> matrix2d{ return apply_function(log, x) } func abs(x: matrix2d) -> matrix2d{ return apply_function(abs, x) } func sqrt(x: matrix2d) -> matrix2d{ return apply_function(sqrt, x) } func floor(x: matrix2d) -> matrix2d{ return apply_function(floor, x) } func ceil(x: matrix2d) -> matrix2d{ return apply_function(ceil, x) } func round(x: matrix2d) -> matrix2d{ return apply_function(round, x) } func sign(x: matrix2d) -> matrix2d{ var y = apply_function(sign, x.flat) var z = zeros_like(x) z.flat = y return z } func randn(N: (Int, Int), mean: Double=0, sigma: Double=1) -> matrix2d{ var x = zeros(N) for i in 0..<x.n{ x.flat[i] = randn() } var y = (x * sigma) + mean; return y } func rand(N: (Int, Int)) -> matrix2d{ var x = zeros(N) for i in 0..<x.n{ x.flat[i] = rand() } return x } func pow(x: matrix2d, power: Double) -> matrix2d{ var y = pow(x.flat, power) var z = zeros_like(x) z.flat = y return z } func min(x: matrix2d, absValue:Bool=false)-> Double{ return min(x.flat, absValue:absValue) } func max(x: matrix2d, absValue:Bool=false)-> Double{ return max(x.flat, absValue:absValue) } func norm(x: matrix2d, type:String="l2") -> Double{ if type=="l0"{ return norm(x.flat, type:"l0")} if type=="l1"{ return norm(x.flat, type:"l1")} if type=="l2"{ return norm(x.flat, type:"l2")} assert(false, "type of norm unrecongnized") return -1.0 } //func pow(x: matrix, power: Double) -> matrix{ // var y = zeros(x.count) // for i in 0..<x.count{ // y[i] = pow(x[i], power) // } // return y //} func sum(x: matrix2d, dim:Int=0) -> matrix{ // arg dim: indicating what dimension you want to sum over. For example, if dim==0, then it'll sum over dimension 0 -- it will add all the numbers in the 0th dimension, x[0..<x.shape.0, i] var dimen:Int if dim==1{ dimen = x.shape.1 var y = zeros(dimen) for i in 0..<dimen{ y[i] = sum(x[0..<x.shape.0, i]) } return y } else if dim==0{ dimen = x.shape.0 var y = zeros(dimen) for i in 0..<dimen{ y[i] = sum(x[i, 0..<x.shape.1]) } return y } assert(false, "Argument `dim` not recongnized") return zeros(1) } //func avg(x: matrix) -> Double{ // var y: Double = sum(x) // // return y / x.count.double //} //func std(x: matrix) -> Double{ // var y: Double = avg(x) // var z = x - y // return sqrt(sum(pow(z, 2) / x.count.double)) //} ///// variance used since var is a keyword //func variance(x: matrix) -> Double{ // var y: Double = avg(x) // var z = x - y // return sum(pow(z, 2) / x.count.double) //} //func cumsum(x: matrix) -> matrix{ // let N = x.count // var y = zeros(N) // for i in 0..<N{ // if i==0 { y[i] = x[0] } // else if i==1 { y[i] = x[0] + x[1] } // else { y[i] = x[i] + y[i-1] } // } // return y //}
mit
79d4a1fc0b9f7444f36055d53aaae93e
22.245161
192
0.559811
2.719245
false
false
false
false